repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
laser-turtle/ogaml
|
src/graphics/stubs/texture_stubs.c
|
<gh_stars>10-100
#define GL_GLEXT_PROTOTYPES
#if defined(_WIN32)
#include <windows.h>
#include <gl/glew.h>
#endif
#if defined(__APPLE__)
#include <OpenGL/gl3.h>
#ifndef GL_TESS_CONTROL_SHADER
#define GL_TESS_CONTROL_SHADER 0x00008e88
#endif
#ifndef GL_TESS_EVALUATION_SHADER
#define GL_TESS_EVALUATION_SHADER 0x00008e87
#endif
#ifndef GL_PATCHES
#define GL_PATCHES 0x0000000e
#endif
#else
#include <GL/gl.h>
#endif
#include <caml/bigarray.h>
#include <string.h>
#include "utils.h"
#include "types_stubs.h"
#define TEX(_a) (*(GLuint*) Data_custom_val(_a))
#define MLvar_Minify (254173077)
#define MLvar_Magnify (-1011094397)
#define MLvar_Wrap (1940966357)
void finalise_tex(value v)
{
glDeleteTextures(1,&TEX(v));
}
int compare_tex(value v1, value v2)
{
GLuint i1 = TEX(v1);
GLuint i2 = TEX(v2);
if(i1 < i2) return -1;
else if(i1 == i2) return 0;
else return 1;
}
intnat hash_tex(value v)
{
GLuint i = TEX(v);
return i;
}
static struct custom_operations tex_custom_ops = {
"texture GC handling",
finalise_tex,
compare_tex,
hash_tex,
custom_serialize_default,
custom_deserialize_default
};
// INPUT nothing
// OUTPUT a fresh texture id
CAMLprim value
caml_create_texture(value unit)
{
CAMLparam0();
CAMLlocal1(v);
GLuint buf[1];
glGenTextures(1, buf);
v = caml_alloc_custom( &tex_custom_ops, sizeof(GLuint), 0, 1);
memcpy( Data_custom_val(v), buf, sizeof(GLuint) );
CAMLreturn(v);
}
// INPUT a binding point and a texture id option
// OUTPUT nothing, binds the texture
CAMLprim value
caml_bind_texture(value point, value tex_opt)
{
CAMLparam2(point, tex_opt);
if(tex_opt == Val_none)
glBindTexture(Target_val(point), 0);
else
glBindTexture(Target_val(point), TEX(Some_val(tex_opt)));
CAMLreturn(Val_unit);
}
// INPUT an int (texture location)
// OUTPUT nothing, activates the texture location
CAMLprim value
caml_activate_texture(value loc)
{
CAMLparam1(loc);
glActiveTexture(GL_TEXTURE0 + Int_val(loc));
CAMLreturn(Val_unit);
}
// INPUT a texture target, a level, a pixel format, a size, a texture format, some data
// OUTPUT nothing, binds an image to the current texture2D
CAMLprim value
caml_tex_image_2D_native(value target, value lvl, value fmt, value size, value tfmt, value data)
{
CAMLparam5(target, fmt, size, tfmt, data);
CAMLxparam1(lvl);
glTexImage2D(Target_val(target),
Int_val(lvl),
TextureFormat_val(tfmt),
Int_val(Field(size,0)),
Int_val(Field(size,1)),
0,
PixelFormat_val(fmt),
GL_UNSIGNED_BYTE,
(data == Val_none)? NULL : String_val(Some_val(data)));
CAMLreturn(Val_unit);
}
CAMLprim value
caml_tex_image_2D_bytecode(value *argv, int argn)
{
return caml_tex_image_2D_native(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
}
// INPUT a texture target, a level, an offset, a size, a pixel format, some data
// OUTPUT nothing, binds an subimage to the current texture2D
CAMLprim value
caml_tex_subimage_2D_native(value target, value lvl, value off, value size, value fmt, value data)
{
CAMLparam5(target, lvl, off, size, fmt);
CAMLxparam1(data);
glTexSubImage2D(Target_val(target),
Int_val(lvl),
Int_val(Field(off,0)),
Int_val(Field(off,1)),
Int_val(Field(size,0)),
Int_val(Field(size,1)),
PixelFormat_val(fmt),
GL_UNSIGNED_BYTE,
String_val(data));
CAMLreturn(Val_unit);
}
CAMLprim value
caml_tex_subimage_2D_bytecode(value *argv, int argn)
{
return caml_tex_subimage_2D_native(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
}
// INPUT a texture target, a number of mipmaps, a texture format, a texture size
// OUTPUT nothing, allocates the space for a texture2D
CAMLprim value
caml_tex_storage_2D(value target, value lvls, value tfmt, value size)
{
CAMLparam4(target,lvls,tfmt,size);
glTexStorage2D(Target_val(target),
Int_val(lvls),
TextureFormat_val(tfmt),
Int_val(Field(size,0)),
Int_val(Field(size,1)));
CAMLreturn(Val_unit);
}
// INPUT a texture target, a level, a pixel format, a size, a texture format, some data
// OUTPUT nothing, binds an image to the current texture3D
CAMLprim value
caml_tex_image_3D_native(value target, value lvl, value fmt, value size, value tfmt, value data)
{
CAMLparam5(target, fmt, size, tfmt, data);
CAMLxparam1(lvl);
glTexImage3D(Target_val(target),
Int_val(lvl),
TextureFormat_val(tfmt),
Int_val(Field(size,0)),
Int_val(Field(size,1)),
Int_val(Field(size,2)),
0,
PixelFormat_val(fmt),
GL_UNSIGNED_BYTE,
(data == Val_none)? NULL : String_val(Some_val(data)));
CAMLreturn(Val_unit);
}
CAMLprim value
caml_tex_image_3D_bytecode(value *argv, int argn)
{
return caml_tex_image_3D_native(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
}
// INPUT a texture target, a level, an offset, a size, a pixel format, some data
// OUTPUT nothing, binds an subimage to the current texture3D
CAMLprim value
caml_tex_subimage_3D_native(value target, value lvl, value off, value size, value fmt, value data)
{
CAMLparam5(target, lvl, off, size, fmt);
CAMLxparam1(data);
glTexSubImage3D(Target_val(target),
Int_val(lvl),
Int_val(Field(off,0)),
Int_val(Field(off,1)),
Int_val(Field(off,2)),
Int_val(Field(size,0)),
Int_val(Field(size,1)),
Int_val(Field(size,2)),
PixelFormat_val(fmt),
GL_UNSIGNED_BYTE,
String_val(data));
CAMLreturn(Val_unit);
}
CAMLprim value
caml_tex_subimage_3D_bytecode(value *argv, int argn)
{
return caml_tex_subimage_3D_native(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
}
// INPUT a texture target, a number of mipmaps, a texture format, a texture size
// OUTPUT nothing, allocates the space for a texture3D
CAMLprim value
caml_tex_storage_3D(value target, value lvls, value tfmt, value size)
{
CAMLparam4(target,lvls,tfmt,size);
glTexStorage3D(Target_val(target),
Int_val(lvls),
TextureFormat_val(tfmt),
Int_val(Field(size,0)),
Int_val(Field(size,1)),
Int_val(Field(size,2)));
CAMLreturn(Val_unit);
}
// INPUT a variant containing the texture type and a min/mag filter
// OUTPUT nothing, sets the texture parameter
CAMLprim value
caml_tex_parameter(value typ, value loc)
{
CAMLparam2(typ, loc);
if(Field(loc, 0) == MLvar_Magnify)
glTexParameteri(Target_val(typ), GL_TEXTURE_MAG_FILTER, Magnify_val(Field(loc, 1)));
else if(Field(loc, 0) == MLvar_Minify)
glTexParameteri(Target_val(typ), GL_TEXTURE_MIN_FILTER, Minify_val(Field(loc, 1)));
else if(Field(loc, 0) == MLvar_Wrap) {
glTexParameteri(Target_val(typ), GL_TEXTURE_WRAP_S, Wrap_val(Field(loc, 1)));
glTexParameteri(Target_val(typ), GL_TEXTURE_WRAP_R, Wrap_val(Field(loc, 1)));
glTexParameteri(Target_val(typ), GL_TEXTURE_WRAP_T, Wrap_val(Field(loc, 1)));
}
else {
caml_failwith("Caml polymorphic variant error in tex_parameter_2D(1)");
}
CAMLreturn(Val_unit);
}
// INPUT a texture ID
// OUTPUT nothing, deletes the texture
CAMLprim value
caml_destroy_texture(value id)
{
CAMLparam1(id);
glDeleteTextures(1, &TEX(id));
CAMLreturn(Val_unit);
}
|
laser-turtle/ogaml
|
src/graphics/stubs/text_stubs.c
|
<reponame>laser-turtle/ogaml
#include <caml/bigarray.h>
#include "utils.h"
#define STB_TRUETYPE_IMPLEMENTATION
#include "stb_truetype.h"
CAMLprim value
caml_stb_load_font(value filename)
{
CAMLparam1(filename);
long size;
unsigned char* fontBuffer;
FILE* fontFile = fopen(String_val(filename), "rb");
stbtt_fontinfo* info;
fseek(fontFile, 0, SEEK_END);
size = ftell(fontFile);
fseek(fontFile, 0, SEEK_SET);
fontBuffer = malloc(size);
fread(fontBuffer, size, 1, fontFile);
fclose(fontFile);
info = malloc(sizeof(stbtt_fontinfo));
if (stbtt_InitFont(info, fontBuffer, 0) == 0)
info = NULL;
CAMLreturn((value)info);
}
CAMLprim value
caml_stb_isvalid(value info)
{
CAMLparam1(info);
CAMLreturn(Val_bool((stbtt_fontinfo*)info != NULL));
}
CAMLprim value
caml_stb_kern_advance(value info, value c1, value c2)
{
CAMLparam3(info, c1, c2);
CAMLreturn(
Val_int(
stbtt_GetCodepointKernAdvance((stbtt_fontinfo*)info,
Int_val(c1),
Int_val(c2))
)
);
}
CAMLprim value
caml_stb_scale(value info, value px)
{
CAMLparam2(info, px);
CAMLreturn(
caml_copy_double(
stbtt_ScaleForPixelHeight((stbtt_fontinfo*)info,
Int_val(px))
)
);
}
CAMLprim value
caml_stb_metrics(value info)
{
CAMLparam1(info);
CAMLlocal1(res);
int ascent, descent, linegap;
stbtt_GetFontVMetrics((stbtt_fontinfo*)info, &ascent, &descent, &linegap);
res = caml_alloc(3, 0);
Store_field(res, 0, Val_int(ascent));
Store_field(res, 1, Val_int(descent));
Store_field(res, 2, Val_int(linegap));
CAMLreturn(res);
}
CAMLprim value
caml_stb_hmetrics(value info, value code)
{
CAMLparam2(info, code);
int advance, bearing;
stbtt_GetCodepointHMetrics((stbtt_fontinfo*)info, Int_val(code), &advance, &bearing);
CAMLreturn(Int_pair(advance,bearing));
}
CAMLprim value
caml_stb_box(value info, value code)
{
CAMLparam2(info, code);
CAMLlocal1(res);
int x0, y0, x1, y1;
if(!stbtt_GetCodepointBox((stbtt_fontinfo*)info, Int_val(code), &x0, &y0, &x1, &y1)) {
x0 = 0;
y0 = 0;
x1 = 0;
y1 = 0;
}
res = caml_alloc(4,0);
Store_field(res, 0, Val_int(x0));
Store_field(res, 1, Val_int(y0));
Store_field(res, 2, Val_int(x1 - x0));
Store_field(res, 3, Val_int(y1 - y0));
CAMLreturn(res);
}
CAMLprim value
caml_stb_bitmap(value info, value code, value scale)
{
CAMLparam3(info, code, scale);
CAMLlocal2(res, bmp);
int width, height, xoff, yoff;
unsigned char* bitmap = stbtt_GetCodepointBitmap((stbtt_fontinfo*)info,
Double_val(scale),
Double_val(scale),
Int_val(code),
&width,
&height,
&xoff,
&yoff);
if(!bitmap) {
width = 0;
height = 0;
}
res = caml_alloc(3,0);
bmp = caml_alloc_string(width * height);
memcpy(String_val(bmp), bitmap, width * height);
Store_field(res, 0, bmp);
Store_field(res, 1, Val_int(width));
Store_field(res, 2, Val_int(height));
if(bitmap)
stbtt_FreeBitmap(bitmap, NULL);
CAMLreturn(res);
}
CAMLprim value
caml_stb_render_bitmap(value info, value code, value oversampling, value scale)
{
CAMLparam4(info, code, oversampling, scale);
CAMLlocal2(res, bmp);
stbtt_fontinfo* stb_info = (stbtt_fontinfo*)info;
int stb_code = Int_val(code);
int stb_oversampling = Int_val(oversampling);
float stb_scale = Double_val(scale);
int ix0, iy0, ix1, iy1;
int w,h;
int width, height;
unsigned char* bitmap;
stbtt_GetCodepointBitmapBox(stb_info,
stb_code,
stb_scale * stb_oversampling,
stb_scale * stb_oversampling,
&ix0,
&iy0,
&ix1,
&iy1);
w = ix1 - ix0;
h = iy1 - iy0;
width = w + stb_oversampling - 1;
height = h + stb_oversampling - 1;
bitmap = malloc(width * height * sizeof(char));
memset(bitmap, 0, width * height);
stbtt_MakeCodepointBitmap(stb_info,
bitmap,
w,
h,
width,
stb_scale * stb_oversampling,
stb_scale * stb_oversampling,
stb_code);
if(stb_oversampling > 1) {
stbtt__h_prefilter(bitmap,
width,
height,
width,
stb_oversampling);
stbtt__v_prefilter(bitmap,
width,
height,
width,
stb_oversampling);
}
res = caml_alloc(3,0);
bmp = caml_alloc_string(width * height);
memcpy(String_val(bmp), bitmap, width * height);
free(bitmap);
Store_field(res, 0, bmp);
Store_field(res, 1, Val_int(width));
Store_field(res, 2, Val_int(height));
CAMLreturn(res);
}
|
laser-turtle/ogaml
|
src/core/windows/stubs/window_stubs.c
|
<reponame>laser-turtle/ogaml
#include "utils.h"
#include <windows.h>
#include <Windowsx.h>
#include <memory.h>
value* callback_get_window_from_id;
value* callback_push_event_to_window;
value getModifiers()
{
CAMLparam0();
CAMLlocal1(res);
res = caml_alloc(4,0);
Store_field(res,0,Val_bool(HIWORD(GetAsyncKeyState(VK_SHIFT)) != 0));
Store_field(res,1,Val_bool(HIWORD(GetAsyncKeyState(VK_CONTROL)) != 0));
Store_field(res,2,Val_bool(HIWORD(GetAsyncKeyState(VK_CAPITAL)) != 0));
Store_field(res,3,Val_bool(HIWORD(GetAsyncKeyState(VK_MENU)) != 0));
CAMLreturn(res);
}
value processEvent(UINT message, WPARAM wParam, LPARAM lParam)
{
CAMLparam0();
CAMLlocal3(res,res_field,modifiers);
int x,y,dt,button;
switch(message)
{
case WM_CLOSE:
{
res = Val_int(1);
break;
}
case WM_SIZE:
{
res = caml_alloc(1,0);
Store_field(res, 0, Val_bool(wParam != SIZE_MINIMIZED));
break;
}
case WM_ENTERSIZEMOVE:
{
res = Val_int(2);
break;
}
case WM_EXITSIZEMOVE:
{
res = Val_int(3);
break;
}
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
{
res = caml_alloc(2,1);
if(wParam >=65 && wParam <= 90) {
res_field = caml_alloc(1,1);
Store_field(res_field,0,Val_int(wParam));
} else {
res_field = caml_alloc(1,0);
Store_field(res_field,0,Val_int(wParam));
}
modifiers = getModifiers();
Store_field(res, 0, res_field);
Store_field(res, 1, modifiers);
break;
}
case WM_KEYUP:
case WM_SYSKEYUP:
{
res = caml_alloc(2,2);
if(wParam >=65 && wParam <= 90) {
res_field = caml_alloc(1,1);
Store_field(res_field,0,Val_int(wParam));
} else {
res_field = caml_alloc(1,0);
Store_field(res_field,0,Val_int(wParam));
}
modifiers = getModifiers();
Store_field(res, 0, res_field);
Store_field(res, 1, modifiers);
break;
}
case WM_MOUSEWHEEL:
{
res = caml_alloc(4,3);
x = GET_X_LPARAM(lParam);
y = GET_Y_LPARAM(lParam);
dt = GET_WHEEL_DELTA_WPARAM(wParam);
modifiers = getModifiers();
Store_field(res, 0, Val_int(x));
Store_field(res, 1, Val_int(y));
Store_field(res, 2, Val_int(dt));
Store_field(res, 3, modifiers);
break;
}
case WM_MOUSEHWHEEL:
{
res = caml_alloc(4,4);
x = GET_X_LPARAM(lParam);
y = GET_Y_LPARAM(lParam);
dt = GET_WHEEL_DELTA_WPARAM(wParam);
modifiers = getModifiers();
Store_field(res, 0, Val_int(x));
Store_field(res, 1, Val_int(y));
Store_field(res, 2, Val_int(dt));
Store_field(res, 3, modifiers);
break;
}
case WM_LBUTTONUP:
{
res = caml_alloc(4,5);
x = GET_X_LPARAM(lParam);
y = GET_Y_LPARAM(lParam);
modifiers = getModifiers();
Store_field(res, 0, Val_int(0));
Store_field(res, 1, Val_int(x));
Store_field(res, 2, Val_int(y));
Store_field(res, 3, modifiers);
break;
}
case WM_LBUTTONDOWN:
{
res = caml_alloc(4,6);
x = GET_X_LPARAM(lParam);
y = GET_Y_LPARAM(lParam);
modifiers = getModifiers();
Store_field(res, 0, Val_int(0));
Store_field(res, 1, Val_int(x));
Store_field(res, 2, Val_int(y));
Store_field(res, 3, modifiers);
break;
}
case WM_RBUTTONUP:
{
res = caml_alloc(4,5);
x = GET_X_LPARAM(lParam);
y = GET_Y_LPARAM(lParam);
modifiers = getModifiers();
Store_field(res, 0, Val_int(1));
Store_field(res, 1, Val_int(x));
Store_field(res, 2, Val_int(y));
Store_field(res, 3, modifiers);
break;
}
case WM_RBUTTONDOWN:
{
res = caml_alloc(4,6);
x = GET_X_LPARAM(lParam);
y = GET_Y_LPARAM(lParam);
modifiers = getModifiers();
Store_field(res, 0, Val_int(1));
Store_field(res, 1, Val_int(x));
Store_field(res, 2, Val_int(y));
Store_field(res, 3, modifiers);
break;
}
case WM_MBUTTONUP:
{
res = caml_alloc(4,5);
x = GET_X_LPARAM(lParam);
y = GET_Y_LPARAM(lParam);
modifiers = getModifiers();
Store_field(res, 0, Val_int(2));
Store_field(res, 1, Val_int(x));
Store_field(res, 2, Val_int(y));
Store_field(res, 3, modifiers);
break;
}
case WM_MBUTTONDOWN:
{
res = caml_alloc(4,6);
x = GET_X_LPARAM(lParam);
y = GET_Y_LPARAM(lParam);
modifiers = getModifiers();
Store_field(res, 0, Val_int(2));
Store_field(res, 1, Val_int(x));
Store_field(res, 2, Val_int(y));
Store_field(res, 3, modifiers);
break;
}
case WM_XBUTTONUP:
{
res = caml_alloc(4,5);
x = GET_X_LPARAM(lParam);
y = GET_Y_LPARAM(lParam);
modifiers = getModifiers();
button = HIWORD(wParam) == XBUTTON1 ? 3 : 4;
Store_field(res, 0, Val_int(button));
Store_field(res, 1, Val_int(x));
Store_field(res, 2, Val_int(y));
Store_field(res, 3, modifiers);
break;
}
case WM_XBUTTONDOWN:
{
res = caml_alloc(4,6);
x = GET_X_LPARAM(lParam);
y = GET_Y_LPARAM(lParam);
modifiers = getModifiers();
button = HIWORD(wParam) == XBUTTON1 ? 3 : 4;
Store_field(res, 0, Val_int(button));
Store_field(res, 1, Val_int(x));
Store_field(res, 2, Val_int(y));
Store_field(res, 3, modifiers);
break;
}
case WM_MOUSEMOVE:
{
res = caml_alloc(2,7);
x = GET_X_LPARAM(lParam);
y = GET_Y_LPARAM(lParam);
Store_field(res, 0, Val_int(x));
Store_field(res, 1, Val_int(y));
break;
}
default:
{
res = Val_int(0);
break;
}
}
CAMLreturn(res);
}
CAMLprim value
caml_get_async_key_state(value key)
{
CAMLparam1(key);
int code = Int_val(Field(key,0));
CAMLreturn(Val_bool(HIWORD(GetAsyncKeyState(code)) != 0));
}
CAMLprim value
caml_get_async_mouse_state(value but)
{
CAMLparam1(but);
int code = 0;
switch (Int_val(but))
{
case 0:
code = VK_LBUTTON;
break;
case 1:
code = VK_RBUTTON;
break;
case 2:
code = VK_MBUTTON;
break;
case 3:
code = VK_XBUTTON1;
break;
case 4:
code = VK_XBUTTON2;
break;
default:
caml_failwith("Variant error in get_async_mouse_state");
break;
}
CAMLreturn(Val_bool(HIWORD(GetAsyncKeyState(code)) != 0));
}
CAMLprim value
caml_button_swap(value unit)
{
CAMLparam1(unit);
CAMLreturn(Val_bool(GetSystemMetrics(SM_SWAPBUTTON)));
}
LRESULT CALLBACK onEvent(HWND handle, UINT message, WPARAM wParam, LPARAM lParam)
{
LONG_PTR data;
value uid;
value win;
if(message == WM_CREATE)
{
uid = (int)((CREATESTRUCT*)lParam)->lpCreateParams;
SetWindowLongPtrA(handle, GWLP_USERDATA, (LONG_PTR)uid);
}
if(handle) {
data = GetWindowLongPtrA(handle, GWLP_USERDATA);
if(data) {
uid = (int)data;
if(!callback_get_window_from_id) {
callback_get_window_from_id = caml_named_value("OGAMLCallbackGetWindow");
}
if(!callback_push_event_to_window) {
callback_push_event_to_window = caml_named_value("OGAMLCallbackPushEvent");
}
if(callback_get_window_from_id && callback_push_event_to_window) {
win = caml_callback(*callback_get_window_from_id, Val_int(uid));
if(Is_block(win)) {
caml_callback2(*callback_push_event_to_window, Field(win,0),
processEvent(message,wParam,lParam));
}
}
}
}
if (message == WM_CLOSE) {
return 0;
}
if ((message == WM_SYSCOMMAND) && (wParam == SC_KEYMENU))
return 0;
return DefWindowProcA(handle, message, wParam, lParam);
}
CAMLprim value
caml_register_class_W (value name)
{
CAMLparam1(name);
const wchar_t* classname = (wchar_t*)String_val(name);
WNDCLASSW windowClass;
windowClass.style = 0;
windowClass.lpfnWndProc = &onEvent;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = GetModuleHandleA(NULL);
windowClass.hIcon = NULL;
windowClass.hCursor = LoadCursor( NULL, IDC_ARROW );
windowClass.hbrBackground = 0;
windowClass.lpszMenuName = NULL;
windowClass.lpszClassName = classname;
RegisterClassA(&windowClass);
CAMLreturn(Val_unit);
}
CAMLprim value
caml_create_window_W(value cname, value title, value rect, value style, value uid)
{
CAMLparam5(cname, title, rect, style, uid);
DWORD winstyle = (DWORD)style;
HWND window;
int width, height, posx, posy;
RECT rectangle;
posx = Int_val(Field(rect,0));
posy = Int_val(Field(rect,1));
width = Int_val(Field(rect,2));
height = Int_val(Field(rect,3));
rectangle.left = posx;
rectangle.top = posy;
rectangle.right = posx+width;
rectangle.bottom = posy+height;
AdjustWindowRect(&rectangle, winstyle, 0);
posx = rectangle.left;
posy = rectangle.top;
width = rectangle.right - rectangle.left;
height = rectangle.bottom - rectangle.top;
window = CreateWindowA(String_val(cname),
String_val(title),
winstyle,
posx,
posy,
width,
height,
NULL,
NULL,
GetModuleHandle(NULL),
(LPCWSTR)Int_val(uid));
CAMLreturn((value)window);
}
CAMLprim value
caml_get_window_style(value handle)
{
CAMLparam1(handle);
HWND wnd = (HWND)handle;
DWORD winstyle = (DWORD)GetWindowLongPtr(wnd, GWL_STYLE);
CAMLreturn((value)winstyle);
}
CAMLprim value
caml_set_window_style(value handle, value style)
{
CAMLparam2(handle, style);
HWND wnd = (HWND)handle;
DWORD winstyle = (DWORD)style;
SetWindowLongPtr(wnd, GWL_STYLE, winstyle);
CAMLreturn(Val_unit);
}
CAMLprim value
caml_screen_to_client(value handle, value pos)
{
CAMLparam2(handle, pos);
CAMLlocal1(res);
HWND wnd = (HWND)handle;
POINT pt;
pt.x = Int_val(Field(pos,0));
pt.y = Int_val(Field(pos,1));
ScreenToClient(wnd, &pt);
res = caml_alloc(2,0);
Store_field(res, 0, Val_int(pt.x));
Store_field(res, 1, Val_int(pt.y));
CAMLreturn(res);
}
CAMLprim value
caml_client_to_screen(value handle, value pos)
{
CAMLparam2(handle, pos);
CAMLlocal1(res);
HWND wnd = (HWND)handle;
POINT pt;
pt.x = Int_val(Field(pos,0));
pt.y = Int_val(Field(pos,1));
ClientToScreen(wnd, &pt);
res = caml_alloc(2,0);
Store_field(res, 0, Val_int(pt.x));
Store_field(res, 1, Val_int(pt.y));
CAMLreturn(res);
}
CAMLprim value
caml_adjust_window_rect(value handle, value rect, value style)
{
CAMLparam3(handle, rect, style);
CAMLlocal1(res);
HWND wnd = (HWND)handle;
DWORD winstyle = (DWORD)style;
RECT rectangle;
rectangle.left = Int_val(Field(rect,0));
rectangle.top = Int_val(Field(rect,1));
rectangle.right = Int_val(Field(rect,2)) + rectangle.left;
rectangle.bottom = Int_val(Field(rect,3)) + rectangle.top;
AdjustWindowRect(&rectangle, winstyle, FALSE);
res = caml_alloc(4, 0);
Store_field(res, 0, Val_int(rectangle.left));
Store_field(res, 1, Val_int(rectangle.top));
Store_field(res, 2, Val_int(rectangle.right - rectangle.left));
Store_field(res, 3, Val_int(rectangle.bottom - rectangle.top));
CAMLreturn(res);
}
CAMLprim value
caml_fullscreen_size(value unit)
{
CAMLparam1(unit);
CAMLlocal1(res);
res = caml_alloc(2,0);
Store_field(res, 0, Val_int(GetSystemMetrics(SM_CXSCREEN)));
Store_field(res, 1, Val_int(GetSystemMetrics(SM_CYSCREEN)));
CAMLreturn(res);
}
CAMLprim value
caml_set_window_text(value handle, value txt)
{
CAMLparam2(handle, txt);
HWND wnd = (HWND)handle;
SetWindowTextA(wnd, (LPCTSTR)String_val(txt));
CAMLreturn(Val_unit);
}
CAMLprim value
caml_close_window(value handle)
{
CAMLparam1(handle);
HWND wnd = (HWND)handle;
CloseWindow(wnd);
CAMLreturn(Val_unit);
}
CAMLprim value
caml_destroy_window(value handle)
{
CAMLparam1(handle);
HWND wnd = (HWND)handle;
DestroyWindow(wnd);
CAMLreturn(Val_unit);
}
CAMLprim value
caml_window_has_focus(value handle)
{
CAMLparam1(handle);
HWND wnd = (HWND)handle;
CAMLreturn(Val_bool(wnd == GetForegroundWindow()));
}
CAMLprim value
caml_get_window_rect(value handle)
{
CAMLparam1(handle);
CAMLlocal1(res);
HWND wnd = (HWND)handle;
RECT rectwin, rectclt;
GetWindowRect(wnd, &rectwin);
GetClientRect(wnd, &rectclt);
res = caml_alloc(4,0);
Store_field(res, 0, Val_int(rectwin.left));
Store_field(res, 1, Val_int(rectwin.top));
Store_field(res, 2, Val_int(rectclt.right - rectclt.left));
Store_field(res, 3, Val_int(rectclt.bottom - rectclt.top));
CAMLreturn(res);
}
CAMLprim value
caml_move_window(value handle, value rect, value nomove, value nosize)
{
CAMLparam4(handle, rect, nomove, nosize);
HWND wnd = (HWND)handle;
int x, y, w, h;
UINT flags = 0;
if(Bool_val(nomove)) {
flags |= SWP_NOMOVE;
}
if(Bool_val(nosize)) {
flags |= SWP_NOSIZE;
}
x = Int_val(Field(rect,0));
y = Int_val(Field(rect,1));
w = Int_val(Field(rect,2));
h = Int_val(Field(rect,3));
SetWindowPos(wnd,NULL,x,y,w,h,flags);
CAMLreturn(Val_unit);
}
CAMLprim value
caml_attach_userdata(value handle, value udata)
{
CAMLparam2(handle, udata);
HWND wnd;
LONG_PTR userdata;
wnd = (HWND)handle;
userdata = (LONG_PTR)(udata);
SetWindowLongPtrA(wnd,GWLP_USERDATA,userdata);
CAMLreturn(Val_unit);
}
CAMLprim value
caml_swap_buffers(value handle)
{
CAMLparam1(handle);
HDC hDC = GetDC((HWND)handle);
SwapBuffers(hDC);
CAMLreturn(Val_unit);
}
CAMLprim value
caml_process_events(value handle)
{
CAMLparam1(handle);
MSG message;
while (PeekMessageA(&message, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&message);
DispatchMessageA(&message);
}
CAMLreturn(Val_unit);
}
CAMLprim value
caml_cursor_position(value unit)
{
CAMLparam1(unit);
CAMLlocal1(res);
POINT point;
GetCursorPos(&point);
res = caml_alloc(2,0);
Store_field(res, 0, Val_int(point.x));
Store_field(res, 1, Val_int(point.y));
CAMLreturn(res);
}
CAMLprim value
caml_set_cursor_position(value pos)
{
CAMLparam1(pos);
SetCursorPos(Int_val(Field(pos,0)),Int_val(Field(pos,1)));
CAMLreturn(Val_unit);
}
CAMLprim value
caml_show_cursor(value handle, value show)
{
CAMLparam2(handle, show);
ShowCursor(Bool_val(show));
CAMLreturn(Val_unit);
}
CAMLprim value
caml_set_fullscreen_devmode(value handle, value width, value height)
{
CAMLparam1(handle);
LONG result;
DEVMODE dm;
dm.dmSize = sizeof(DEVMODE);
dm.dmPelsWidth = Int_val(width);
dm.dmPelsHeight = Int_val(height);
dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT;
result = ChangeDisplaySettingsA(&dm, CDS_FULLSCREEN);
CAMLreturn(Val_bool(result == DISP_CHANGE_SUCCESSFUL));
}
CAMLprim value
caml_unset_fullscreen_devmode(value handle)
{
CAMLparam1(handle);
CAMLreturn(Val_bool(ChangeDisplaySettingsA(0, 0) == DISP_CHANGE_SUCCESSFUL));
}
|
laser-turtle/ogaml
|
src/core/x11/stubs/utils.c
|
#define CAML_NAME_SPACE
#include "utils.h"
static struct custom_operations XVisualInfo_custom_ops = {
identifier : "XVisualInfo handling",
finalize : custom_finalize_default,
compare : custom_compare_default,
hash : custom_hash_default,
serialize : custom_serialize_default,
deserialize : custom_deserialize_default
};
static struct custom_operations XEvent_custom_ops = {
identifier : "XEvent handling",
finalize : custom_finalize_default,
compare : custom_compare_default,
hash : custom_hash_default,
serialize : custom_serialize_default,
deserialize : custom_deserialize_default
};
static struct custom_operations Window_custom_ops = {
identifier : "Window handling",
finalize : custom_finalize_default,
compare : custom_compare_default,
hash : custom_hash_default,
serialize : custom_serialize_default,
deserialize : custom_deserialize_default
};
value Val_some(value v)
{
CAMLparam1(v);
CAMLlocal1(some);
some = caml_alloc(1, 0);
Store_field( some, 0, v );
CAMLreturn(some);
}
value Int_pair(int a, int b)
{
CAMLparam0();
CAMLlocal1(pair);
pair = caml_alloc(2, 0);
Store_field(pair, 0, Val_int(a));
Store_field(pair, 1, Val_int(b));
CAMLreturn(pair);
}
|
laser-turtle/ogaml
|
src/core/x11/stubs/window_stubs.c
|
<filename>src/core/x11/stubs/window_stubs.c
#include <X11/Xlib.h>
#include <GL/gl.h>
#include <GL/glx.h>
#include "utils.h"
// INPUT display, parent window, origin, size, border width,
// border value, bg value
// OUTPUT new window
CAMLprim value
caml_xcreate_simple_window(
value disp, value parent, value origin, value size, value visual
)
{
CAMLparam5(disp, parent, origin, size, visual);
CAMLlocal1(res);
Display* dpy = Display_val(disp);
Window p = Window_val(parent);
XVisualInfo* xvi = XVisualInfo_val(visual);
int depth = xvi->depth;
Visual *vis = xvi->visual;
unsigned int mask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;
XSetWindowAttributes winAttr ;
winAttr.event_mask = StructureNotifyMask | KeyPressMask ;
winAttr.background_pixmap = None ;
winAttr.background_pixel = 0 ;
winAttr.border_pixel = 0 ;
winAttr.colormap = XCreateColormap(dpy, p, vis, AllocNone);
Window win = XCreateWindow(
dpy,
p,
Int_val(Field(origin,0)),
Int_val(Field(origin,1)),
Int_val(Field(size,0)),
Int_val(Field(size,1)),
0,
depth,
InputOutput,
vis,
mask,
&winAttr
);
Window_alloc(res);
Window_copy(res, &win);
CAMLreturn(res);
}
// INPUT display, screen
// OUTPUT window (root of screen)
CAMLprim value
caml_xroot_window(value disp, value screen)
{
CAMLparam2(disp, screen);
CAMLlocal1(res);
Display* dpy = Display_val(disp);
Window win = XRootWindow(dpy, Int_val(screen));
Window_alloc(res);
Window_copy(res, &win);
CAMLreturn(res);
}
// INPUT display, window, string
// OUTPUT nothing, sets the title of the window
CAMLprim value
caml_xwindow_set_title(value disp, value win, value str)
{
CAMLparam3(disp, win, str);
Display* dpy = Display_val(disp);
Window w = Window_val(win);
XStoreName(dpy, w, String_val(str));
CAMLreturn(Val_unit);
}
// INPUT display, window
// OUTPUT the title of the window
CAMLprim value
caml_xwindow_get_title(value disp, value win)
{
CAMLparam2(disp, win);
CAMLlocal1(res);
Display* dpy = Display_val(disp);
Window w = Window_val(win);
char* win_name;
XFetchName(dpy, w, &win_name);
res = caml_copy_string(win_name);
XFree(win_name);
CAMLreturn(res);
}
// INPUT display, window
// OUTPUT nothing, maps the window
CAMLprim value
caml_xmap_window(value disp, value win)
{
CAMLparam2(disp, win);
Display* dpy = Display_val(disp);
Window w = Window_val(win);
XMapWindow(dpy, w);
CAMLreturn(Val_unit);
}
// INPUT display, window
// OUTPUT nothing, unmaps the window
CAMLprim value
caml_xunmap_window(value disp, value win)
{
CAMLparam2(disp, win);
Display* dpy = Display_val(disp);
Window w = Window_val(win);
XUnmapWindow(dpy, w);
CAMLreturn(Val_unit);
}
// INPUT display, window
// OUTPUT nothing, destroys the window
CAMLprim value
caml_xdestroy_window(value disp, value win)
{
CAMLparam2(disp, win);
Display* dpy = Display_val(disp);
Window w = Window_val(win);
XDestroyWindow(dpy, w);
CAMLreturn(Val_unit);
}
// INPUT display, window
// OUTPUT width and height of window (in pixels)
CAMLprim value
caml_size_window(value disp, value win)
{
CAMLparam2(disp, win);
Display* dpy = Display_val(disp);
Window w = Window_val(win);
XWindowAttributes att;
XGetWindowAttributes(dpy, w, &att);
CAMLreturn(Int_pair(att.width, att.height));
}
// INPUT display, window
// OUTPUT position of the window (in pixel)
CAMLprim value
caml_xwindow_position(value disp, value win)
{
CAMLparam2(disp, win);
Display* dpy = Display_val(disp);
Window w = Window_val(win);
XWindowAttributes att;
XGetWindowAttributes(dpy, w, &att);
CAMLreturn(Int_pair(att.x, att.y));
}
// INPUT display, window, x, y
// OUTPUT resizes the window
CAMLprim value
caml_resize_window(value disp, value win, value width, value height)
{
CAMLparam4(disp, win, width, height);
Display* dpy = Display_val(disp);
Window w = Window_val(win);
XResizeWindow(dpy, w, Int_val(width), Int_val(height));
CAMLreturn(Val_unit);
}
// INPUT display, window, min size, max size
// OUTPUT nothing, sets the wm size hints
CAMLprim value
caml_set_wm_size_hints(value disp, value win, value minsize, value maxsize)
{
CAMLparam4(disp, win, minsize, maxsize);
Display* dpy = Display_val(disp);
Window w = Window_val(win);
XSizeHints* hints = XAllocSizeHints();
hints->flags = PMinSize | PMaxSize;
hints->min_width = Int_val(Field(minsize,0));
hints->min_height = Int_val(Field(minsize,1));
hints->max_width = Int_val(Field(maxsize,0));
hints->max_height = Int_val(Field(maxsize,1));
XSetWMNormalHints(dpy, w, hints);
XFree(hints);
CAMLreturn(Val_unit);
}
// INPUT a display, a window
// OUTPUT true iff the window has focus
CAMLprim value
caml_has_focus(value disp, value win)
{
CAMLparam2(disp, win);
Display* dpy = Display_val(disp);
Window w = Window_val(win);
Window result;
int state;
XGetInputFocus(dpy, &result, &state);
CAMLreturn(Val_bool(w == result));
}
// INPUT a display, a window, a boolean
// OUTPUT nothing, changes the visibility of the cursor
CAMLprim value
caml_xshow_cursor(value disp, value win, value bl)
{
CAMLparam3(disp, win, bl);
Display* dpy = Display_val(disp);
Window w = Window_val(win);
if(!Bool_val(bl)) {
Pixmap bm_no;
Colormap cmap;
Cursor no_ptr;
XColor black, dummy;
static char bm_no_data[] = {0, 0, 0, 0, 0, 0, 0, 0};
cmap = DefaultColormap(dpy, DefaultScreen(dpy));
XAllocNamedColor(dpy, cmap, "black", &black, &dummy);
bm_no = XCreateBitmapFromData(dpy, w, bm_no_data, 8, 8);
no_ptr = XCreatePixmapCursor(dpy, bm_no, bm_no, &black, &black, 0, 0);
XDefineCursor(dpy, w, no_ptr);
XFreeCursor(dpy, no_ptr);
if (bm_no != None)
XFreePixmap(dpy, bm_no);
XFreeColors(dpy, cmap, &black.pixel, 1, 0);
} else {
XUndefineCursor(dpy, w);
}
CAMLreturn(Val_unit);
}
|
laser-turtle/ogaml
|
src/core/x11/stubs/keyboard_stubs.c
|
<gh_stars>10-100
#include <X11/Xlib.h>
#include <xcb/xcb.h>
#include <X11/Xlib-xcb.h>
#include <X11/keysym.h>
#include "utils.h"
CAMLprim value
caml_is_key_down(value disp, value code)
{
CAMLparam2(disp, code);
Display* dpy = Display_val(disp);
xcb_generic_error_t* error = NULL;
xcb_connection_t* conn = XGetXCBConnection(dpy);
xcb_query_keymap_reply_t* keymap =
xcb_query_keymap_reply(conn,
xcb_query_keymap(conn),
&error);
xcb_keycode_t sym;
if(Tag_val(code) == 0) {
sym = Int_val(Field(code,0));
} else {
int val = Int_val(Field(code,0));
char str[2] = {val, '\0'};
int ks = XStringToKeysym(str);
sym = XKeysymToKeycode(dpy, ks);
}
CAMLreturn(Val_bool((keymap->keys[sym / 8] & (1 << (sym % 8))) != 0));
}
|
laser-turtle/ogaml
|
src/core/windows/stubs/context_stubs.c
|
<filename>src/core/windows/stubs/context_stubs.c
#include "utils.h"
#include <windows.h>
#include <memory.h>
CAMLprim value
caml_wgl_create_context(value hwnd)
{
CAMLparam1(hwnd);
HDC hDC;
HGLRC hRC;
hDC = GetDC((HWND)hwnd);
hRC = wglCreateContext(hDC);
CAMLreturn((value)hRC);
}
CAMLprim value
caml_wgl_make_current(value hwnd, value hrc)
{
CAMLparam2(hwnd,hrc);
HDC hDC = GetDC((HWND)hwnd);
wglMakeCurrent(hDC,(HGLRC)hrc);
CAMLreturn(Val_unit);
}
CAMLprim value
caml_wgl_remove_current(value hwnd)
{
CAMLparam1(hwnd);
HDC hDC = GetDC((HWND)hwnd);
wglMakeCurrent(hDC,NULL);
CAMLreturn (Val_unit);
}
CAMLprim value
caml_wgl_destroy(value hrc)
{
CAMLparam1(hrc);
wglDeleteContext((HGLRC)hrc);
CAMLreturn(Val_unit);
}
CAMLprim value
caml_wgl_isnull(value hrc)
{
CAMLparam1(hrc);
HGLRC ctx = (HGLRC) hrc;
CAMLreturn(Val_bool(ctx == NULL));
}
|
laser-turtle/ogaml
|
src/core/x11/stubs/mouse_stubs.c
|
<gh_stars>10-100
#include <X11/Xlib.h>
#include "utils.h"
// INPUT a display, a window, a position
// OUTPUT nothing, warps the pointer to the position relatively to the window
CAMLprim value
caml_xwarp_pointer(value disp, value win, value x, value y)
{
CAMLparam4(disp, win, x, y);
Display* dpy = Display_val(disp);
Window w = Window_val(win);
XWarpPointer(dpy, None, w, 0, 0, 0, 0, Int_val(x), Int_val(y));
XFlush(dpy);
CAMLreturn(Val_unit);
}
// INPUT a display, a window
// OUTPUT the position of the cursor relatively to the window
CAMLprim value
caml_xquery_pointer_position(value disp, value win)
{
CAMLparam2(disp, win);
Display* dpy = Display_val(disp);
Window w = Window_val(win);
Window rr, cr;
int rx, ry, wx, wy;
unsigned int mask;
XQueryPointer(dpy, w, &rr, &cr, &rx, &ry, &wx, &wy, &mask);
CAMLreturn(Int_pair(wx, wy));
}
// INPUT a display, a window, a button
// OUTPUT true iff the specified button is pressed
CAMLprim value
caml_xquery_button_down(value disp, value win, value but)
{
CAMLparam3(disp, win, but);
CAMLlocal1(res); res = Val_false;
Display* dpy = Display_val(disp);
Window w = Window_val(win);
Window rr, cr;
int rx, ry, wx, wy;
unsigned int mask;
XQueryPointer(dpy, w, &rr, &cr, &rx, &ry, &wx, &wy, &mask);
if(Int_val(but) >= 1 && Int_val(but) <= 5) {
if((1 << (Int_val(but) + 7)) & mask)
res = Val_true;
}
CAMLreturn(res);
}
|
laser-turtle/ogaml
|
src/core/cocoa/stubs/cocoa_stubs.h
|
#include "utils.h"
#ifndef __APPLE__
#define strong retain
#endif
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#include <CoreFoundation/CoreFoundation.h>
#import <CoreGraphics/CoreGraphics.h>
#include <Carbon/Carbon.h>
// A function to move the cursor
void warpCursor(NSPoint loc);
// Our own event object to add windowClosed
typedef enum
{
OGCocoaEvent,
OGCloseWindowEvent,
OGKeyDown,
OGKeyUp,
OGResizedWindowEvent,
OGScrollWheel
} OGEventType;
typedef struct
{
unsigned short keyCode;
NSString * characters;
NSEventModifierFlags modifierFlags;
} OGKeyInfo;
typedef union
{
NSEvent* nsevent;
OGKeyInfo keyInformation;
CGFloat scrollingDeltaY;
} OGEventContent;
@interface OGEvent : NSObject
{
OGEventType m_type;
OGEventContent m_content;
}
- (instancetype)initWithNSEvent:(NSEvent*)nsevent;
- (instancetype)initWithCloseWindow;
- (instancetype)initWithResizedWindow;
- (instancetype)initWithKeyUp:(unsigned short)keyCode
characters:(NSString *)characters
modifierFlags:(NSEventModifierFlags)modifierFlags;
- (instancetype)initWithKeyDown:(unsigned short)keyCode
characters:(NSString *)characters
modifierFlags:(NSEventModifierFlags)modifierFlags;
- (instancetype)initWithScrollingDeltaY:(CGFloat)deltaY;
- (OGEventType)type;
- (OGEventContent)content;
@end
// Custom OpenGLView that handles events
////////////////////////////////////////
@interface OGOpenGLView : NSOpenGLView
{
NSMutableArray* m_events;
}
-(void)pushEvent:(OGEvent *)event;
-(OGEvent *)popEvent;
@end
// Event processing and menu bar (strongly inspired from SFML)
//////////////////////////////////////////////////////////////
@interface OGApplication : NSApplication
// Event processing
+(void) processEvent;
// Setting the menu bar
+(void) setUpMenuBar;
// Displatchs events
-(void)sendEvent:(NSEvent*)anEvent;
@end
// Application specific events processing
/////////////////////////////////////////
@interface OGApplicationDelegate : NSObject <NSApplicationDelegate>
// Handling of termination notification
-(NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender;
// Once all windows are closed
-(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)app;
@end
// Handler of a window
//////////////////////
@interface OGWindowController : NSResponder <NSWindowDelegate>
{
NSWindow* m_window;
BOOL m_windowIsOpen; // Luckily it is NO by default
OGOpenGLView* m_view;
NSOpenGLContext* m_context;
}
-(id)initWithWindow:(NSWindow*)window;
-(void)setTitle:(NSString*)title;
-(NSRect)frame;
-(NSRect)contentFrame;
-(void)closeWindow;
-(BOOL)isWindowOpen;
-(void)releaseWindow;
-(void)openWindow;
-(OGEvent *)popEvent;
-(void)setGLContext:(NSOpenGLContext*)context;
-(void)flushGLContext;
-(NSPoint)mouseLocation;
-(NSPoint)properRelativeMouseLocation;
-(void)setProperRelativeMouseLocationTo:(NSPoint)loc;
-(BOOL)hasFocus;
// Handling resizing of a window
-(void)windowDidResize:(NSNotification *)notification;
-(void)resize:(NSRect)frame;
-(void)toggleFullScreen;
-(NSWindow*)window;
@end
|
laser-turtle/ogaml
|
src/core/x11/stubs/utils_stubs.c
|
#include "utils.h"
CAMLprim value
caml_realpath(value path)
{
CAMLparam1(path);
CAMLlocal1(res);
char* res_ptr = realpath(String_val(path), NULL);
res = caml_copy_string(res_ptr);
free(res_ptr);
CAMLreturn(res);
}
|
laser-turtle/ogaml
|
src/graphics/stubs/ebo_stubs.c
|
#define GL_GLEXT_PROTOTYPES
#if defined(_WIN32)
#include <windows.h>
#include <gl/glew.h>
#endif
#if defined(__APPLE__)
#include <OpenGL/gl3.h>
#ifndef GL_TESS_CONTROL_SHADER
#define GL_TESS_CONTROL_SHADER 0x00008e88
#endif
#ifndef GL_TESS_EVALUATION_SHADER
#define GL_TESS_EVALUATION_SHADER 0x00008e87
#endif
#ifndef GL_PATCHES
#define GL_PATCHES 0x0000000e
#endif
#else
#include <GL/gl.h>
#endif
#include <caml/bigarray.h>
#include "utils.h"
#include "types_stubs.h"
#define BUFFER(_a) (*(GLuint*) Data_custom_val(_a))
// INPUT a buffer name
// OUTPUT nothing, binds the buffer
CAMLprim value
caml_bind_ebo(value buf)
{
CAMLparam1(buf);
if(buf == Val_none)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
else
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BUFFER(Some_val(buf)));
CAMLreturn(Val_unit);
}
// INPUT a length, some data (option), a mode
// OUTPUT nothing, updates the bound buffer with the data
CAMLprim value
caml_ebo_data(value len, value opt, value mode)
{
CAMLparam3(len, opt, mode);
if(opt == Val_none)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, Int_val(len), NULL, EBOKind_val(mode));
else {
const GLvoid* c_dat = Caml_ba_data_val(Field(Some_val(opt),0));
glBufferData(GL_ELEMENT_ARRAY_BUFFER, Int_val(len), c_dat, EBOKind_val(mode));
}
CAMLreturn(Val_unit);
}
// INPUT an offset, a length, some data
// OUTPUT nothing, updates a sub-buffer with the data
CAMLprim value
caml_ebo_subdata(value off, value len, value data)
{
CAMLparam3(off, len, data);
const GLvoid* c_dat = Caml_ba_data_val(Field(data,0));
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, Int_val(off), Int_val(len), c_dat);
CAMLreturn(Val_unit);
}
|
laser-turtle/ogaml
|
src/graphics/stubs/image_stubs.c
|
#include "utils.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
CAMLprim value
caml_image_load_from_file(value filename)
{
CAMLparam1(filename);
CAMLlocal2(result, px);
int x,y,chan;
char* pixels;
stbi_set_flip_vertically_on_load(1);
pixels = stbi_load(String_val(filename), &x, &y, &chan, STBI_rgb_alpha);
if(pixels && x && y) {
result = caml_alloc(3,0);
px = caml_alloc_string(x * y * 4);
memcpy(String_val(px), pixels, x * y * 4);
Store_field(result, 0, px);
Store_field(result, 1, Val_int(x));
Store_field(result, 2, Val_int(y));
stbi_image_free(pixels);
CAMLreturn(Val_some(result));
}
else {
CAMLreturn(Val_none);
}
}
CAMLprim value
caml_image_load_error(value unit)
{
CAMLparam0();
CAMLreturn(caml_copy_string(stbi_failure_reason()));
}
CAMLprim value
caml_image_write_png(value filename, value size, value chan, value stride, value data)
{
CAMLparam5(filename, size, chan, stride, data);
int w,h;
w = Int_val(Field(size,0));
h = Int_val(Field(size,1));
stbi_write_png(String_val(filename), w, h, Int_val(chan), String_val(data), Int_val(stride));
CAMLreturn(Val_unit);
}
|
laser-turtle/ogaml
|
src/graphics/stubs/utils.h
|
#ifndef CAML_STUBS_HEADER
#define CAML_STUBS_HEADER
#define CAML_NAME_SPACE
#include <caml/custom.h>
#include <caml/fail.h>
#include <caml/callback.h>
#include <caml/memory.h>
#include <caml/alloc.h>
#include <caml/mlvalues.h>
#include <stdio.h>
#define Val_none Val_int(0)
#define Some_val(v) Field(v,0)
value Val_some(value v);
value Int_pair(int a, int b);
#endif
|
laser-turtle/ogaml
|
src/graphics/stubs/types_stubs.h
|
<gh_stars>10-100
#ifndef TYPES_STUBS_HEADER
#define TYPES_STUBS_HEADER
#include <caml/custom.h>
#include <caml/fail.h>
#include <caml/callback.h>
#include <caml/memory.h>
#include <caml/alloc.h>
#include <caml/mlvalues.h>
#include <stdio.h>
GLenum BlendFunc_val(value func);
GLenum BlendFactor_val(value fac);
GLenum EBOKind_val(value kind);
int Val_attrib_type(GLenum type);
GLenum Cull_val(value mode);
GLenum Polygon_val(value mode);
GLenum Depthfun_val(value fun);
value Val_error(GLenum err);
GLenum Shader_val(value type);
GLenum Target_val(value target);
GLenum Magnify_val(value mag);
GLenum Minify_val(value min);
GLenum Wrap_val(value wrp);
GLenum TextureFormat_val(value fmt);
GLenum PixelFormat_val(value fmt);
GLenum Floattype_val(value type);
GLenum Inttype_val(value type);
GLenum Drawmode_val(value mode);
GLenum VBOKind_val(value kind);
GLenum Attachment_val(value att);
GLenum Parameter_val(value par);
#endif
|
laser-turtle/ogaml
|
src/core/windows/stubs/utils.c
|
#define CAML_NAME_SPACE
#include "utils.h"
struct custom_operations empty_custom_opts = {
"obj_st handling",
custom_finalize_default,
custom_compare_default,
custom_hash_default,
custom_serialize_default,
custom_deserialize_default
};
value Val_some(value v)
{
CAMLparam1(v);
CAMLlocal1(some);
some = caml_alloc(1, 0);
Store_field( some, 0, v );
CAMLreturn(some);
}
value Int_pair(int a, int b)
{
CAMLparam0();
CAMLlocal1(pair);
pair = caml_alloc(2, 0);
Store_field(pair, 0, Val_int(a));
Store_field(pair, 1, Val_int(b));
CAMLreturn(pair);
}
|
laser-turtle/ogaml
|
src/core/windows/stubs/style_stubs.c
|
#include "utils.h"
#include <windows.h>
#include <memory.h>
DWORD Style_val(value style)
{
switch(Int_val(style))
{
case 0:
return WS_BORDER;
case 1:
return WS_CAPTION;
case 2:
return WS_MAXIMIZE;
case 3:
return WS_MAXIMIZEBOX;
case 4:
return WS_MINIMIZE;
case 5:
return WS_MINIMIZEBOX;
case 6:
return WS_POPUP;
case 7:
return WS_SYSMENU;
case 8:
return WS_THICKFRAME;
case 9:
return WS_VISIBLE;
case 10:
return WS_CLIPCHILDREN;
case 11:
return WS_CLIPSIBLINGS;
default:
caml_failwith("Caml variant error in Style_val(1)");
}
return 0;
}
CAMLprim value
caml_mkstyle_W(value styles)
{
CAMLparam1(styles);
CAMLlocal2(hd, tl);
DWORD flags = 0;
tl = styles;
while(tl != Val_emptylist) {
hd = Field(tl,0);
tl = Field(tl,1);
flags |= Style_val(hd);
}
CAMLreturn((value)flags);
}
|
laser-turtle/ogaml
|
src/graphics/stubs/types_stubs.c
|
<reponame>laser-turtle/ogaml<filename>src/graphics/stubs/types_stubs.c
#define GL_GLEXT_PROTOTYPES
#if defined(_WIN32)
#include <windows.h>
#include <gl/glew.h>
#endif
#if defined(__APPLE__)
#include <OpenGL/gl3.h>
#ifndef GL_TESS_CONTROL_SHADER
#define GL_TESS_CONTROL_SHADER 0x00008e88
#endif
#ifndef GL_TESS_EVALUATION_SHADER
#define GL_TESS_EVALUATION_SHADER 0x00008e87
#endif
#ifndef GL_PATCHES
#define GL_PATCHES 0x0000000e
#endif
#else
#include <GL/gl.h>
#endif
#include "types_stubs.h"
#include "utils.h"
GLenum BlendFunc_val(value func)
{
switch(Tag_val(func))
{
case 0:
return GL_FUNC_ADD;
case 1:
return GL_FUNC_SUBTRACT;
default:
caml_failwith("Caml variant error in BlendFunc_val(1)");
}
}
GLenum BlendFactor_val(value fac)
{
switch(Int_val(fac))
{
case 0 :
return GL_ZERO;
case 1 :
return GL_ONE;
case 2 :
return GL_SRC_COLOR;
case 3 :
return GL_ONE_MINUS_SRC_COLOR;
case 4 :
return GL_DST_COLOR;
case 5 :
return GL_ONE_MINUS_DST_COLOR;
case 6 :
return GL_SRC_ALPHA;
case 7 :
return GL_SRC_ALPHA_SATURATE;
case 8 :
return GL_ONE_MINUS_SRC_ALPHA;
case 9 :
return GL_DST_ALPHA;
case 10:
return GL_ONE_MINUS_DST_ALPHA;
case 11:
return GL_CONSTANT_COLOR;
case 12:
return GL_ONE_MINUS_CONSTANT_COLOR;
case 13:
return GL_CONSTANT_ALPHA;
case 14:
return GL_ONE_MINUS_CONSTANT_ALPHA;
default:
caml_failwith("Caml variant error in BlendFactor_val(1)");
}
}
GLenum EBOKind_val(value kind)
{
switch(Int_val(kind))
{
case 0:
return GL_STATIC_DRAW;
case 1:
return GL_DYNAMIC_DRAW;
default:
caml_failwith("Caml variant error in EBOKind_val(1)");
}
}
int Val_attrib_type(GLenum type)
{
switch(type)
{
case GL_INT : return 1;
case GL_INT_VEC2 : return 2;
case GL_INT_VEC3 : return 3;
case GL_INT_VEC4 : return 4;
case GL_FLOAT : return 5;
case GL_FLOAT_VEC2 : return 6;
case GL_FLOAT_VEC3 : return 7;
case GL_FLOAT_VEC4 : return 8;
case GL_FLOAT_MAT2 : return 9;
case GL_FLOAT_MAT2x3 : return 10;
case GL_FLOAT_MAT2x4 : return 11;
case GL_FLOAT_MAT3x2 : return 12;
case GL_FLOAT_MAT3 : return 13;
case GL_FLOAT_MAT3x4 : return 14;
case GL_FLOAT_MAT4x2 : return 15;
case GL_FLOAT_MAT4x3 : return 16;
case GL_FLOAT_MAT4 : return 17;
case GL_SAMPLER_1D : return 18;
case GL_SAMPLER_2D : return 19;
case GL_SAMPLER_2D_ARRAY : return 20;
case GL_SAMPLER_3D : return 21;
case GL_SAMPLER_CUBE : return 22;
default: return 0;
}
}
GLenum Cull_val(value mode)
{
switch(Int_val(mode))
{
case 0:
return -1;
case 1:
return GL_CCW;
case 2:
return GL_CW;
default:
caml_failwith("Caml variant error in Cull_val(1)");
}
}
GLenum Polygon_val(value mode)
{
switch(Int_val(mode))
{
case 0:
return GL_POINT;
case 1:
return GL_LINE;
case 2:
return GL_FILL;
default:
caml_failwith("Caml variant error in Polygon_val(1)");
}
}
GLenum Depthfun_val(value fun)
{
switch(Int_val(fun))
{
case 0:
case 1:
return GL_ALWAYS;
case 2:
return GL_NEVER;
case 3:
return GL_LESS;
case 4:
return GL_GREATER;
case 5:
return GL_EQUAL;
case 6:
return GL_LEQUAL;
case 7:
return GL_GEQUAL;
case 8:
return GL_NOTEQUAL;
default:
caml_failwith("Caml variant error in Depthfun_val(1)");
}
}
value Val_error(GLenum err)
{
switch(err)
{
case GL_NO_ERROR: return Val_none;
case GL_INVALID_ENUM : return Val_some(Val_int(0));
case GL_INVALID_VALUE : return Val_some(Val_int(1));
case GL_INVALID_OPERATION : return Val_some(Val_int(2));
case GL_INVALID_FRAMEBUFFER_OPERATION : return Val_some(Val_int(3));
case GL_OUT_OF_MEMORY : return Val_some(Val_int(4));
#ifndef __APPLE__
case GL_STACK_UNDERFLOW : return Val_some(Val_int(5));
case GL_STACK_OVERFLOW : return Val_some(Val_int(6));
#endif
default : return Val_none;
}
}
GLenum Shader_val(value type)
{
switch(Int_val(type))
{
case 0:
return GL_FRAGMENT_SHADER;
case 1:
return GL_VERTEX_SHADER;
default:
caml_failwith("Caml variant error in Shader_val(1)");
}
}
GLenum Target_val(value target)
{
switch(Int_val(target))
{
case 0:
return GL_TEXTURE_1D;
case 1:
return GL_TEXTURE_2D;
case 2:
return GL_TEXTURE_2D_ARRAY;
case 3:
return GL_TEXTURE_3D;
case 4:
return GL_TEXTURE_CUBE_MAP;
case 5:
return GL_TEXTURE_CUBE_MAP_POSITIVE_X;
case 6:
return GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
case 7:
return GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
case 8:
return GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
case 9:
return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
case 10:
return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
default:
caml_failwith("Caml variant error in Target_val(1)");
}
}
GLenum Magnify_val(value mag)
{
switch(Int_val(mag))
{
case 0:
return GL_NEAREST;
case 1:
return GL_LINEAR;
default:
caml_failwith("Caml variant error in Magnify_val(1)");
}
}
GLenum Minify_val(value min)
{
switch(Int_val(min))
{
case 0:
return GL_NEAREST;
case 1:
return GL_LINEAR;
case 2:
return GL_NEAREST_MIPMAP_NEAREST;
case 3:
return GL_LINEAR_MIPMAP_NEAREST;
case 4:
return GL_NEAREST_MIPMAP_LINEAR;
case 5:
return GL_LINEAR_MIPMAP_LINEAR;
default:
caml_failwith("Caml variant error in Minify_val(1)");
}
}
GLenum Wrap_val(value wrp)
{
switch(Int_val(wrp))
{
case 0:
return GL_CLAMP_TO_EDGE;
case 1:
return GL_CLAMP_TO_BORDER;
case 2:
return GL_MIRRORED_REPEAT;
case 3:
return GL_REPEAT;
#ifndef GL_MIRROR_CLAMP_TO_EDGE
case 4:
caml_failwith("GL_MIRROR_CLAMP_TO_EDGE is not supported");
#else
case 4:
return GL_MIRROR_CLAMP_TO_EDGE;
#endif
default:
caml_failwith("Caml variant error in Wrap_val(1)");
}
}
GLenum TextureFormat_val(value fmt)
{
switch(Int_val(fmt))
{
case 0:
return GL_R8;
case 1:
return GL_RG8;
case 2:
return GL_RGB8;
case 3:
return GL_RGBA8;
case 4:
return GL_DEPTH_COMPONENT24;
case 5:
return GL_DEPTH24_STENCIL8;
case 6:
return GL_STENCIL_INDEX8;
default:
caml_failwith("Caml variant error in TextureFormat_val(1)");
}
}
GLenum PixelFormat_val(value fmt)
{
switch(Int_val(fmt))
{
case 0:
return GL_RED;
case 1:
return GL_RG;
case 2:
return GL_RGB;
case 3:
return GL_BGR;
case 4:
return GL_RGBA;
case 5:
return GL_BGRA;
case 6:
return GL_DEPTH_COMPONENT;
case 7:
return GL_DEPTH_STENCIL;
default:
caml_failwith("Caml variant error in TextureFormat_val(1)");
}
}
GLenum Floattype_val(value type)
{
switch(Int_val(type))
{
case 0:
return GL_BYTE;
case 1:
return GL_UNSIGNED_BYTE;
case 2:
return GL_SHORT;
case 3:
return GL_UNSIGNED_SHORT;
case 4:
return GL_INT;
case 5:
return GL_UNSIGNED_INT;
case 6:
return GL_FLOAT;
case 7:
return GL_DOUBLE;
default:
failwith("Caml variant error in Floattype_val(1)");
}
}
GLenum Inttype_val(value type)
{
switch(Int_val(type))
{
case 0:
return GL_BYTE;
case 1:
return GL_UNSIGNED_BYTE;
case 2:
return GL_SHORT;
case 3:
return GL_UNSIGNED_SHORT;
case 4:
return GL_INT;
case 5:
return GL_UNSIGNED_INT;
default:
failwith("Caml variant error in Inttype_val(1)");
}
}
GLenum Drawmode_val(value mode)
{
switch(Int_val(mode))
{
case 0:
return GL_TRIANGLE_STRIP;
case 1:
return GL_TRIANGLE_FAN;
case 2:
return GL_TRIANGLES;
case 3:
return GL_LINES;
default:
failwith("Caml variant error in Drawmode_val(1)");
}
}
GLenum VBOKind_val(value kind)
{
switch(Int_val(kind))
{
case 0:
return GL_STATIC_DRAW;
case 1:
return GL_DYNAMIC_DRAW;
default:
caml_failwith("Caml variant error in VBOKind_val(1)");
}
}
GLenum Attachment_val(value att)
{
if(Is_long(att)) {
switch(Int_val(att))
{
case 0:
return GL_DEPTH_ATTACHMENT;
case 1:
return GL_STENCIL_ATTACHMENT;
case 2:
return GL_DEPTH_STENCIL_ATTACHMENT;
default:
caml_failwith("Caml variant error in Attachment_val (long val)");
}
} else {
switch(Tag_val(att))
{
case 0:
return (GL_COLOR_ATTACHMENT0 + Int_val(Field(att,0)));
default:
caml_failwith("Caml variant error in Attachment_val (tag val)");
}
}
}
GLenum Parameter_val(value par)
{
switch(Int_val(par))
{
case 0:
return GL_MAX_3D_TEXTURE_SIZE;
case 1:
return GL_MAX_ARRAY_TEXTURE_LAYERS;
case 2:
return GL_MAX_COLOR_TEXTURE_SAMPLES;
case 3:
return GL_MAX_CUBE_MAP_TEXTURE_SIZE;
case 4:
return GL_MAX_DEPTH_TEXTURE_SAMPLES;
case 5:
return GL_MAX_ELEMENTS_INDICES;
case 6:
return GL_MAX_ELEMENTS_VERTICES;
case 7:
return GL_MAX_INTEGER_SAMPLES;
case 8:
return GL_MAX_RENDERBUFFER_SIZE;
case 9:
return GL_MAX_TEXTURE_BUFFER_SIZE;
case 10:
return GL_MAX_TEXTURE_IMAGE_UNITS;
case 11:
return GL_MAX_TEXTURE_SIZE;
case 12:
return GL_MAX_COLOR_ATTACHMENTS;
default:
caml_failwith("Caml variant error in Parameter_val (1)");
}
}
|
laser-turtle/ogaml
|
src/graphics/stubs/blending_stubs.c
|
<filename>src/graphics/stubs/blending_stubs.c
#define GL_GLEXT_PROTOTYPES
#if defined(_WIN32)
#include <windows.h>
#include <gl/glew.h>
#endif
#if defined(__APPLE__)
#include <OpenGL/gl3.h>
#ifndef GL_TESS_CONTROL_SHADER
#define GL_TESS_CONTROL_SHADER 0x00008e88
#endif
#ifndef GL_TESS_EVALUATION_SHADER
#define GL_TESS_EVALUATION_SHADER 0x00008e87
#endif
#ifndef GL_PATCHES
#define GL_PATCHES 0x0000000e
#endif
#else
#include <GL/gl.h>
#endif
#include <caml/bigarray.h>
#include "utils.h"
#include "types_stubs.h"
CAMLprim value
caml_blend_enable(value b)
{
CAMLparam1(b);
if(Bool_val(b)) glEnable(GL_BLEND);
else glDisable(GL_BLEND);
CAMLreturn(Val_unit);
}
CAMLprim value
caml_blend_func_separate(value srcRGB, value dstRGB, value srcA, value dstA)
{
CAMLparam4(srcRGB, dstRGB, srcA, dstA);
glBlendFuncSeparate(
BlendFactor_val(srcRGB),
BlendFactor_val(dstRGB),
BlendFactor_val(srcA),
BlendFactor_val(dstA));
CAMLreturn(Val_unit);
}
CAMLprim value
caml_blend_equation_separate(value eqRGB, value eqA)
{
CAMLparam2(eqRGB, eqA);
GLenum rgb_eq = (Is_long(eqRGB))? GL_FUNC_ADD : BlendFunc_val(eqRGB);
GLenum alp_eq = (Is_long(eqA))? GL_FUNC_ADD : BlendFunc_val(eqA );
glBlendEquationSeparate(rgb_eq, alp_eq);
CAMLreturn(Val_unit);
}
|
laser-turtle/ogaml
|
src/graphics/stubs/vao_stubs.c
|
#define GL_GLEXT_PROTOTYPES
#if defined(_WIN32)
#include <windows.h>
#include <gl/glew.h>
#endif
#if defined(__APPLE__)
#include <OpenGL/gl3.h>
#ifndef GL_TESS_CONTROL_SHADER
#define GL_TESS_CONTROL_SHADER 0x00008e88
#endif
#ifndef GL_TESS_EVALUATION_SHADER
#define GL_TESS_EVALUATION_SHADER 0x00008e87
#endif
#ifndef GL_PATCHES
#define GL_PATCHES 0x0000000e
#endif
#else
#include <GL/gl.h>
#endif
#include <caml/bigarray.h>
#include <string.h>
#include "utils.h"
#include "types_stubs.h"
#define VAO(_a) (*(GLuint*) Data_custom_val(_a))
void finalise_vao(value v)
{
glDeleteVertexArrays(1,&VAO(v));
}
int compare_vao(value v1, value v2)
{
GLuint i1 = VAO(v1);
GLuint i2 = VAO(v2);
if(i1 < i2) return -1;
else if(i1 == i2) return 0;
else return 1;
}
intnat hash_vao(value v)
{
GLuint i = VAO(v);
return i;
}
static struct custom_operations vao_custom_ops = {
"vao gc handling",
finalise_vao,
compare_vao,
hash_vao,
custom_serialize_default,
custom_deserialize_default
};
// INPUT nothing
// OUTPUT a vertex array name
CAMLprim value
caml_create_vao(value unit)
{
CAMLparam0();
CAMLlocal1(v);
GLuint buf[1];
glGenVertexArrays(1, buf);
v = caml_alloc_custom( &vao_custom_ops, sizeof(GLuint), 0, 1);
memcpy( Data_custom_val(v), buf, sizeof(GLuint) );
CAMLreturn(v);
}
// INPUT : a vertex array name
// OUTPUT : nothing, binds the vertex array
CAMLprim value
caml_bind_vao(value buf)
{
CAMLparam1(buf);
if(buf == Val_none)
glBindVertexArray(0);
else {
glBindVertexArray(VAO(Some_val(buf)));
}
CAMLreturn(Val_unit);
}
// INPUT : a vertex array name
// OUTPUT : nothing, deletes the vertex array
CAMLprim value
caml_destroy_vao(value buf)
{
CAMLparam1(buf);
glDeleteVertexArrays(1, &VAO(buf));
CAMLreturn(Val_unit);
}
// INPUT an attribute location
// OUTPUT nothing, enables the attribute
CAMLprim value
caml_enable_attrib(value loc)
{
CAMLparam1(loc);
glEnableVertexAttribArray((GLuint)Int_val(loc));
CAMLreturn(Val_unit);
}
// INPUT an attribute location, its size, its type,
// an offset, a stride
// OUTPUT nothing, sets the float attribute pointer
CAMLprim value
caml_attrib_float(value loc, value size, value type, value off, value stride)
{
CAMLparam5(loc, size, type, off, stride);
GLuint glloc = (GLuint)Int_val(loc);
GLint glsize = Int_val(size);
GLsizei glstride = Int_val(stride);
GLvoid* gloffset = (GLvoid*)Int_val(off);
glVertexAttribPointer(glloc, glsize, Floattype_val(type), GL_TRUE, glstride, gloffset);
CAMLreturn(Val_unit);
}
// INPUT an attribute location, its size, its type,
// an offset, a stride
// OUTPUT nothing, sets the float attribute pointer
CAMLprim value
caml_attrib_int(value loc, value size, value type, value off, value stride)
{
CAMLparam5(loc, size, type, off, stride);
GLuint glloc = (GLuint)Int_val(loc);
GLint glsize = Int_val(size);
GLsizei glstride = Int_val(stride);
GLvoid* gloffset = (GLvoid*)Int_val(off);
glVertexAttribIPointer(glloc, glsize, Inttype_val(type), glstride, gloffset);
CAMLreturn(Val_unit);
}
// INPUT a draw mode, two indices (start, end)
// OUTPUT nothing, draws the currently bound VAO
CAMLprim value
caml_draw_arrays(value mode, value start, value end)
{
CAMLparam3(mode, start, end);
glDrawArrays(Drawmode_val(mode), Int_val(start), Int_val(end));
CAMLreturn(Val_unit);
}
// INPUT a draw mode, a number of elements
// OUTPUT nothing, draws the requested number of elements from
// the currently bound EBO and VAO
CAMLprim value
caml_draw_elements(value mode, value first, value nb)
{
CAMLparam2(mode, nb);
glDrawElements(Drawmode_val(mode), Int_val(nb), GL_UNSIGNED_INT, (GLvoid*)Int_val(first));
CAMLreturn(Val_unit);
}
|
laser-turtle/ogaml
|
src/core/windows/stubs/pixelformat_stubs.c
|
#include "utils.h"
#include <windows.h>
#include <wingdi.h>
#include <memory.h>
CAMLprim value
caml_simple_pfmt_descriptor(value hwnd, value depth, value stencil)
{
CAMLparam3(hwnd, depth, stencil);
PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
32,
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
Int_val(depth),
Int_val(stencil),
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
PIXELFORMATDESCRIPTOR* result = malloc(sizeof(PIXELFORMATDESCRIPTOR));
*result = pfd;
CAMLreturn((value)result);
}
CAMLprim value
caml_choose_pixelformat(value hwnd, value descriptor)
{
CAMLparam2(hwnd,descriptor);
HDC handle = GetDC((HWND)hwnd);
PIXELFORMATDESCRIPTOR* pfd = (PIXELFORMATDESCRIPTOR*)descriptor;
int pfmt = ChoosePixelFormat(handle,pfd);
CAMLreturn((value)pfmt);
}
CAMLprim value
caml_set_pixelformat(value hwnd, value descriptor, value format)
{
CAMLparam3(hwnd, descriptor, format);
HDC handle = GetDC((HWND)hwnd);
PIXELFORMATDESCRIPTOR* pfd = (PIXELFORMATDESCRIPTOR*)descriptor;
SetPixelFormat(handle,(int)format,pfd);
CAMLreturn(Val_unit);
}
CAMLprim value
caml_destroy_pfmt_descriptor(value descriptor)
{
CAMLparam1(descriptor);
PIXELFORMATDESCRIPTOR* pfd = (PIXELFORMATDESCRIPTOR*)descriptor;
free(pfd);
CAMLreturn(Val_unit);
}
|
myoKun345/RcppCWB
|
src/cwb/cqp/eval.c
|
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <limits.h>
#include <math.h>
/* we can't include <search.h> since we then get conflicts with leaf type */
#include <sys/types.h> /* required for regex */
#include "../cl/globals.h"
#include "../cl/macros.h"
#include "../cl/corpus.h"
#include "../cl/attributes.h"
#include "../cl/cdaccess.h"
#include "../cl/special-chars.h"
#include "cqp.h"
#include "ranges.h"
#include "options.h"
#include "tree.h"
#include "symtab.h"
#include "corpmanag.h"
#include "regex2dfa.h"
#include "eval.h"
#include "builtins.h"
#include "output.h"
#include "matchlist.h"
#define no_match -1
#define RED_THRESHOLD 0.01
/**
* Counts the number of token positions encompassed by all members
* of the ->range array of the CorpusList argument.
*
* That is, in oher words, it tells you the size of this corpus.
*/
int
nr_positions(CorpusList *cp)
{
int nr_pos, i;
assert(cp);
nr_pos = -1;
if (cp->size >= 0) {
nr_pos = 0;
for (i = 0; i < cp->size; i++)
nr_pos += cp->range[i].end - cp->range[i].start + 1;
}
return nr_pos;
}
float
red_factor(CorpusList *cp, int *nr_pos)
{
int size;
Attribute *attr;
assert(cp);
if (!access_corpus(cp))
return 0.0;
if ((attr = find_attribute(cp->corpus, DEFAULT_ATT_NAME, ATT_POS, NULL)) == NULL)
return 0.0;
if ((size = cp->mother_size) < 0)
return 0.0;
if ((*nr_pos = nr_positions(cp)) < 0)
return 0.0;
return (*nr_pos + 0.0) / (size + 0.0);
}
/**
* Set the appropriate values to the corpus id (given by its pointer to
* the symbol table).
*/
void
set_corpus_matchlists(CorpusList *cp,
Matchlist *matchlist,
int nr_lists,
int keep_old_ranges)
{
int i;
if (keep_old_ranges) {
int rp, mp;
/* delete the ranges which didn't lead to a match */
/* TODO: Interaction with target @ settings */
cl_free(cp->sortidx);
/* keep keywords, ranges, targets */
mp = 0;
rp = 0;
while (rp < cp->size) {
if (mp < matchlist[0].tabsize) {
if (matchlist[0].start[mp] >= cp->range[rp].start) {
if (matchlist[0].start[mp] > cp->range[rp].end ||
matchlist[0].end[mp] > cp->range[rp].end) {
/* the match is not wholly within the current range */
cp->range[rp++].start = -1;
}
else {
/* this match lies within the current range. So keep
* that range and increment.
*/
rp ++;
}
}
else
/* match.start < range.start */
mp++;
}
else {
/* mp >= matchlist[0].tabsize */
/* we can't find a matchlist element, so mark the range as deleted */
cp->range[rp++].start = -1;
}
}
(void) RangeSetop(cp, RReduce, NULL, NULL);
}
else {
cl_free(cp->range);
cl_free(cp->targets);
cl_free(cp->keywords);
cl_free(cp->sortidx);
if (matchlist[0].tabsize > 0)
cp->range =
(Range *)cl_malloc(sizeof(Range) * matchlist[0].tabsize);
cp->size = matchlist[0].tabsize;
for (i = 0; i < matchlist[0].tabsize; i++) {
cp->range[i].start = matchlist[0].start[i];
cp->range[i].end = matchlist[0].end[i];
}
if (matchlist[0].target_positions) {
cp->targets = matchlist[0].target_positions;
matchlist[0].target_positions = NULL;
}
assert((nr_lists <= 1) && "set_corpus_matchlists(): multiple lists not supported!");
}
}
/**
* Gets a list of corpus positions where the given p-attribute has
* the specified form.
*
* Positions are placed into the "start" array of the matchlist.
*
* @param attribute The p-attribute to search.
* @param wordform The form to search for.
* @param matchlist Where to put the results.
* @return The size of the resulting matchlist table
* (also stored in its tabsize member).
*/
int
get_corpus_positions(Attribute *attribute,
char *wordform,
Matchlist *matchlist)
{
int word_id;
assert(attribute);
assert(matchlist);
assert(matchlist->start == NULL);
word_id = cl_str2id(attribute, wordform);
if ((word_id >= 0) && (cl_errno == CDA_OK)) {
/* get the positions of the id in the attribute */
matchlist->start = cl_idlist2cpos(attribute,
&word_id,
1,
1,
&(matchlist->tabsize));
matchlist->matches_whole_corpus = 0;
}
if (initial_matchlist_debug &&
(matchlist->start != NULL) &&
(matchlist->tabsize > 0) && !silent)
Rprintf("matched initial wordform for non-regex %s, "
"%d matches\n", wordform, matchlist->tabsize);
return(matchlist->tabsize);
}
/**
* Get corpus positions matching a regular expression on a given attribute.
*
* get_matched_corpus_positions looks in a corpus which is to be loaded for
* a regular expression 'regstr' of a given p-attribute and returns the table
* of matching start indices (start_table) and the tablesize (tabsize).
*
* @param attribute The attribute to search on. May be NULL, in
* which case DEFAULT_ATT_NAME is used.
* @param regstr String containing the regular expression.
* @param canonicalize Flags to be passed to the CL regex engine.
* @param matchlist Location where the list of matches will be placed.
* @param restrictor_list Passed to cl_idlist2cpos_oldstyle
* @param restrictor_size Passed to cl_idlist2cpos_oldstyle
* @return The number of matches found.
*/
int
get_matched_corpus_positions(Attribute *attribute,
char *regstr,
int canonicalize,
Matchlist *matchlist,
int *restrictor_list,
int restrictor_size)
{
int *word_ids, nr_of_words, i, size, range;
assert(matchlist);
assert(matchlist->start == NULL);
matchlist->is_inverted = 0;
if (attribute == NULL)
attribute = cl_new_attribute_oldstyle(evalenv->query_corpus->corpus,
DEFAULT_ATT_NAME,
ATT_POS,
NULL);
assert(attribute);
size = cl_max_cpos(attribute);
range = cl_max_id(attribute);
/* changed .* / .+ optimization to .* only -- so "" will be handled correctly as an attribute value
(will be standard in CWB 4.0, and may happen now if someone runs encode with -U "") */
/* AH notes Aug 2011: the above comment about 4.0 has nothing to do with the TODO-4.0 plan I sketched out! */
if (STREQ(regstr, ".*")) {
if (eval_debug)
Rprintf("get_matched_corpus_positions: .* optimization\n");
matchlist->start = (int *)cl_malloc(sizeof(int) * size);
/* we here produce a copy of a system corpus. TODO: optimize that with the "matches_whole_corpus"-flag. */
for (i = 0; i < size; i++)
matchlist->start[i] = i;
matchlist->tabsize = size;
matchlist->matches_whole_corpus = 1;
}
else {
/* get the word ids of the word forms which are matched by the regular expression 'regstr' */
word_ids = cl_regex2id(attribute,
regstr,
canonicalize,
&nr_of_words);
if (nr_of_words == range) {
/* again, matches whole corpus. TODO: optimize. */
matchlist->start = (int *)cl_malloc(sizeof(int) * size);
/* we here produce a copy of a system corpus. TODO: optimize that
* with the "matches_whole_corpus"-flag.
*/
for (i = 0; i < size; i++)
matchlist->start[i] = i;
matchlist->tabsize = size;
matchlist->matches_whole_corpus = 1;
cl_free(word_ids);
}
else if ((word_ids != NULL) && (nr_of_words > 0)) {
/* Some matching wordforms have been found. */
/* get the position numbers in the active corpus of the word ids */
matchlist->start = cl_idlist2cpos_oldstyle(attribute,
word_ids,
nr_of_words,
1,
&(matchlist->tabsize),
restrictor_list,
restrictor_size);
cl_free(word_ids);
}
else {
/* no matching wordforms have been found. */
matchlist->tabsize = 0;
matchlist->matches_whole_corpus = 0;
}
} /* end case where regstr is not ".*" */
/* finally, possibly print out a debug message */
if (initial_matchlist_debug &&
(matchlist->start != NULL) &&
(matchlist->tabsize > 0) && !silent)
Rprintf("matched initial pattern for regex %s, %d matches\n",
regstr,
matchlist->tabsize);
return(matchlist->tabsize);
}
/*
* This is the function which evaluates an AVS to true or false.
*/
/* labelrefs is the reference table for the current state (needed to set labels/targets) */
/* target_labelrefs is the reference table of the target state; if the constraint is fulfilled, */
/* eval_constraint() has to copy labelrefs to target_labelrefs and set labels there. */
Boolean
eval_constraint(AVS avs, int corppos, RefTab labelrefs, RefTab target_labelrefs)
{
int start, end, struc, anchor;
int result = False;
CorpusList *corpus;
switch (avs->type) {
case Tag:
struc = cl_cpos2struc(avs->tag.attr, corppos);
if (struc < 0)
return False;
cl_struc2cpos(avs->tag.attr, struc, &start, &end);
/* opening tag */
if (avs->tag.is_closing == False) {
result = (corppos == start) ? True : False;
/* evaluate optional constraint only when at start of region */
if (result && avs->tag.constraint) {
char *val = cl_struc2str(avs->tag.attr, struc);
if (val) {
if (avs->tag.rx)
result = cl_regex_match(avs->tag.rx, val, 0); /* pre-compiled regex available */
else
result = (0 == strcmp(avs->tag.constraint, val)); /* no pre-compiled regex -> match as plain string */
}
else
result = False;
if (avs->tag.negated)
result = !result;
}
}
/* closing tag */
else {
result = (corppos == end) ? True : False;
if (strict_regions && (avs->tag.right_boundary != NULL)) {
int rbound = get_reftab(labelrefs, avs->tag.right_boundary->ref, -1);
if ((rbound < 0) || (corppos != rbound)) /* check that a within region constraint was set by an open tag, and that this is the matching close tag! */
result = False; /* (so that <s> []* </s> will work and <s></s> won't match, plus some more exotic cases) */
}
}
if (result) {
dup_reftab(labelrefs, target_labelrefs);
/* in StrictRegions mode, set corresponding label (open tag) or clear it (close tag) */
if (strict_regions && (avs->tag.right_boundary != NULL)) {
if (avs->tag.is_closing == False) /* open tag */
set_reftab(target_labelrefs, avs->tag.right_boundary->ref, end);
else /* close tag */
set_reftab(target_labelrefs, avs->tag.right_boundary->ref, -1);
}
}
return result;
case Anchor:
corpus = evalenv->query_corpus;
switch (avs->anchor.field) {
case MatchField:
anchor = corpus->range[evalenv->rp].start;
break;
case MatchEndField:
anchor = corpus->range[evalenv->rp].end;
break;
case TargetField:
assert("Internal error in eval_constraint()" && corpus->targets != NULL);
anchor = corpus->targets[evalenv->rp];
break;
case KeywordField:
assert("Internal error in eval_constraint()" && corpus->keywords != NULL);
anchor = corpus->keywords[evalenv->rp];
break;
default:
assert("Internal error in eval_constraint(): no handler for anchor." && 0);
}
/* we don't have to worry about whether it's an opening or closing anchor tag,
* because corppos already is the _effective_ cpos (passed from simulate()) */
result = ((anchor >= 0) && (anchor == corppos)) ? True : False;
/* don't forget to copy the reftab to the target state */
if (result)
dup_reftab(labelrefs, target_labelrefs);
return result;
case Pattern:
/* used to reset the list of labels (kill forward references) here */
/* Ah great, so labels can only be set by the _last_ active candidate,
because it will erase all the labels set by earlier candidates for
this point. However, if we keep labels pointing to the current
cpos, we should be OK (assuming that all states progress in parallel
along the corpus). This should enable us to get optional labels at
least. If several candidates pass through the same labelled pattern
at different times, though, that label will be re-set whenever
a candidate arrives; this is simply because CQP doesn't have a full
labels implementation. Rats.
*/
/* if (evalenv->labels)
reset_labellist(evalenv->labels, corppos+1); */
/* we're resetting from corppos+1 because another active state may just
have set a label to the current corppos! */
/* Got some rat poison now, i.e. a new labels implementation !!! */
/* now evaluate the pattern */
result = eval_bool(avs->con.constraint, labelrefs, corppos);
/* if the current constraint is labelled, set the
corresponding label value; but _only_ if result is True,
i.e. if the automaton actually reaches that state!
*/
if (result) {
dup_reftab(labelrefs, target_labelrefs); /* copy labels to target state & set label there*/
if (avs->con.label != NULL)
set_reftab(target_labelrefs, avs->con.label->ref, corppos);
}
/* return the evaluation of the bool tree of the constraint */
return result;
case MatchAll:
/* if (evalenv->labels) !!! RAT POISON !!!
reset_labellist(evalenv->labels, corppos+1); */
dup_reftab(labelrefs, target_labelrefs);
if (avs->matchall.label != NULL)
set_reftab(target_labelrefs, avs->matchall.label->ref, corppos);
return True;
}
assert(0 && "Not reached");
return 0;
}
/* get the corpus position referenced by a label wrt. to the reference table rt */
/* (corppos used to be required for anchor labels, which are now removed, but it'll be useful for the 'this' label) */
int
get_label_referenced_position(LabelEntry label, RefTab rt, int corppos)
{
int referenced_position = -1;
if (label) {
referenced_position = get_reftab(rt, label->ref, corppos);
if (eval_debug)
Rprintf("Evaluating label %s = %d\n", label->name, referenced_position);
}
return referenced_position;
}
Boolean
get_leaf_value(Constrainttree ctptr,
RefTab rt, /* label reference table of the current simulation */
int corppos,
DynCallResult *dcr,
int deliver_strings)
{
int pos, rv;
DynCallResult *fargs;
ActualParamList *p;
Boolean params_ok;
int struc_start, struc_end;
assert(ctptr);
dcr->type = ATTAT_NONE;
switch (ctptr->type) {
case func:
if (ctptr->func.nr_args > 0) {
fargs = (DynCallResult *)cl_malloc(sizeof(DynCallResult) * ctptr->func.nr_args);
if (fargs == NULL)
return False;
pos = 0;
params_ok = True;
for (p = ctptr->func.args; (p != NULL) &&
(pos < ctptr->func.nr_args) &&
params_ok;
p = p->next, pos++)
params_ok = get_leaf_value(p->param, rt, corppos, &(fargs[pos]), 1);
/* we don't want to crash when one of the args can't be computed!) */
assert(!params_ok || pos == ctptr->func.nr_args);
if (params_ok) {
if (ctptr->func.predef >= 0) {
rv = call_predefined_function(ctptr->func.predef,
fargs,
pos,
ctptr,
dcr);
free(fargs);
/* if the evaluation of a builtin function fails, this is usually due to a usage error;
-> abort query evaluation to avoid hundreds or thousands of error messages (simulate Ctrl-C signal) */
if (!rv)
EvaluationIsRunning = 0;
return rv;
}
else {
assert(ctptr->func.dynattr);
pos = call_dynamic_attribute(ctptr->func.dynattr,
dcr,
fargs,
ctptr->func.nr_args);
free(fargs);
return ((pos == 1) && (cderrno == CDA_OK)) ? True : False;
}
}
else {
/* parameter cannot be calculated */
free(fargs);
return False;
}
}
else
return False;
break;
case pa_ref:
if (ctptr->pa_ref.attr == NULL) {
/* label reference without an attribute -> returns referenced corpus position */
assert(ctptr->pa_ref.label);
dcr->type = ATTAT_POS;
dcr->value.intres = get_label_referenced_position(ctptr->pa_ref.label, rt, corppos);
if (ctptr->pa_ref.delete) {
if (eval_debug)
Rprintf("** AUTO-DELETING LABEL %s = %d\n",
ctptr->pa_ref.label->name, dcr->value.intres);
set_reftab(rt, ctptr->pa_ref.label->ref, -1);
}
return True;
}
else {
int referenced_position;
if (ctptr->pa_ref.label == NULL)
referenced_position = corppos;
else {
referenced_position = get_label_referenced_position(ctptr->pa_ref.label, rt, corppos);
if (ctptr->pa_ref.delete) {
if (eval_debug)
Rprintf("** AUTO-DELETING LABEL %s = %d\n",
ctptr->pa_ref.label->name, referenced_position);
set_reftab(rt, ctptr->pa_ref.label->ref, -1);
}
if (referenced_position < 0) {
dcr->type = ATTAT_NONE;
return True;
}
}
if (deliver_strings) {
dcr->type = ATTAT_STRING;
dcr->value.charres = get_string_at_position(ctptr->pa_ref.attr,
referenced_position);
}
else {
dcr->type = ATTAT_PAREF;
dcr->value.parefres.attr = ctptr->pa_ref.attr;
assert(dcr->value.parefres.attr);
dcr->value.parefres.token_id = get_id_at_position(ctptr->pa_ref.attr,
referenced_position);
}
return (cderrno == CDA_OK) ? True : False;
}
break;
case sa_ref:
if (ctptr->sa_ref.label == NULL) {
/* bare reference to S-attribute -> old behaviour */
dcr->type = ATTAT_INT;
dcr->value.intres = 0;
if (get_struc_attribute(ctptr->sa_ref.attr,
corppos,
&struc_start, &struc_end)) {
if (corppos == struc_start)
dcr->value.intres += 1;
if (corppos == struc_end)
dcr->value.intres += 2;
/* new: make sure the value of an saref (without values) is
non-zero (i.e. evaluates to True) as long as we are within a region */
if ((corppos >= struc_start) && (corppos <= struc_end))
dcr->value.intres += 4;
/* not really necessary, since get_struc_attribute() returns 0 if we're not inside a region */
}
else if (cderrno != CDA_ESTRUC) { /* get_struc_attribtue() sets cderrno=CDA_EDSTRUC if not in region */
return False; /* this _is_ an error */
}
return True;
}
else {
/* label reference to S-attribute -> return value of containing region */
int referenced_position = get_label_referenced_position(ctptr->sa_ref.label, rt, corppos);
if (ctptr->sa_ref.delete) {
if (eval_debug)
Rprintf("** AUTO-DELETING LABEL %s = %d\n",
ctptr->sa_ref.label->name, referenced_position);
set_reftab(rt, ctptr->sa_ref.label->ref, -1);
}
if (referenced_position < 0) {
dcr->type = ATTAT_NONE; /* don't know what it does; copied from pa_ref */
return True;
}
dcr->type = ATTAT_STRING;
dcr->value.charres = structure_value_at_position(ctptr->sa_ref.attr,
referenced_position);
/* structure_value_at_position() sets CDA_EPOSORNG if not in region */
if (cderrno == CDA_EPOSORNG) {
dcr->type = ATTAT_NONE; /* reasonable behaviour: return ATTAT_NONE if not in region */
return True;
}
return (cderrno == CDA_OK) ? True : False;
}
break;
case string_leaf:
if (ctptr->leaf.pat_type == CID) {
/*
* that's quick & dirty. We should have a cidref node
*/
dcr->type = ATTAT_INT;
dcr->value.intres = ctptr->leaf.ctype.cidconst;
}
else {
dcr->type = ATTAT_STRING;
dcr->value.charres = ctptr->leaf.ctype.sconst;
}
return True;
break;
case float_leaf:
dcr->type = ATTAT_FLOAT;
dcr->value.floatres = ctptr->leaf.ctype.fconst;
break;
case int_leaf:
dcr->type = ATTAT_INT;
dcr->value.intres = ctptr->leaf.ctype.iconst;
return True;
break;
default:
cqpmessage(Error,
"get_leaf_value(): Illegal node type %d\n",
__FILE__, ctptr->type);
EvaluationIsRunning = 0;
return False;
break;
}
assert(0 && "Not reached");
return 0;
}
/** Comparison function used when eval_bool() calls qsort(). */
static int
intcompare(const void *i, const void *j)
{
return(*(int *)i - *(int *)j);
}
/**
* evaluate the boolean constraint tree by using recursion;
* "corppos" is the current corpus position
*/
Boolean
eval_bool(Constrainttree ctptr, RefTab rt, int corppos)
{
DynCallResult lhs, rhs;
int start, end, id;
int referenced_corppos;
if (ctptr)
if (ctptr->type == bnode) {
switch(ctptr->node.op_id) {
/* logical and */
case b_and:
if (eval_debug)
Rprintf("eval_bool: evaluate boolean and\n");
assert((ctptr->node.left != NULL) && (ctptr->node.right != NULL));
return(eval_bool(ctptr->node.left, rt, corppos) &&
eval_bool(ctptr->node.right, rt, corppos));
break;
/* logical or */
case b_or:
if (eval_debug)
Rprintf("eval_bool: evaluate boolean or\n");
assert((ctptr->node.left != NULL) && (ctptr->node.right != NULL));
return(eval_bool(ctptr->node.left, rt, corppos) ||
eval_bool(ctptr->node.right, rt, corppos));
break;
/* logical implication */
case b_implies:
if (eval_debug)
Rprintf("eval_bool: evaluate boolean implication\n");
assert((ctptr->node.left != NULL) && (ctptr->node.right != NULL));
return((eval_bool(ctptr->node.left, rt, corppos)) ? eval_bool(ctptr->node.right, rt, corppos) : True);
break;
/* logical not */
case b_not:
if (eval_debug)
Rprintf("eval_bool: evaluate boolean not\n");
if (!ctptr->node.left)
return(True);
assert(ctptr->node.right == NULL);
return(!eval_bool(ctptr->node.left, rt, corppos));
break;
/* relational operators */
case cmp_gt:
case cmp_lt:
case cmp_get:
case cmp_let:
case cmp_eq:
case cmp_neq:
case cmp_ex:
if (eval_debug)
Rprintf("eval_bool: evaluate comparisons\n");
/* check presence of arguments */
assert((ctptr->node.left != NULL) &&
((ctptr->node.op_id == cmp_ex) || (ctptr->node.right != NULL)));
/*
* LHS:
* -- Attribute reference (type String)
* -- Function call (type String or Integer)
* -- Qualified Label reference (type String)
*/
switch (ctptr->node.left->type) {
case func:
case pa_ref:
case sa_ref: /* label refernce to S-attribute with values */
if (get_leaf_value(ctptr->node.left, rt, corppos, &lhs, 0) == False)
return False;
break;
default:
cqpmessage(Error,
"Illegal type (%d) of LHS argument in pattern.",
ctptr->node.left->type);
EvaluationIsRunning = 0;
return False;
break;
}
/* if we only check for existence of a value, the RHS is neglected */
if (ctptr->node.op_id == cmp_ex)
switch (lhs.type) {
case ATTAT_STRING:
return (lhs.value.charres != NULL);
break;
case ATTAT_PAREF:
return (lhs.value.parefres.token_id >= 0 ? 1 : 0);
break;
case ATTAT_FLOAT:
return (lhs.value.floatres == 0.0 ? 0 : 1);
break;
case ATTAT_INT:
return (lhs.value.intres == 0) ? 0 : 1;
break;
case ATTAT_POS: /* returned by bare label references */
return (lhs.value.intres >= 0) ? 1 : 0;
break;
case ATTAT_NONE: /* undefined value, always evaluates to False */
return 0;
break;
default:
cqpmessage(Error,
"Illegal type (%d) of existence expression.",
lhs.type);
EvaluationIsRunning = 0;
return False;
}
/* otherwise, we have to compute & check the RHS */
assert(ctptr->node.right != NULL);
switch(ctptr->node.right->type) {
case func:
case pa_ref:
case sa_ref:
case int_leaf:
case float_leaf:
case string_leaf:
if (get_leaf_value(ctptr->node.right, rt, corppos, &rhs, 0) == False)
return False;
break;
default:
cqpmessage(Error,
"Illegal type (%d) of RHS argument in pattern.",
ctptr->node.right->type);
EvaluationIsRunning = 0;
return False;
break;
}
/* OK. We now evaluate the relational operator */
/* make it easier in case of ints */
if (lhs.type == ATTAT_POS)
lhs.type = ATTAT_INT;
if (rhs.type == ATTAT_POS)
rhs.type = ATTAT_INT;
if ((lhs.type == ATTAT_NONE) || (rhs.type == ATTAT_NONE))
/* cannot evaluate */
return False;
if (lhs.type == ATTAT_PAREF && rhs.type == ATTAT_INT) {
if (ctptr->node.op_id == cmp_eq)
return (lhs.value.parefres.token_id == rhs.value.intres ? 1 : 0);
else if (ctptr->node.op_id == cmp_neq)
return (lhs.value.parefres.token_id != rhs.value.intres ? 1 : 0);
else {
cqpmessage(Error,
"Comparison operators >, >=, <, <= not allowed for p-attribute.");
EvaluationIsRunning = 0;
return False;
}
}
else if (lhs.type == ATTAT_PAREF && rhs.type == ATTAT_PAREF) {
if (lhs.value.parefres.attr == NULL || rhs.value.parefres.attr == NULL) {
cqpmessage(Error,
"Missing p-attribute on PAREF (lhs or rhs)");
EvaluationIsRunning = 0;
return False;
}
else if (lhs.value.parefres.attr == rhs.value.parefres.attr)
switch (ctptr->node.op_id) {
case cmp_eq:
return lhs.value.parefres.token_id == rhs.value.parefres.token_id;
break;
case cmp_neq:
return lhs.value.parefres.token_id != rhs.value.parefres.token_id;
break;
default:
cqpmessage(Error,
"Comparison operators >, >=, <, <= not allowed between p-attributes.");
EvaluationIsRunning = 0;
return False;
break;
}
else {
char *ls, *rs;
ls = get_string_of_id(lhs.value.parefres.attr, lhs.value.parefres.token_id);
rs = get_string_of_id(rhs.value.parefres.attr, rhs.value.parefres.token_id);
switch (ctptr->node.op_id) {
case cmp_eq:
return strcmp(ls, rs) == 0;
break;
case cmp_neq:
return strcmp(ls, rs) != 0;
break;
default:
cqpmessage(Error,
"Comparison operators >, >=, <, <= not allowed between p-attributes.");
EvaluationIsRunning = 0;
return False;
break;
}
}
}
else if ((lhs.type == ATTAT_PAREF || lhs.type == ATTAT_STRING)
&& (rhs.type == ATTAT_STRING || rhs.type == ATTAT_PAREF)) {
/* ok. we have strings or parefs on both sides. we cannot have
* parefs both left and right, since this is handled above.
*/
char *ls, *rs;
ls = NULL; rs = NULL;
if (lhs.type == ATTAT_PAREF) {
assert(lhs.value.parefres.attr);
ls = get_string_of_id(lhs.value.parefres.attr, lhs.value.parefres.token_id);
if ((ls == NULL) || cderrno != CDA_OK) {
cqpmessage(Error,
"Error accessing p-attribute %s (lexicon ID #%d).",
lhs.value.parefres.attr->any.name, lhs.value.parefres.token_id);
EvaluationIsRunning = 0;
return False;
}
}
else
ls = lhs.value.charres;
if (rhs.type == ATTAT_PAREF) {
assert(rhs.value.parefres.attr);
rs = get_string_of_id(rhs.value.parefres.attr, rhs.value.parefres.token_id);
if ((rs == NULL) || cderrno != CDA_OK) {
cqpmessage(Error,
"Error accessing p-attribute %s (lexicon ID #%d).",
rhs.value.parefres.attr->any.name, rhs.value.parefres.token_id);
EvaluationIsRunning = 0;
return False;
}
}
else
rs = rhs.value.charres;
assert(rs && ls);
assert(ctptr->node.right);
/* The string on the right sight can be either a RegExp or a literal string.
RegExps may only occur in string leafs, i.e. strings entered directly in the
query. All other string values (such as paref's or saref's or return values
of function calls are literal strings */
if ((ctptr->node.right->type != string_leaf) ||
(ctptr->node.right->leaf.pat_type == NORMAL))
/* literal string */
return ((ctptr->node.op_id == cmp_eq) ? STREQ(ls, rs) : !STREQ(ls, rs));
else if (ctptr->node.right->leaf.pat_type == REGEXP) {
/* RegExp */
if (STREQ(rs, ".*")) /* see note about .* / .+ optimization above */
return (ctptr->node.op_id == cmp_eq) ? True : False;
else {
/* perform a regular expression match of the two */
return((ctptr->node.op_id == cmp_eq) ?
cl_regex_match(ctptr->node.right->leaf.rx, ls, 0) :
!cl_regex_match(ctptr->node.right->leaf.rx, ls, 0));
}
}
else {
cqpmessage(Error,
"Internal error in eval_bool()<eval.c>: right->pat_type == CID???");
EvaluationIsRunning = 0;
return False;
}
}
if (lhs.type != rhs.type) {
cqpmessage(Error,
"LHS type (%d) doesn't match RHS type (%d), can't compare.",
lhs.type, rhs.type);
EvaluationIsRunning = 0;
return False;
}
switch (lhs.type) {
case ATTAT_INT:
switch (ctptr->node.op_id) {
case cmp_gt:
return lhs.value.intres > rhs.value.intres;
break;
case cmp_lt:
return lhs.value.intres < rhs.value.intres;
break;
case cmp_get:
return lhs.value.intres >= rhs.value.intres;
break;
case cmp_let:
return lhs.value.intres <= rhs.value.intres;
break;
case cmp_eq:
return lhs.value.intres == rhs.value.intres;
break;
case cmp_neq:
return lhs.value.intres != rhs.value.intres;
break;
default:
cqpmessage(Error,
"Illegal numerical comparison operator (%d).",
ctptr->node.op_id);
EvaluationIsRunning = 0;
return False;
break;
}
break;
case ATTAT_FLOAT:
switch (ctptr->node.op_id) {
case cmp_gt:
return lhs.value.floatres > rhs.value.floatres;
break;
case cmp_lt:
return lhs.value.floatres < rhs.value.floatres;
break;
case cmp_get:
return lhs.value.floatres >= rhs.value.floatres;
break;
case cmp_let:
return lhs.value.floatres <= rhs.value.floatres;
break;
case cmp_eq:
return lhs.value.floatres == rhs.value.floatres;
break;
case cmp_neq:
return lhs.value.floatres != rhs.value.floatres;
break;
default:
cqpmessage(Error,
"Illegal numerical comparison operator (%d).",
ctptr->node.op_id);
EvaluationIsRunning = 0;
return False;
break;
}
break;
case ATTAT_PAREF:
case ATTAT_STRING:
case ATTAT_POS:
case ATTAT_VAR:
default:
assert(0);
break;
}
/* are we still here? */
assert("In principle, this should be a non-reachable point. Sorry." && 0);
break;
default:
cqpmessage(Error,
"Illegal boolean operand (%d) in pattern.\n",
ctptr->node.op_id);
EvaluationIsRunning = 0;
return False;
break;
}
}
else if (ctptr->type == cnode) {
return ctptr->constnode.val == 0 ? False : True;
}
else if (ctptr->type == id_list) {
int res;
if (eval_debug)
Rprintf("eval_bool: evaluate id_list membership\n");
assert(ctptr->idlist.attr);
if (ctptr->idlist.label) {
referenced_corppos = get_label_referenced_position(ctptr->idlist.label, rt, corppos);
if (ctptr->idlist.delete) {
if (eval_debug)
Rprintf("** AUTO-DELETING LABEL %s = %d\n",
ctptr->idlist.label->name, referenced_corppos);
set_reftab(rt, ctptr->idlist.label->ref, -1);
}
}
else {
referenced_corppos = corppos;
}
if (ctptr->idlist.nr_items <= 0)
res = 0; /* never member */
else {
id = get_id_at_position(ctptr->idlist.attr, referenced_corppos);
if (id >= 0)
res = bsearch((char *)&id,
(char *)(ctptr->idlist.items),
ctptr->idlist.nr_items,
sizeof(int),
intcompare) == NULL ? 0 : 1;
else
res = 0;
}
if (ctptr->idlist.negated)
return !res;
else
return res;
}
else if (ctptr->type == sbound) {
assert("Not reached any more" && 0 && ctptr->sbound.strucattr != NULL);
if (!get_struc_attribute(ctptr->sbound.strucattr, corppos, &start, &end) ||
(cderrno != CDA_OK))
return False;
else {
if (ctptr->sbound.is_closing == False)
/* opening tag */
return (corppos == start) ? True : False;
else
/* closing tag */
return (corppos == end) ? True : False;
}
}
else {
cqpmessage(Error,
"Internal error in eval_bool()<eval.c>: Illegal node type %d.",
ctptr->type);
EvaluationIsRunning = 0;
return False;
}
else
return(True);
assert(0 && "Not reached");
return 0;
}
int
mark_offrange_cells(Matchlist *matchlist, CorpusList *corpus)
{
int rp, i, del;
rp = 0;
i = 0;
del = 0;
assert(matchlist);
assert(corpus);
/* this is only of importance when we are working on a subcorpus.
* Test that. */
assert(corpus->mother_size > 0);
if ((corpus->size == 1) &&
(corpus->range[0].start == 0) &&
(corpus->range[0].end == corpus->mother_size - 1))
return 0;
while (i < matchlist->tabsize) {
if ((rp >= corpus->size) ||
(matchlist->start[i] < corpus->range[rp].start)) {
matchlist->start[i] = -1;
if (matchlist->end)
matchlist->end[i] = -1;
i++;
del++;
}
else if (matchlist->start[i] > corpus->range[rp].end)
rp++;
else
i++;
}
return del;
}
/**
* Gets the inital list of matches for a query.
*
* NB. This function is called recursively.
*
* @return False iff something has gone wrong.
*/
Boolean
calculate_initial_matchlist_1(Constrainttree ctptr,
Matchlist *matchlist,
CorpusList *corpus)
{
int i;
Matchlist left, right;
/* do NOT use free_matchlist here! */
init_matchlist(&left);
init_matchlist(&right);
if (ctptr) {
if (ctptr->type == bnode) {
switch(ctptr->node.op_id) {
case b_and: /* logical and */
assert(ctptr->node.left && ctptr->node.right);
/* just the beginnings of an implementation for the b_and operator (by oli);
never mind, the entire <eval.c> code will have to be rewritten at some point
TODO */
#ifdef INITIAL_MATCH_BY_MU
if (calculate_initial_matchlist_1(ctptr->node.left, &left, corpus) &&
calculate_initial_matchlist_1(ctptr->node.right, &right, corpus)) {
Setop(&left, Intersection, &right);
free_matchlist(&right);
matchlist->start = left.start;
matchlist->end = left.end;
matchlist->tabsize = left.tabsize;
matchlist->matches_whole_corpus = 0;
matchlist->is_inverted = 0;
return True;
}
else {
free_matchlist(matchlist)
free_matchlist(&left);
free_matchlist(&right);
return False;
}
#else
/* this is the old code. */
if (calculate_initial_matchlist_1(ctptr->node.left, &left, corpus)) {
/* We have b_and. So try to eval the right tree for each
* position yielded by the left tree. */
for (i = 0; i < left.tabsize; i++) {
if (!EvaluationIsRunning)
break;
if (left.start[i] >= 0 &&
!eval_bool(ctptr->node.right, NULL, left.start[i]))
/* we're ignoring labels at the moment, so we pass NULL as reftab */
left.start[i] = -1;
}
if (!Setop(&left, Reduce, NULL))
return False;
matchlist->start = left.start;
matchlist->end = left.end;
matchlist->tabsize = left.tabsize;
matchlist->matches_whole_corpus = 0;
return True;
}
else {
free_matchlist(matchlist);
free_matchlist(&left);
free_matchlist(&right);
return False;
}
#endif
break;
case b_or: /* logical or */
if (eval_debug)
Rprintf("calc_initial_ml: boolean or\n");
assert(ctptr->node.left && ctptr->node.right);
if (calculate_initial_matchlist_1(ctptr->node.left, &left, corpus) &&
calculate_initial_matchlist_1(ctptr->node.right, &right, corpus)) {
if (left.is_inverted)
if (!Setop(&left, Complement, NULL))
return False;
if (right.is_inverted)
if (!Setop(&right, Complement, NULL))
return False;
if (!Setop(&left, Union, &right))
return False;
free_matchlist(&right);
matchlist->start = left.start;
matchlist->end = left.end;
matchlist->tabsize = left.tabsize;
matchlist->matches_whole_corpus = left.matches_whole_corpus;
matchlist->is_inverted = 0;
return True;
}
else {
free_matchlist(matchlist);
free_matchlist(&left);
free_matchlist(&right);
return False;
}
break;
case b_implies: /* logical implication (not optimised in query initial position) */
/* for the moment, this is just a ridiculous dummy implementation; replace when tables are ready */
/* matchlist should be initialised and empty, hence invert it to get list of all corpus positions */
if (!Setop(matchlist, Complement, NULL))
return False;
mark_offrange_cells(matchlist, corpus);
for (i = 0; i < matchlist->tabsize; i++) {
if (!EvaluationIsRunning) {
free_matchlist(matchlist);
return False;
}
if (matchlist->start[i] >= 0 &&
!eval_bool(ctptr, NULL, matchlist->start[i]))
/* we're ignoring labels at the moment, so we pass NULL as reftab */
matchlist->start[i] = -1;
}
if (!Setop(matchlist, Reduce, NULL))
return False;
return True;
break;
case b_not: /* logical negation */
if (eval_debug)
Rprintf("calc_initial_ml: boolean not\n");
assert(ctptr->node.left);
if (calculate_initial_matchlist_1(ctptr->node.left,
matchlist, corpus)) {
if (!Setop(matchlist, Complement, NULL))
return False;
if (mark_offrange_cells(matchlist, corpus))
if (!Setop(matchlist, Reduce, NULL))
return False;
return True;
}
else {
free_matchlist(matchlist);
return False;
}
break;
/* relational operators */
case cmp_gt:
case cmp_lt:
case cmp_get:
case cmp_let:
case cmp_eq:
case cmp_neq:
case cmp_ex:
if (eval_debug)
Rprintf("calc_initial_ml: evaluate comparisons\n");
/* check argument types */
assert((ctptr->node.left != NULL) &&
((ctptr->node.op_id == cmp_ex) || (ctptr->node.right != NULL)));
/* on the left, there can be
* func
* pa_ref
* on the right,
* string_leaf
* int_leaf
* may occur additionally.
*/
switch (ctptr->node.left->type) {
case func:
case sa_ref:
/* for the moment, this is just a ridiculous dummy implementation; replace when tables are ready */
/* matchlist should be initialised and empty, hence invert it to get list of all corpus positions */
if (!Setop(matchlist, Complement, NULL))
return False;
mark_offrange_cells(matchlist, corpus);
for (i = 0; i < matchlist->tabsize; i++) {
if (!EvaluationIsRunning) {
free_matchlist(matchlist);
return False;
}
if (matchlist->start[i] >= 0 &&
!eval_bool(ctptr, NULL, matchlist->start[i]))
/* we're ignoring labels at the moment, so we pass NULL as reftab */
matchlist->start[i] = -1;
}
if (!Setop(matchlist, Reduce, NULL))
return False;
return True;
break;
case pa_ref:
if (ctptr->node.left->pa_ref.label) {
/* this shouldn't happen because no labels are defined in query initial position */
/* sadly, [_ = 1042] would be very useful, but it's a hell of a special case to implement here */
cqpmessage(Error,
"Reference to label '%s' not allowed in query initial position.",
ctptr->node.left->pa_ref.label->name);
return False;
}
else {
/*
* we have a non-labelled pa_ref on the left
* should have a string atom on the right
*/
if ((ctptr->node.right == NULL) ||
(ctptr->node.right->type != string_leaf)) {
/* for the moment, this is just a ridiculous dummy implementation; replace when tables are ready */
/* matchlist should be initialised and empty, hence invert it to get list of all corpus positions */
if (!Setop(matchlist, Complement, NULL))
return False;
mark_offrange_cells(matchlist, corpus);
for (i = 0; i < matchlist->tabsize; i++) {
if (!EvaluationIsRunning) {
free_matchlist(matchlist);
return False;
}
if (matchlist->start[i] >= 0 &&
!eval_bool(ctptr, NULL, matchlist->start[i]))
/* we're ignoring labels at the moment, so we pass NULL as reftab */
matchlist->start[i] = -1;
}
if (!Setop(matchlist, Reduce, NULL))
return False;
return True;
}
switch (ctptr->node.right->leaf.pat_type) {
case REGEXP:
/* check whether we have a ".+" or ".*" on the right --in this case
* there is nothing to do (matched by everything)
* TODO: change that in case "" may be returned by attribute access
* --> removed ".+" optimisation, which may produce wrong results e.g. if LHS is function call
*/
if ((strcmp(ctptr->node.right->leaf.ctype.sconst, ".*") == 0)) {
if (ctptr->node.op_id == cmp_neq) {
/* every word is != ".*", so just return an empty match list */
free_matchlist(matchlist);
return True;
}
else {
/* return a copy of the corpus (expensive, but what shall we do)? */
get_matched_corpus_positions(ctptr->node.left->pa_ref.attr,
".*",
0,
matchlist,
(int *)corpus->range,
corpus->size);
if (mark_offrange_cells(matchlist, corpus))
if (!Setop(matchlist, Reduce, NULL))
return False;
return True;
}
}
else {
get_matched_corpus_positions(ctptr->node.left->pa_ref.attr,
ctptr->node.right->leaf.ctype.sconst,
ctptr->node.right->leaf.canon,
matchlist,
(int *)corpus->range,
corpus->size);
}
break;
case NORMAL:
get_corpus_positions(ctptr->node.left->pa_ref.attr,
ctptr->node.right->leaf.ctype.sconst,
matchlist);
break;
case CID:
matchlist->start = get_positions(ctptr->node.left->pa_ref.attr,
ctptr->node.right->leaf.ctype.cidconst,
&(matchlist->tabsize),
(int *)corpus->range,
corpus->size);
matchlist->matches_whole_corpus = 0;
matchlist->is_inverted = 0;
matchlist->end = NULL;
break;
default:
cqpmessage(Error,
"Unknown pattern type (%d) on RHS of comparison operator.",
ctptr->node.right->leaf.pat_type);
return False;
break;
}
if (mark_offrange_cells(matchlist, corpus))
if (!Setop(matchlist, Reduce, NULL))
return False;
if (ctptr->node.op_id == cmp_neq)
if (!Setop(matchlist, Complement, NULL))
return False; /* Auswertung bei Speicherueberlauf abbrechen */
}
return True;
break;
default:
cqpmessage(Error,
"Wrong node type (%d) on LHS of comparison operator.",
ctptr->node.left->type);
break;
} /* switch (ctptr->node.left->type) ... */
break;
default:
assert("Internal error in calculate_initial_matchlist_1(): Unknown comparison operator." && 0);
break;
} /* endswitch (ctptr->node.op_id) ... */
} /* endif (ctptr->type == bnode) */
else if (ctptr->type == cnode) {
if (ctptr->constnode.val == 0) {
matchlist->start = NULL;
matchlist->end = NULL;
matchlist->tabsize = 0;
matchlist->matches_whole_corpus = 0;
matchlist->is_inverted = 0;
}
else {
get_matched_corpus_positions(ctptr->node.left->pa_ref.attr,
".*",
0,
matchlist,
(int *)corpus->range,
corpus->size);
if (mark_offrange_cells(matchlist, corpus))
if (!Setop(matchlist, Reduce, NULL))
return False;
}
return True;
}
else if (ctptr->type == id_list) {
if (ctptr->idlist.label == NULL) {
if (ctptr->idlist.nr_items > 0) {
assert(ctptr->idlist.attr);
matchlist->start = collect_matches(ctptr->idlist.attr,
ctptr->idlist.items,
ctptr->idlist.nr_items,
1, /* sort: yes */
&(matchlist->tabsize),
NULL, 0);
matchlist->end = NULL;
matchlist->matches_whole_corpus = 0;
matchlist->is_inverted = 0;
}
else {
matchlist->start = NULL;
matchlist->end = NULL;
matchlist->tabsize = 0;
matchlist->matches_whole_corpus = 0;
matchlist->is_inverted = 0;
}
if (ctptr->idlist.negated)
if (!Setop(matchlist, Complement, NULL))
return False;
if (mark_offrange_cells(matchlist, corpus))
if (!Setop(matchlist, Reduce, NULL))
return False;
return True;
}
else {
cqpmessage(Error,
"Reference to label '%s' not allowed in query initial position.",
ctptr->node.left->idlist.label->name);
return False;
} /* if (ctptr->idlist.label == NULL) ... else ... */
}
else {
cqpmessage(Error,
"Internal error in calculate_initial_matchlist_1()<eval.c>: Illegal node type %d.\n",
ctptr->type);
return(False);
} /* if (ctptr->type == bnode) ... else if ... */
} /* endif ctptr */
else {
/* if ctptr is NULL */
return(True);
}
assert("Internal error in calculate_initial_matchlist1(): went over the edge." && 0);
return 0;
}
/**
* Wrapper around calculate_initial_matchlist_1, qv.
*
* @see calculate_initial_matchlist_1
*/
Boolean
calculate_initial_matchlist(Constrainttree ctptr,
Matchlist *matchlist,
CorpusList *corpus)
{
Boolean res;
res = calculate_initial_matchlist_1(ctptr, matchlist, corpus);
/* i.e. if calling the main function worked, and a matchlist was created */
if (res && matchlist) {
if (matchlist->is_inverted) {
matchlist->is_inverted = 0;
res = Setop(matchlist, Complement, NULL);
}
if (res && mark_offrange_cells(matchlist, corpus)) {
res = Setop(matchlist, Reduce, NULL);
}
}
return res;
}
/*
* try to match the given word form pattern and return success.
*/
Boolean
matchfirstpattern(AVS pattern,
Matchlist *matchlist,
CorpusList *corpus)
{
int nr_strucs, nr_ok, ok, i, k, start, end, nr_pos, cpos;
Bitfield bf;
float red;
char *val;
assert(pattern);
switch (pattern->type) {
case Tag:
assert(pattern->tag.attr != NULL);
nr_strucs = cl_max_struc(pattern->tag.attr);
if (nr_strucs <= 0) { /* CL considers 0 regions a missing data error, but we won't be that strict */
matchlist->tabsize = 0; /* should be initialised to that, but make sure we report 0 matches */
return True;
}
/* if there is a constraint, match annotated strings first */
bf = create_bitfield(nr_strucs); /* always use bitfield (the memory overhead is acceptable) */
if (pattern->tag.constraint) {
clear_all_bits(bf);
nr_ok = 0;
for (i = 0; (i < nr_strucs) && (EvaluationIsRunning); i++) {
val = cl_struc2str(pattern->tag.attr, i);
if (val) {
if (pattern->tag.rx)
ok = cl_regex_match(pattern->tag.rx, val, 0);
else
ok = (0 == strcmp(pattern->tag.constraint, val));
if (pattern->tag.negated)
ok = !ok;
}
else
ok = 0;
if (ok) {
set_bit(bf, i);
nr_ok++;
}
}
if (!EvaluationIsRunning)
nr_ok = 0; /* user abort -> stop query execution */
}
else {
set_all_bits(bf); /* no constraint -> all regions are possible start points */
nr_ok = nr_strucs;
}
if (nr_ok <= 0) { /* no matches -> return empty matchlist */
destroy_bitfield(&bf);
matchlist->tabsize = 0;
return True;
}
else {
/* compute the initial matchlist according to the flags in bf */
matchlist->start = (int *)cl_malloc(sizeof(int) * nr_ok);
matchlist->end = NULL;
matchlist->matches_whole_corpus = 0;
k = 0;
for (i = 0; i < nr_strucs; i++) {
if (get_bit(bf, i)) {
if (!cl_struc2cpos(pattern->tag.attr, i, &start, &end)) {
destroy_bitfield(&bf);
cl_free(matchlist->start);
return False;
}
matchlist->start[k++] = (pattern->tag.is_closing) ? (end + 1) : start;
/* NB: it's (end+1) for a closing tag, since the tag refers to the token at cpos-1 */
}
}
}
destroy_bitfield(&bf);
matchlist->tabsize = nr_ok;
return True;
break;
case Anchor:
/* first, check some error conditions */
if ((corpus->size == 0) || (corpus->range == NULL)) {
cqpmessage(Error, "Subquery on empty corpus. Not evaluated.");
return False;
}
if ((pattern->anchor.field == TargetField) && (corpus->targets == NULL)) {
cqpmessage(Error, "No <target> anchors found in query corpus.");
return False;
}
if ((pattern->anchor.field == KeywordField) && (corpus->keywords == NULL)) {
cqpmessage(Error, "No <keyword> anchors found in query corpus.");
return False;
}
/* allocate matchlist with maximal size required */
matchlist->start = (int *)cl_malloc(sizeof(int) * corpus->size);
matchlist->end = NULL;
matchlist->matches_whole_corpus = 0;
matchlist->tabsize = corpus->size;
/* now go through all ranges in the query corpus and copy the corresponding anchor position into the matchlist */
for (i = 0; i < corpus->size; i++) {
switch (pattern->anchor.field) {
case MatchField:
cpos = corpus->range[i].start;
break;
case MatchEndField:
cpos = corpus->range[i].end;
break;
case TargetField:
cpos = corpus->targets[i];
break;
case KeywordField:
cpos = corpus->keywords[i];
break;
default:
assert("Internal Error" && 0);
}
if (pattern->anchor.is_closing && (cpos >= 0))
cpos++; /* </target> anchor refers to point after target token etc. */
matchlist->start[i] = cpos;
}
/* remove 'undefined' target or keyword anchors */
if (!Setop(matchlist, Reduce, NULL))
return False;
return True;
break; /* endcase Anchor */
case Pattern:
/* no need to set labels here, since this is done in the following NFA simulation */
if (0 &&
(query_optimize) &&
((red = red_factor(corpus, &nr_pos)) != 0.0) &&
(red < RED_THRESHOLD)) {
/*
* THIS IS CURRENTLY DISABLED (TODO!)
* ----------------------------------------------------------------------
*
* The evaluator optimization expects the ``initial matchlist''
* to be exact, that is, there mustn't be any CPs in it which don't
* reflect to valid start states in the automaton.
*
* Fri Mar 17 11:12:47 1995 (oli)
*/
if (!silent)
Rprintf("QOpt: %f (pos %d)\n", red, nr_pos);
matchlist->start = (int *)cl_malloc(sizeof(int) * nr_pos);
matchlist->end = NULL;
matchlist->matches_whole_corpus = 0;
if (matchlist->start == NULL)
return False;
matchlist->tabsize = nr_pos;
k = 0;
for (i = 0; i < corpus->size; i++)
for (start = corpus->range[i].start;
start <= corpus->range[i].end;
start++) {
assert(k < nr_pos);
matchlist->start[k++] = start;
}
assert(k == nr_pos);
if (!silent)
Rprintf("QOpt: copied ranges\n");
return (k == nr_pos);
}
else {
int ok;
ok = calculate_initial_matchlist(pattern->con.constraint,
matchlist, corpus);
return ok;
}
break; /* endcase Pattern */
case MatchAll:
get_matched_corpus_positions(NULL, ".*", 0, matchlist,
(int *)corpus->range, corpus->size);
return True;
break;
}
assert("Internal Error." && 0);
return False;
}
/*
* This function's name is totally useless.
*/
void
simulate(Matchlist *matchlist,
int *cut,
int start_state,
int start_offset, /* start_offset is always set to 0; no idea what it was meant for??? */
int *state_vector,
int *target_vector,
RefTab *reftab_vector,
RefTab *reftab_target_vector,
int start_transition)
{
int i, p, cpos, effective_cpos, rp;
int strict_regions_ok, lookahead_constraint, zero_width_pattern;
int target_state, transition_valid;
int state,
boundary, b1, b2,
running_states,
winner,
my_target,
this_is_a_winner;
int *help;
RefTab *help2;
AVStructure *condition;
int nr_transitions = 0;
int percentage, new_percentage; /* for ProgressBar option */
assert(evalenv->query_corpus);
assert(evalenv->query_corpus->size > 0);
assert(evalenv->query_corpus->range);
assert(matchlist);
assert(matchlist->start);
assert(matchlist->end);
/*
* state 0 must neither be final nor error
*/
assert(!evalenv->dfa.Final[0] && (evalenv->dfa.E_State != 0));
if ((evalenv->query_corpus->size == 0) ||
(evalenv->query_corpus->range == NULL)) {
free_matchlist(matchlist);
}
else {
assert(state_vector);
assert(target_vector);
assert(reftab_vector);
assert(reftab_target_vector);
rp = 0;
i = 0;
percentage = -1;
while ((i < matchlist->tabsize) && ((*cut) != 0) && EvaluationIsRunning) {
if (progress_bar && !evalenv->aligned) {
new_percentage = floor(0.5 + (100.0 * i) / matchlist->tabsize);
if (new_percentage > percentage) {
percentage = new_percentage;
progress_bar_percentage(0, 0, percentage);
}
}
/*
* find the appropriate range
* three cases:
* 1 start point smaller than range beginning
* we should have considered that start point before.
* so we cannot have a match in this case.
* action: assign -1 to matchlist->start and increment i
* 2 start point within range (ok)
* action: simulate automaton
* 3 start point beyond range end
* we have to check whether a later range will contain the
* starting point.
* action: increment rp.
*/
my_target = -1;
if (debug_simulation)
Rprintf("Looking at matchlist element %d (cpos %d)\n"
" range[rp=%d]=[%d,%d]\n",
i, matchlist->start[i],
rp,
(rp < evalenv->query_corpus->size) ?
evalenv->query_corpus->range[rp].start : -1,
(rp < evalenv->query_corpus->size) ?
evalenv->query_corpus->range[rp].end : -1);
if ((rp >= evalenv->query_corpus->size) ||
(matchlist->start[i] < evalenv->query_corpus->range[rp].start)) {
/* case 1
* - no match possible
*/
matchlist->start[i] = -1;
i++;
}
else if (matchlist->start[i] > evalenv->query_corpus->range[rp].end)
/* case 3
* - no match in this range.
* check for a later one (but keep the current matchlist element)
*/
rp++;
else {
/* case 2
* simulate automaton
*/
/* determine maximal right boundary for this match:
* boundary = MIN() of
* - boundary given by "within" clause (defaults to hard_boundary, if there is no "within" clause)
* - right boundary of current range in the query_corpus (for subqueries)
*/
b1 = calculate_rightboundary(evalenv->query_corpus,
matchlist->start[i],
evalenv->search_context);
b2 = evalenv->query_corpus->range[rp].end;
boundary = MIN(b1, b2);
if (debug_simulation)
Rprintf("Starting NFA simulation. Max bound is %d\n", boundary);
if (boundary == -1) {
/*
* no match here, since not within selected boundary.
*/
matchlist->start[i] = -1;
if (debug_simulation)
Rprintf(" ... not within selected boundary\n");
}
else {
int first_transition_traversed;
/*
* set up some 'global' variables in evalenv (which subroutines may need to use)
*/
evalenv->rp = rp; /* current range (in subquery); used to evaluate Anchor constraints */
/*
* all states are inactive / reset label references
*/
for (state = 0; state < evalenv->dfa.Max_States; state++) {
state_vector[state] = -1;
reset_reftab(reftab_vector[state]);
}
/*
* activate initial state and set the special "match" label
*/
state_vector[start_state] = matchlist->start[i] + start_offset;
set_reftab(reftab_vector[start_state], evalenv->match_label->ref, matchlist->start[i] + start_offset);
running_states = 1; /* the number of currently active states */
winner = -1; /* the end position of the winning (final) state */
first_transition_traversed = 0; /* the first transition was not yet traversed */
/* bail out on the first winner, unless matching_strategy == longest match */
/* (in longest_match strategy, wait until we don't have any running states left) */
while (((winner < 0) || (evalenv->matching_strategy == longest_match))
&& (running_states > 0)) {
/*
* the core of the whole simulation
*/
/*
* first clear the list of target states
*/
for (state = 0; state < evalenv->dfa.Max_States; state++)
target_vector[state] = -1;
/* no need to reset the target reftab, since only reftab associated
with active states will be considered */
for (state = 0;
(state < evalenv->dfa.Max_States) &&
((winner < 0) || (evalenv->matching_strategy == longest_match)) && /* abort when we've found a winner, unless strategy is longest match */
(running_states > 0); /* no remaining active states -> simulation finished */
state++) {
cpos = state_vector[state];
/* A state always refers to a point between two consecutive tokens.
* cpos = state_vector[state] is the corpus position of the second token.
* Hence, in a query, patterns and open tags refer to the second token (at cpos),
* where as closing tags refer to the first token (at cpos-1)
*/
if (debug_simulation) {
Rprintf(" state %d, cpos %d...\n", state, cpos);
if (symtab_debug)
print_label_values(evalenv->labels, reftab_vector[state], cpos);
}
/* Transitions from this state are allowed if:
* - cpos >= 0 --> state is active
* - cpos <= boundary --> within right boundary for this match
* !! if the next query element is a closing tag, we have to substitue cpos-1 for cpos in this condition !!
* --> we'll test (cpos >= 0) right now and the other condition separately for each possible transition
*/
if (cpos >= 0) { /* active state */
running_states--; /* this state becomes inactive; it will spawn new active states if there are valid transitions */
for (p = 0; /* cycle through all possible transitions from this state */
(p < evalenv->dfa.Max_Input)
&& ((winner < 0) || (evalenv->matching_strategy == longest_match)); /* in shortest_match mode, stop evaluation as soon as there is a winner */
p++) {
/* the target state (that is, the state we reach after the transition) */
target_state = evalenv->dfa.TransTable[state][p];
/* if we reach a non-error state with this transition */
if (target_state != evalenv->dfa.E_State) {
/* condition is the AVStructure ("pattern") associated with this transition */
condition = &(evalenv->patternlist[p]);
/* check whether the associated condition is a lookahead constraint pattern */
lookahead_constraint =
((condition->type == MatchAll) && (condition->matchall.lookahead)) ||
((condition->type == Pattern) && (condition->con.lookahead));
/* tags, anchors, and lookahead constraints are zero-width patterns */
zero_width_pattern =
(condition->type == Tag) || (condition->type == Anchor) || lookahead_constraint;
/* check if we're still in range (i.e. effective_cpos <= boundary; except for lookahead constraint) */
effective_cpos = cpos;
/* a closing tag or anchor point refers to effective_cpos = cpos-1 */
if ((condition->type == Tag && condition->tag.is_closing)
|| (condition->type == Anchor && condition->anchor.is_closing))
effective_cpos--;
/* In StrictRegions mode, we have to check all constraints imposed by region boundaries now. */
strict_regions_ok = 1;
if (strict_regions) {
int flags = LAB_RDAT | LAB_DEFINED | LAB_USED; /* 'active' labels in rdat namespace */
LabelEntry rbound_label = symbol_table_new_iterator(evalenv->labels, flags);
while (rbound_label != NULL) {
int rbound = get_reftab(reftab_vector[state], rbound_label->ref, -1);
if ((rbound >= 0) && (effective_cpos > rbound))
strict_regions_ok = 0; /* a within region constraint has been violated */
rbound_label = symbol_table_iterator(rbound_label, flags);
}
}
/* if we're in range, evaluate the constraint and activate target state iff true */
if ( ((effective_cpos <= boundary) ||
(lookahead_constraint && (effective_cpos == boundary+1)))
&& strict_regions_ok ) {
/* IF this is the first transition we pass from the start state,
* AND it is the one for which we built the initial matchlist,
* we can save a little time if we don't evaluate the condition again;
* if (start_transition >= 0) we can also safely ignore all other
* transitions from the start state because they will crop up in another
* initial matchlist (start_transition < 0 happens in "aligned" queries, for instance)
*
* !! THIS MESSES UP THE SHORTEST MATCH STRATEGY !! -> results have to be cleaned up after the query
*/
if ((state == start_state) &&
(start_transition >= 0) &&
(first_transition_traversed == 0)) {
transition_valid = (start_transition == p) ? 1 : 0;
/* if this first transition is valid, we need to copy the reftab
* and set the optional label associated with this transition (otherwise done by eval_constraint()) */
if (transition_valid) {
LabelEntry label;
/* copy the state's reftab to the target state (done by eval_constrain() in the other cases) */
dup_reftab(reftab_vector[state], reftab_target_vector[target_state]);
if (condition->type == Pattern)
label = condition->con.label;
else if (condition->type == MatchAll)
label = condition->matchall.label;
else
label = NULL;
if (label != NULL) {
set_reftab(reftab_target_vector[target_state], label->ref, effective_cpos); /* see below */
}
/* if the skipped first pattern was an open tag, we have to set the corresponding label in StrictRegions mode here */
if (strict_regions && (condition->type == Tag)) {
int start, end;
if ((! condition->tag.is_closing) &&
(condition->tag.right_boundary != NULL) &&
get_struc_attribute(condition->tag.attr, effective_cpos, &start, &end)) {
set_reftab(reftab_target_vector[target_state], condition->tag.right_boundary->ref, end);
}
}
}
}
/* OTHERWISE we evaluate the condition associated with the transition
* (NB this condition refers to the effective_cpos!)
*/
else {
transition_valid = eval_constraint(condition, effective_cpos,
reftab_vector[state], reftab_target_vector[target_state]);
} /* if ((state == start_state) && ... ) ... */
/* now set target for this transition */
if (transition_valid && matchlist->target_positions) {/* the second condition should be unecessary */
int pattern_is_targeted;
if (condition->type == Pattern) {
pattern_is_targeted = condition->con.is_target;
}
else if (condition->type == MatchAll) {
pattern_is_targeted = condition->matchall.is_target;
}
else {
pattern_is_targeted = 0;
}
if (pattern_is_targeted) {
set_reftab(reftab_target_vector[target_state], evalenv->target_label->ref, /* the special "target" label */
effective_cpos); /* since only patterns can be targeted, this is ==cpos at the moment, but why not change it? */
}
}
/* now, finally, check if we have a winner, i.e.
* - the target state is a final state
* - the optional global constraint is fulfilled
* and then advance to the next token (unless transition was associated with a tag or anchor point)
*/
if (transition_valid) {
nr_transitions++;
if (nr_transitions == 20000) {
CheckForInterrupts();
nr_transitions = 0;
}
if (debug_simulation) {
Rprintf("Transition %d --%d-> %d (pattern %d TRUE at cpos=%d)\n",
state, p, target_state, p, effective_cpos);
if (symtab_debug)
print_label_values(evalenv->labels, reftab_target_vector[target_state], effective_cpos);
}
/* check for winner */
this_is_a_winner = 0;
if (evalenv->dfa.Final[target_state]) {
if (evalenv->gconstraint == NULL) {
this_is_a_winner = 1;
}
else {
int matchend_cpos = (zero_width_pattern) ? cpos - 1 : cpos;
/* set special "matchend" label before the global constraint is evaluated */
set_reftab(reftab_target_vector[target_state], evalenv->matchend_label->ref, matchend_cpos);
/* evaluate global constraint with current cpos set to -1 (undef) */
if (eval_bool(evalenv->gconstraint, reftab_target_vector[target_state], -1)) {
this_is_a_winner = 1;
}
/* delete "matchend" label in case we continue the simulation (longest match mode) */
set_reftab(reftab_target_vector[target_state], evalenv->matchend_label->ref, -1);
}
}
if (this_is_a_winner) {
if (debug_simulation)
Rprintf("Winning cpos found at %d\n", cpos);
/* remember the last token (cpos) of this winner & its target position (if set) */
winner = (zero_width_pattern) ? cpos - 1 : cpos;
/* for zero-width elements, the last token of the match is the token _before_ the current corpus position
[NB: for closing tags and anchors we could have used the effective cpos, but not for open tags and lookahead constraints]
*/
if (evalenv->has_target_indicator) {
my_target = get_reftab(reftab_target_vector[target_state],
evalenv->target_label->ref, -1);
}
/* NB If (matching_strategy == longest_match) later winners will overwrite
the <winner> and <my_target> variables */
}
/* if our matching strategy is longest_match, we have to activate the target state,
* so our winner can expand to a longer match in queries like ''"ADJA" "NN"+;'' */
if (!this_is_a_winner || (evalenv->matching_strategy == longest_match)) {
/* for zero-width elements, don't increment corpus position (think of "<s><np> ... </np></s>" for instance) */
if (zero_width_pattern) {
target_vector[target_state] = cpos; /* this is NOT the effective cpos, otherwise we'd go backwards! */
}
else {
target_vector[target_state] = cpos + 1;
}
}
} /* if (transition_valid) ... [check for winners] */
} /* if (effective_cpos <= boundary) ... */
} /* if (target_state != evalenv->dfa.E_State) ... */
} /* for (p = 0; ... ; p++) ... [loop over all transitions from this state] */
} /* if (cpos >= 0) ... [active state] */
} /* for (state = 0; ... ; state++) ... [loop over all states] */
/* we have now traversed all possible transitions from all active states
* -> if this is the first simulation cycle, we have now done our first transitions */
first_transition_traversed = 1;
/* if we haven't found a winner, or we're looking for other winners,
check if there are still any active states */
if ((winner < 0) || (evalenv->matching_strategy == longest_match)) {
running_states = 0;
for (state = 0; state < evalenv->dfa.Max_States; state++)
if (target_vector[state] >= 0)
running_states++;
/* while we're at it, swap the current state & target vectors and reftabs for the next simulation cycle */
help = state_vector;
state_vector = target_vector;
target_vector = help;
help2 = reftab_vector;
reftab_vector = reftab_target_vector;
reftab_target_vector = help2;
}
/*
Some nonsensical CQP queries involving XML tags or zero-width assertions (such as ``<s> *'') can lead to a FSA with
eps-cycles (i.e. a cycle that returns to the same state without consuming a token) and hence to an infinite loop in the simulation.
The hallmark of such an infinite loop should be that the state_vector converges to a stable state (a "fixed point").
Here, we check for this situation (state_vector == target_vector) and abort FSA simulation if it is caught in an infinite loop.
For now, an emphatic error message is printed (asking users to file a bug report if this code should abort a valid query) and
query execution is stopped immediately. Once we are reasonably certain that the infinite loop test works correctly, we might
also simply consider set the current run to "no match" and continue with the next starting point in the list.
*/
for (state = 0; state < evalenv->dfa.Max_States; state++)
if (state_vector[state] != target_vector[state])
break;
if (state >= evalenv->dfa.Max_States) {
/* state_vector hasn't changed in last simulation step => caught in infinite loop */
cqpmessage(Error, "Infinite loop detected: did you quantify over a zero-width element (XML tag or lookahead)?\n"
"\tIf you are reasonably sure that your query is valid, please contact the CWB development team and file a bug report!\n"
"\tQuery execution aborted.");
running_states = 0; /* this should get us safely out of the inner loop ... */
EvaluationIsRunning = 0; /* ... and the outer loop */
}
} /* while (((winner < 0) || ... ) && (running_states > 0)) ... */
/*
* if we returned here, we either have a winning
* corpus position or no running states any more.
*/
if (debug_simulation)
Rprintf("NFA sim terminated. Winner %d, running states %d\n",
winner, running_states);
/* queries like "</s>" will return empty matches -> ignore those (set to no match)
* (NB this doesn't happen for open tags, since "<s>" == "<s> []")
*/
if ((winner >= 0) && (winner >= matchlist->start[i])) {
if (*cut > 0)
*cut = *cut - 1;
matchlist->end[i] = winner;
}
else
matchlist->start[i] = -1;
}
if (matchlist->target_positions) {
if (matchlist->start[i] >= 0)
matchlist->target_positions[i] = my_target;
else
matchlist->target_positions[i] = -1;
}
i++;
/* move to the next regarded matchlist element */
} /* case 2: simulate automaton */
} /* while ((i < matchlist->tabsize) && ... ) ... [simulate automaton for current matchlist] */
/*
* if we left the execution prematurely ... (interrupt, I guess?)
*/
while (i < matchlist->tabsize) {
matchlist->start[i] = -1;
i++;
}
} /* end of the big "else" (unless evalenv->query_corpus->size == 0) */
}
int
check_alignment_constraints(Matchlist *ml)
{
int mlp, envp, i;
int as, ae, dum1, dum2, dum3;
EEP tmp;
int *state_vector;
int *target_vector;
RefTab *reftab_vector;
RefTab *reftab_target_vector;
Matchlist matchlist;
if (eep > 0) {
/*
* we have alignments
*/
EvaluationIsRunning = 1;
init_matchlist(&matchlist);
for (envp = 1; envp <= eep; envp++) {
assert(Environment[envp].aligned);
tmp = evalenv;
evalenv = &(Environment[envp]);
state_vector = (int *)cl_malloc(sizeof(int) * Environment[envp].dfa.Max_States);
target_vector = (int *)cl_malloc(sizeof(int) * Environment[envp].dfa.Max_States);
reftab_vector = (RefTab *) cl_malloc(sizeof(RefTab) * evalenv->dfa.Max_States);
reftab_target_vector = (RefTab *) cl_malloc(sizeof(RefTab) * evalenv->dfa.Max_States);
/* init reference table for current evalenv */
for (i = 0; i < evalenv->dfa.Max_States; i++) {
reftab_vector[i] = new_reftab(evalenv->labels);
reftab_target_vector[i] = new_reftab(evalenv->labels);
}
for (mlp = 0; mlp < ml->tabsize; mlp++)
if (ml->start[mlp] != no_match) {
int alg1, alg2;
if (0 > (alg1 = cl_cpos2alg(Environment[envp].aligned, ml->start[mlp])))
ml->start[mlp] = no_match;
else if (!cl_alg2cpos(Environment[envp].aligned,
alg1, &dum1, &dum2, &as, &dum3) || (cderrno != CDA_OK))
ml->start[mlp] = no_match;
else if (0 > (alg2 = cl_cpos2alg(Environment[envp].aligned, ml->end[mlp])))
ml->start[mlp] = no_match;
else if (!cl_alg2cpos(Environment[envp].aligned,
alg2, &dum1, &dum2, &dum3, &ae) || (cderrno != CDA_OK))
ml->start[mlp] = no_match;
else if ((ae < as) || (ae < 0) || (as < 0))
ml->start[mlp] = no_match;
else {
/* construct initial matchlist by assuming
* that every position in the aligned range
* may be an initial matchpoint
*/
matchlist.tabsize = ae - as + 1;
matchlist.start = (int *)cl_malloc(sizeof(int) * matchlist.tabsize);
matchlist.end = (int *)cl_malloc(sizeof(int) * matchlist.tabsize);
for (i = as; i <= ae; i++) {
matchlist.start[i - as] = i;
matchlist.end[i - as] = i;
}
dum1 = 1;
/* don't reset label references here, because it shouldn't
really be necessary (it's done in simulate()) */
simulate(&matchlist, &dum1, 0, 0,
state_vector, target_vector,
reftab_vector, reftab_target_vector,
-1);
if (dum1 != evalenv->negated)
ml->start[mlp] = no_match;
free_matchlist(&matchlist);
}
}
free(state_vector);
free(target_vector);
for (i = 0; i < evalenv->dfa.Max_States; i++) {
delete_reftab(reftab_vector[i]);
delete_reftab(reftab_target_vector[i]);
}
free(reftab_vector);
free(reftab_target_vector);
evalenv = tmp;
}
if (!EvaluationIsRunning) {
cqpmessage(Info, "Evaluation interruted: results may be incomplete.");
if (which_app == cqp) install_signal_handler();
}
}
return 0;
}
/* TODO what a very helpful documentation comment the following is.... (AH) */
/** simulate the dfa */
void
simulate_dfa(int envidx, int cut, int keep_old_ranges)
{
int p, maxresult, state, i;
Matchlist matchlist;
Matchlist total_matchlist;
int *state_vector; /* currently active states are marked with corresponding cpos */
int *target_vector; /* target states when simulating transition */
RefTab *reftab_vector; /* the reference tables corresponding to the state vector */
RefTab *reftab_target_vector; /* the reference tables corresponding to the target vector */
int allocate_target_space;
/* We can avoid wasting memory if the first transition of the FSA is
deterministic, because there's no need to collect matches in
total_matchlist then. */
int FirstTransitionIsDeterministic;
int trans_count = 0, current_transition = 0;
assert(envidx <= eep); /* envidx == 0, actually ... check_alignment_constraint EXPLICITLY assumes that everything
* else is an alignment constraint! */
evalenv = &Environment[envidx];
/* Apparently Max_Input is the maximal number of transitions that appears in the
FSA, so we have Max_Input transitions from every state and the unused ones go
to dfa.E_State (error state?) and aren't evaluated. To cut a long story short,
we'll have to count how many transitions from the start state we'll have to
follow. Heck. */
/* this loop is essentially the same as the main loop below */
for (p = 0; p < evalenv->dfa.Max_Input; p++)
if (evalenv->dfa.TransTable[0][p] != evalenv->dfa.E_State)
trans_count++;
FirstTransitionIsDeterministic = (trans_count == 1) ? 1 : 0;
init_matchlist(&matchlist);
if (!FirstTransitionIsDeterministic)
init_matchlist(&total_matchlist);
allocate_target_space = evalenv->has_target_indicator;
assert(evalenv->query_corpus);
if (evalenv->dfa.Final[0] == True) {
cqpmessage(Error,
"Query matches empty string, evaluation aborted (otherwise whole corpus would be matched)\n");
set_corpus_matchlists(evalenv->query_corpus,
&matchlist, /* total_matchlist may be uninitialised */
1,
0);
free_matchlist(&matchlist);
}
else if (evalenv->query_corpus->size == 0) {
cqpmessage(Info,
"Query corpus is empty (and so is the result).");
free_matchlist(&matchlist);
}
else {
/* allocate the state and reference table vectors here, so that this has
* not to be done in every simulate iteration
*/
state_vector = (int *)cl_malloc(sizeof(int) * evalenv->dfa.Max_States);
target_vector = (int *)cl_malloc(sizeof(int) * evalenv->dfa.Max_States);
reftab_vector = (RefTab *) cl_malloc(sizeof(RefTab) * evalenv->dfa.Max_States);
reftab_target_vector = (RefTab *) cl_malloc(sizeof(RefTab) * evalenv->dfa.Max_States);
/* init reference table for current evalenv */
for (i = 0; i < evalenv->dfa.Max_States; i++) {
reftab_vector[i] = new_reftab(evalenv->labels);
reftab_target_vector[i] = new_reftab(evalenv->labels);
}
EvaluationIsRunning = 1;
/* first transition loop (loops over all possible initial patterns) */
for (p = 0;
(p < evalenv->dfa.Max_Input) && EvaluationIsRunning;
p++)
if ((state = evalenv->dfa.TransTable[0][p]) != evalenv->dfa.E_State) {
current_transition++; /* counts how many of the trans_count initial transitions we have evaluated */
if (progress_bar && !evalenv->aligned) {
progress_bar_clear_line();
progress_bar_message(current_transition, trans_count, " preparing");
}
if (evalenv->labels) {
for (i = 0; i < evalenv->dfa.Max_States; i++) {
reset_reftab(reftab_vector[i]); /* reset all label references */
reset_reftab(reftab_target_vector[i]); /* shouldn't be necessary, just to make sure */
}
}
/* match the initial pattern. */
if (matchfirstpattern(&(evalenv->patternlist[p]),
&matchlist,
evalenv->query_corpus) == True) {
if (initial_matchlist_debug) {
Rprintf("After initial matching for transition %d: ", p);
show_matchlist_firstelements(matchlist);
print_symbol_table(evalenv->labels);
}
if (matchlist.tabsize > 0) {
matchlist.end = (int *)cl_malloc(sizeof(int) * matchlist.tabsize);
(void) memcpy(matchlist.end, matchlist.start,
sizeof(int) * matchlist.tabsize);
if (allocate_target_space) {
matchlist.target_positions = (int *)cl_malloc(sizeof(int) * matchlist.tabsize);
for (i = 0; i < matchlist.tabsize; i++)
matchlist.target_positions[i] = -1;
}
/* If 'cut <n>' is specified, try to get <n> matches from every initial pattern;
* then reduce to a total of <n> matches after sorting (this happens in do_StandardQuery<parse_actions.c>).
* Exception: aligned queries will remove an unpredictable number of matches below, so we must not apply a cut here and instead rely on the final reduction.
* This means that aligned queries will always run to completion even if cut is specified, but the inefficiency can't be helped with the current design.
*/
if (cut <= 0 || eep > 0) /* eep > 0 iff there are alignment constraints */
maxresult = -1;
else
maxresult = cut;
simulate(&matchlist, &maxresult, 0, 0,
state_vector, target_vector,
reftab_vector, reftab_target_vector,
p);
if (initial_matchlist_debug) {
Rprintf("After simulation for transition %d:\n ", p);
show_matchlist(matchlist);
}
if (progress_bar && !evalenv->aligned)
progress_bar_message(current_transition, trans_count, "merging reslt");
/* reduce matchlist for this pass */
Setop(&matchlist, Reduce, NULL);
/* collect the matches (unless there's only one transition) */
if (!FirstTransitionIsDeterministic) {
Setop(&total_matchlist, Union, &matchlist);
}
if (initial_matchlist_debug && (!FirstTransitionIsDeterministic)) {
Rprintf("Complete Matchlist after simulating transition %d: \n", p);
show_matchlist(total_matchlist);
}
}
}
else {
if (EvaluationIsRunning) {
cqpmessage(Error, "Problems while computing initial matchlist for pattern %d. Aborted.\n", p);
EvaluationIsRunning = 0;
}
}
if (!FirstTransitionIsDeterministic)
free_matchlist(&matchlist);
if (progress_bar && !evalenv->aligned)
progress_bar_clear_line();
} /* end of loop over all initial transitions */
/* if there's only one transition, the total matchlist is the same as the matchlist
of that transition, so we just copy it (note that we didn't initialize total_matchlist
in that case */
if (FirstTransitionIsDeterministic)
total_matchlist = matchlist;
if (initial_matchlist_debug) {
Rprintf("After total simulation:\n");
show_matchlist(total_matchlist);
}
if (!EvaluationIsRunning) {
cqpmessage(Warning, "Evaluation interruted: results will be incomplete.");
if (which_app == cqp) install_signal_handler();
}
check_alignment_constraints(&total_matchlist);
EvaluationIsRunning = 0;
/* may need to reduce again after checking alignment constraints */
Setop(&total_matchlist, Reduce, NULL);
if (initial_matchlist_debug) {
Rprintf("after final reducing\n");
show_matchlist(total_matchlist);
}
set_corpus_matchlists(evalenv->query_corpus,
&total_matchlist,
1,
keep_old_ranges);
free_matchlist(&total_matchlist);
free(state_vector);
free(target_vector);
for (i = 0; i < evalenv->dfa.Max_States; i++) {
delete_reftab(reftab_vector[i]);
delete_reftab(reftab_target_vector[i]);
}
free(reftab_vector);
free(reftab_target_vector);
}
}
/**
* This function wraps round simulate_dfa (the only other thing it does is enforce the hard_cut limit).
*
* @see hard_cut
* @see simulate_dfa
*/
void
cqp_run_query(int cut, int keep_old_ranges)
{
if (eep >= 0) {
if (hard_cut > 0)
if (hard_cut < cut)
cut = hard_cut;
simulate_dfa(0, cut, keep_old_ranges);
}
}
int eval_mu_tree(Evaltree et, Matchlist* ml);
void
cqp_run_mu_query(int keep_old_ranges, int cut_value)
{
Matchlist matchlist;
int ok;
init_matchlist(&matchlist);
evalenv = &Environment[0];
assert(evalenv->query_corpus);
ok = eval_mu_tree(evalenv->evaltree, &matchlist);
if (! ok) {
cqpmessage(Error, "Evaluation of MU query has failed (or been interrupted by user)");
free_matchlist(&matchlist); /* automatically initialises to empty match list */
}
if (matchlist.tabsize > 0) {
mark_offrange_cells(&matchlist, evalenv->query_corpus);
Setop(&matchlist, Reduce, NULL);
if (cut_value > 0 && matchlist.tabsize > cut_value) {
int i;
for (i = cut_value; i < matchlist.tabsize; i++)
matchlist.start[i] = -1;
Setop(&matchlist, Reduce, NULL);
}
matchlist.end = (int *)cl_malloc(sizeof(int) * matchlist.tabsize);
memcpy(matchlist.end, matchlist.start, sizeof(int) * matchlist.tabsize);
}
else {
assert(matchlist.start == NULL);
}
set_corpus_matchlists(evalenv->query_corpus,
&matchlist,
1,
keep_old_ranges);
}
void
cqp_run_tab_query()
{
int nr_columns, i, this_col;
Evaltree col;
int smallest_col;
int n_res, max_res;
Matchlist *lists, result;
int *positions;
Evaltree *constraints;
/* ------------------------------------------------------------ */
evalenv = &Environment[0];
assert(evalenv->query_corpus);
/* corpus_size = evalenv->query_corpus->mother_size; */
nr_columns = 0;
for (col = evalenv->evaltree; col; col = col->tab_el.next) {
assert((col->type = tabular));
if (evalenv->patternlist[col->tab_el.patindex].type != Pattern) {
cqpmessage(Error, "matchall [] (or another token pattern matching the entire corpus) is not allowed in TAB query (column #%d)\n", nr_columns + 1);
init_matchlist(&result);
set_corpus_matchlists(evalenv->query_corpus, &result, 1, 0); /* return empty result set */
return;
}
nr_columns++;
}
assert(nr_columns > 0);
/* allocate matchlists for all TAB columns, a vector of list offsets, and a list of constraint trees */
lists = (Matchlist *)cl_calloc(nr_columns, sizeof(Matchlist));
positions = (int *)cl_calloc(nr_columns, sizeof(int));
constraints = (Evaltree *)cl_calloc(nr_columns, sizeof(Evaltree));
/* compute matchlists for all column constraints in the TAB query */
i = 0;
smallest_col = 0;
for (col = evalenv->evaltree; col; col = col->tab_el.next) {
constraints[i] = col;
init_matchlist(&lists[i]);
calculate_initial_matchlist(evalenv->patternlist[col->tab_el.patindex].con.constraint,
&lists[i], evalenv->query_corpus);
/** useful for debugging:
* printf("TAB pattern #%d: %d hits %s %s\n", i + 1, lists[i].tabsize,
* (lists[i].is_inverted) ? "(inverted)" : "", (lists[i].matches_whole_corpus) ? "(whole corpus)" : "");
*/
if (lists[smallest_col].tabsize > lists[i].tabsize)
smallest_col = i;
i++;
}
max_res = lists[smallest_col].tabsize;
init_matchlist(&result);
if (max_res > 0) {
/* ---------------------------------------- */
/* A simple greedy algorithm:
* - for each start position (column 0)
* - find nearest item from next column within distance range
* - if successful, fix this item and proceed to next column
* - if greedy algorithm doesn't find a match, the start position is discarded (even if it might match with different assignment)
* - the original algorithm used to "consume" the items from all columns that participate in a match (so they are no longer available for subsequent matches);
* this produces inconsistent results that are hard to predict, similar to the original implementation of MU queries
* (consider e.g. the sequence A1 .. A2 .. B1 .. C1 .. B2 .. C2: the algorithm would match A1-B1-C1 and A2-B2-C2, but without A1 it would match A2-B1-C1)
* - new algorithm does not to consume items from columns >= 1, so it now predictably matches A1-B1-C1 and A2-B1-C1
* - similar to the standard matching strategy of regular queries, nested matches are discarded, returning only the "early match" A1-B1-C1 in the example
* - as a consequence, each item from any column cannot participate in more than one of the final matches and the result set is bounded by the shortest column
* - TAB queries do not respect the matching strategy setting because this makes little sense without implementing a complete combinatorial search
*/
/* allocate result matchlist (for up to max_res matches) */
result.start = (int *)cl_malloc(sizeof(int) * max_res);
result.end = (int *)cl_malloc(sizeof(int) * max_res);
n_res = 0; /* also serves as pointer into the result matchlist */
while (positions[0] < lists[0].tabsize) {
int next_col, this_pos, next_pos, l_pos, r_pos, boundary;
/* The original implementation of TAB queries completely ignored the optional "within" constraint (which defaults to hard_boundary tokens).
* In order to evaluate the query correctly, we must first determine a right boundary for the complete TAB match, which will also be used
* to cut off unlimited distances (repeat_inf) between TAB columns.
*/
boundary = calculate_rightboundary(evalenv->query_corpus, lists[0].start[positions[0]], evalenv->search_context);
if (boundary < 0) {
/* can't get a match here (because of a "within <s-att>" constraint);
* note that we cannot rely on falling through in the first iteration of the for loop in case there is just a single column
* (e.g. "TAB [] within head;" would fail to apply the "within" constraint)
*/
positions[0]++;
continue;
}
/* iterate over pairs of adjacent columns, scanning for a greedy match within specified distance */
next_pos = -1;
for (next_col = 1; next_col < nr_columns; next_col++) {
this_col = next_col - 1;
/* offset in matchlist for current column */
this_pos = lists[this_col].start[positions[this_col]];
/* valid range for a matching cpos in the next column */
l_pos = cl_cpos_offset(this_pos, constraints[next_col]->tab_el.min_dist, boundary + 1, 0); /* NB: set virtual corpus size to boundary + 1 */
if (l_pos < 0)
break; /* beyond search boundary, no match possible */
if (constraints[next_col]->tab_el.max_dist == repeat_inf)
r_pos = cl_cpos_offset(this_pos, hard_boundary, boundary + 1, 1);
else
r_pos = cl_cpos_offset(this_pos, constraints[next_col]->tab_el.max_dist, boundary + 1, 1);
/* scan next column for a potential match (with cpos >= l_pos) */
while (positions[next_col] < lists[next_col].tabsize &&
(next_pos = lists[next_col].start[positions[next_col]]) < l_pos) {
positions[next_col]++;
}
/* no potential match found or not in range (i.e. !(next_pos <= r_pos)) */
if (positions[next_col] >= lists[next_col].tabsize || next_pos > r_pos)
break;
}
if (next_col >= nr_columns) {
/* we have found a greedy match: copy it to the result matchlist */
l_pos = lists[0].start[positions[0]]; /* start of match = cpos of first column */
r_pos = lists[nr_columns - 1].start[positions[nr_columns - 1]]; /* end of match = cpos of last column */
/* discard nested matches; the only possible case is that r_pos == result.end[n_res - 1] */
if (n_res == 0 || r_pos > result.end[n_res - 1]) {
assert(n_res < max_res);
result.start[n_res] = l_pos;
result.end[n_res] = r_pos;
n_res++;
}
}
positions[0]++;
}
/* finalize the result matchlist */
if (n_res > 0) {
if (n_res < max_res) {
/* shorten vectors if necessary */
result.start = (int *)cl_realloc(result.start, sizeof(int) * n_res);
result.end = (int *)cl_realloc(result.end, sizeof(int) * n_res);
}
result.tabsize = n_res;
/* delete offrange cells if we are in a subcorpus */
if (mark_offrange_cells(&result, evalenv->query_corpus) > 0)
Setop(&result, Reduce, NULL);
}
else {
/* no matches: return empty matchlist */
cl_free(result.start);
cl_free(result.end);
result.tabsize = 0;
}
} /* otherwise max_res == 0 and result has already been initialized as an empty matchlist */
set_corpus_matchlists(evalenv->query_corpus,
&result, 1, 0);
/* cleanup */
cl_free(positions);
cl_free(constraints);
for (i = 0; i < nr_columns; i++)
free_matchlist(&lists[i]);
cl_free(lists);
free_matchlist(&result);
}
/* ---------------------------------------------------------------------- */
int
meet_mu(Matchlist *list1, Matchlist *list2,
int lw, int rw,
Attribute *struc)
{
/* NB: list1 will be modified in place, list2 remains unchanged and will be deallocated by the caller */
int i, j, k, start, end;
int corpus_size = evalenv->query_corpus->mother_size; /* corpus size needed for boundary checks below */
if ((list1->tabsize == 0) || (list2->tabsize == 0)) {
/* If one of the two lists is empty, so is their intersection and we're done. */
cl_free(list1->start);
cl_free(list1->end);
list1->tabsize = 0;
list1->matches_whole_corpus = 0;
}
else {
/* Implementation modified to give consistent "filtering" semantics (SE, 2017-07-01)
* - result of (meet A B <win>) are those items of A for which at least one item of B occurs within <win>
* - the same item of B can satisfy this constraint for multiple items of A, which is achieved simply by not "consuming" this item
* - because both match lists are ordered, the filter can be applied efficiently in a single forward pass
* - new consistent behaviour is now documented in the CQP Query Language Tutorial
*/
/* since we're filtering list1, we can simply upcopy items that pass the filter */
i = 0; /* index in list1 */
j = 0; /* index in list2 */
k = 0; /* insertion point in list1 as result list */
while ((i < list1->tabsize) && (j < list2->tabsize)) {
/* check whether this item from A can be matched against an item from B in the window [start, end] */
if (struc != NULL) {
/* s-attribute context: find region containing current point in A, otherwise there can be no match here */
if (!get_struc_attribute(struc, list1->start[i], &start, &end)
|| (cderrno != CDA_OK)) {
i++;
continue;
}
}
else {
/* numeric context: compute start and end as offsets from current corpus position in A
* - in principle, no boundary checks would be needed because we will only compare valid positions (from B) with the window
* - however, we need to check for integer overflow in case we are dealing with a very large corpus
* (or with an idiot who thinks it's funny to specify a context window of -2147483647 +2147483647 in his query)
* - we need to distinguish between two cases: whether the boundary specifies a (i) minimum or (ii) a maximum distance
* - case (i) occurs for a start offset lw > 0 (e.g. 2 5) and for an end offset rw < 0 (e.g. -4 -2)
* - if a minimum distance boundary (i) falls outside the corpus, we cannot possibly find a match -> skip and continue
* - a maximum distance boundary (ii) can simply be clamped to the range of valid corpus positions
* - because of these case distinctions, the boundary checks are fairly expensive, but cannot be avoided without 64bit ints
*/
start = cl_cpos_offset(list1->start[i], lw, corpus_size, lw <= 0); /* clamp to corpus if lw specifies a maximum distance */
end = cl_cpos_offset(list1->start[i], rw, corpus_size, rw >= 0); /* clamp if rw specifies a maximum distance */
/* if a minimum distance is outside the corpus, there can be no match here */
if (start < 0 || end < 0) {
i++;
continue;
}
}
/* [start, end] is now a valid cpos range (which may be empty for end < start) and we try to find an item from B in this window */
if (end < list2->start[j]) {
i++; /* no item of B within context window */
}
else {
while (j < list2->tabsize && list2->start[j] < start)
j++; /* skip items of B before start of current context window */
/* note that we never have to move backwards in list2 because the context windows will be strictly increasing */
/* now check for a match within the context window unless we have already reached the end of B */
if (j < list2->tabsize && list2->start[j] <= end) {
assert((start <= list2->start[j]) && (list2->start[j] <= end)); /* verify that this is a valid match, as it should be */
list1->start[k] = list1->start[i]; /* upcopy match to insertion point within A */
i++;
k++;
}
else {
i++; /* no match for current point in A */
}
}
assert(k <= list1->tabsize && k <= i); /* make sure that the upcopy works correctly */
} /* end of loop filtering A against B */
if (k == 0) {
/* the result is empty, so free list1 */
cl_free(list1->start); /* also sets the pointer to NULL */
}
else if (k < list1->tabsize) {
/* reallocate vector if the number of matches has been reduced */
list1->start = (int *)cl_realloc(list1->start, sizeof(int) * k);
}
list1->tabsize = k;
list1->matches_whole_corpus = 0; /* should already be the case */
} /* end of case where neither of the two matchlists is empty */
return 1;
}
int
eval_mu_tree(Evaltree et, Matchlist* ml)
{
Matchlist arg2;
int ok;
assert(et);
if (et->type == meet_union) {
switch (et->cooc.op_id) {
case cooc_meet:
init_matchlist(&arg2);
if (! eval_mu_tree(et->cooc.left, ml))
return 0;
if (! eval_mu_tree(et->cooc.right, &arg2)) {
free_matchlist(&arg2);
return 0;
}
ok = meet_mu(ml, &arg2, et->cooc.lw, et->cooc.rw, et->cooc.struc);
free_matchlist(&arg2);
return ok;
break;
case cooc_union:
init_matchlist(&arg2);
if (! eval_mu_tree(et->cooc.left, ml))
return 0;
if (! eval_mu_tree(et->cooc.right, &arg2)) {
free_matchlist(&arg2);
return 0;
}
Setop(ml, Union, &arg2);
free_matchlist(&arg2);
return 1;
break;
default:
assert("Illegal node type in cooc" && 0);
break;
}
}
else if (et->type == leaf) {
assert(CurEnv);
EvaluationIsRunning = 1;
ok = calculate_initial_matchlist(evalenv->patternlist[et->leaf.patindex].con.constraint,
ml, evalenv->query_corpus);
return ok && EvaluationIsRunning; /* aborts evaluation on user interrupt */
}
else {
assert("Illegal node type in MU Evaluation Tree" && 0);
}
assert(0 && "Not reached");
return 0;
}
/* ---------------------------------------------------------------------- */
/**
* Sets up a new environment in the global array.
*
* The next slot upwards is used (and eep is incremented).
*
* @see eep
* @see Environment
* @return True for all OK, false for an error (overflow of MAXENVIRONMENT).
*/
int
next_environment(void)
{
if (eep >= MAXENVIRONMENT) {
Rprintf("No more environments for evaluation (max %d exceeded)\n",
MAXENVIRONMENT);
return 0;
}
else {
eep++;
Environment[eep].query_corpus = NULL;
Environment[eep].labels = new_symbol_table();
Environment[eep].MaxPatIndex = -1;
Environment[eep].gconstraint = NULL;
Environment[eep].evaltree = NULL;
Environment[eep].has_target_indicator = 0;
Environment[eep].target_label = NULL;
Environment[eep].match_label = NULL;
Environment[eep].matchend_label = NULL;
init_dfa(&Environment[eep].dfa);
Environment[eep].search_context.direction = leftright;
Environment[eep].search_context.type = word;
Environment[eep].search_context.attrib = NULL;
Environment[eep].search_context.size = 0;
Environment[eep].negated = 0;
Environment[eep].matching_strategy = matching_strategy; /* initialize from current global setting */
CurEnv = &Environment[eep];
return 1;
}
}
/**
* Frees an evaluation environment.
*
* The environment must be one currently occupied within the global array.
*
* @see Environment
* @see eep
* @param thisenv The eval environment to free.
* @return Boolean: true if the deletion went OK;
* false if the environment to be freed was
* not occupied (will print an error message).
*/
int
free_environment(int thisenv)
{
int i;
if ((thisenv < 0) || (thisenv > eep)) {
Rprintf("Environment %d not occupied\n", thisenv);
return 0;
}
else {
Environment[thisenv].query_corpus = NULL;
delete_symbol_table(Environment[thisenv].labels);
Environment[thisenv].labels = NULL;
for (i = 0; i <= Environment[thisenv].MaxPatIndex; i++) {
switch (Environment[thisenv].patternlist[i].type) {
case Pattern:
free_booltree(Environment[thisenv].patternlist[i].con.constraint);
Environment[thisenv].patternlist[i].con.constraint = NULL;
Environment[thisenv].patternlist[i].con.label = NULL;
Environment[thisenv].patternlist[i].con.is_target = False;
Environment[thisenv].patternlist[i].con.lookahead = False;
break;
case Tag:
Environment[thisenv].patternlist[i].tag.attr = NULL;
Environment[thisenv].patternlist[i].tag.right_boundary = NULL;
cl_free(Environment[thisenv].patternlist[i].tag.constraint);
Environment[thisenv].patternlist[i].tag.flags = 0;
if (Environment[thisenv].patternlist[i].tag.rx) {
cl_delete_regex(Environment[thisenv].patternlist[i].tag.rx);
Environment[thisenv].patternlist[i].tag.rx = NULL;
}
break;
case Anchor:
Environment[thisenv].patternlist[i].anchor.field = NoField;
break;
case MatchAll:
Environment[thisenv].patternlist[i].matchall.label = NULL;
Environment[thisenv].patternlist[i].matchall.is_target = False;
Environment[thisenv].patternlist[i].matchall.lookahead = False;
break;
default:
assert("Illegal AVS type in pattern list of ee" && 0);
break;
}
}
Environment[thisenv].MaxPatIndex = -1;
free_booltree(Environment[thisenv].gconstraint);
Environment[thisenv].gconstraint = NULL;
free_evaltree(&Environment[thisenv].evaltree);
if (Environment[thisenv].dfa.TransTable)
free_dfa(&Environment[thisenv].dfa);
Environment[thisenv].search_context.direction = leftright;
Environment[thisenv].search_context.type = word;
Environment[thisenv].search_context.attrib = NULL;
Environment[thisenv].search_context.size = 0;
Environment[thisenv].has_target_indicator = 0;
return 1;
}
}
/**
* Prints the contents of an EvalEnvironment object to STDOUT.
*
* Which bits of information are printed depends on which of a group of
* debugging-variables are set to true.
*
* The EvalEnvironment to print is specified as an index into the global
* array (Environment).
*
* @see Environment
* @param thisenv Index into Environment indicating which EvalEnvironment
* should be displayed.
*/
void
show_environment(int thisenv)
{
if ((thisenv < 0) || (thisenv > eep))
Rprintf("Environment %d not used\n", thisenv);
else if (show_compdfa || show_evaltree || show_gconstraints || show_patlist) {
/* Note, at least one of the above debugging-variables must be true, or there is nothing to print! */
Rprintf("\n ================= ENVIRONMENT #%d ===============\n\n", thisenv);
Rprintf("Has %starget indicator.\n", Environment[thisenv].has_target_indicator ? "" : "no ");
if (show_compdfa) {
Rprintf("\n==================== DFA:\n\n");
show_complete_dfa(Environment[thisenv].dfa);
}
if (show_evaltree) {
Rprintf("\n==================== Evaluation Tree:\n\n");
print_evaltree(thisenv, Environment[thisenv].evaltree, 0);
}
if (show_gconstraints) {
Rprintf("\n==================== Global Constraints:\n\n");
print_booltree(Environment[thisenv].gconstraint, 0);
}
if (show_patlist)
show_patternlist(thisenv);
Rprintf(" ================= END ENVIRONMENT #%d =============\n", thisenv);
fflush(stdout);
}
}
/**
* Frees all eval environments in the global array, and sets the eep pointer to -1
*/
void
free_environments(void)
{
int i;
for (i = 0; i <= eep; i++)
if (!free_environment(i)) {
Rprintf("Problems while free'ing environment %d\n", i);
break;
}
eep = -1;
}
|
myoKun345/RcppCWB
|
src/cwb/cqp/ranges.c
|
<filename>src/cwb/cqp/ranges.c
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include "../cl/globals.h"
#include "../cl/corpus.h"
#include "../cl/attributes.h"
#include "../cl/cdaccess.h"
#include "../cl/macros.h"
/* for string functions, should only use what is avaialable via public api #include "../cl/special-chars.h" */
#include "corpmanag.h"
#include "eval.h"
#include "ranges.h"
#include "output.h"
#include "matchlist.h"
#include "options.h"
#define SORT_DEBUG 0
/**
* Delete a single cpos-pair (a corpus zone or single query match)
* from a query-generated subcorpus.
*
* This function is not currently in use.
*
* @param cp The CorpusList indicating the query to delete from.
* @param nr The index of the interval to delete (by setting its
* start and end values to -1).
* @return Boolean: true for success, false for failure.
*/
int
delete_interval(CorpusList *cp, int nr)
{
int result;
if ((!cp) ||
(cp->type != SUB) ||
(cp->size <= 0) ||
(nr < 0) ||
(nr >= cp->size))
return 0;
else {
cl_free(cp->sortidx);
cp->range[nr].start = -1;
cp->range[nr].end = -1;
result = RangeSetop(cp, RReduce, NULL, NULL);
return result;
}
}
/**
* Delete a whole bunch of concordance hits from a query-generated subcorpus.
*
* @param cp The CorpusList indicating the query to delete from.
* @param intervals A Bitfield containing a bit for each query hit, which
* is true if the hit is "selected", false if not.
* @param mode ALL_LINES, SELECTED_LINES or UNSELECTED_LINES (indicating
* which lines to delete).
* @return Boolean: true for success, false for failure.
*/
int
delete_intervals(CorpusList *cp, Bitfield intervals, int mode)
{
int i;
int result; /* boolean to return at the end */
int modified; /* count of the number of lines deleted */
int bit; /* temp storage for value retrieved from bitfield */
if ((!cp) ||
!((cp->type == SUB) || (cp->type == TEMP)) ||
(cp->size <= 0))
return 0;
else {
assert(intervals && (intervals->elements == cp->size));
modified = 0;
switch (mode) {
case ALL_LINES:
modified = cp->size;
break;
case SELECTED_LINES:
case UNSELECTED_LINES:
/* for each hit, check whether it is "selected"
* then delete, or not, depending on mode */
for (i = 0; i < cp->size; i++) {
bit = get_bit(intervals, i);
if (((mode == SELECTED_LINES) && bit) ||
((mode == UNSELECTED_LINES) && !bit)) {
modified++;
cp->range[i].start = -1;
cp->range[i].end = -1;
}
}
break;
default:
assert(0 && "Unsupported deletion mode");
break;
}
if (modified) {
/* if all hits were deleted... */
if (modified == cp->size) {
cl_free(cp->sortidx);
cl_free(cp->keywords);
cl_free(cp->targets);
cl_free(cp->range);
cp->size = 0;
}
else {
/* not all hits were deleted */
/* Vorerst, bis mir ein guter Algorithmus zur
* Erhaltung der Sortierung einfaellt TODO TODO
*/
cl_free(cp->sortidx);
result = RangeSetop(cp, RReduce, NULL, NULL);
}
/* since at least one hit was modified, touch the
* corpuslist that represents the query */
touch_corpus(cp);
if (auto_save && cp->type == SUB)
save_subcorpus(cp, NULL);
result = 1;
}
else
result = 1;
return result;
}
}
/**
* Copy concordance hits from a query-generated subcorpus to a
* (new or existing) subcorpus.
*
* This function is not currently in use.
*
* @param cp The CorpusList indicating the query to copy from.
* @param intervals A Bitfield containing a bit for each query hit, which
* is true if the hit is "selected", false if not.
* @param mode ALL_LINES, SELECTED_LINES or UNSELECTED_LINES (indicating
* which lines to copy).
* @param subcorpname Name for the subcorpus to which the lines are to be
* copied.
* @return Boolean: true for success, false for failure.
*/
int
copy_intervals(CorpusList *cp,
Bitfield intervals,
int mode,
char *subcorpname)
{
CorpusList *new_sub;
int result;
int i;
/* cp must be a query-generated subcorpus containing at least 1 hit */
if ((!cp) || (cp->type != SUB) || (cp->size <= 0))
return 0;
else {
assert(intervals && (intervals->elements == cp->size));
new_sub = findcorpus(subcorpname, UNDEF, 0);
if (new_sub == NULL) {
/*
* No corpus of this name exists already! So we can create it.
* First, we copy the source corpus to a new corpus.
* If that was ok, we delete the lines in intervals with
* the inverse mode.
*/
new_sub = duplicate_corpus(cp, subcorpname, 0);
if (new_sub == NULL) {
cqpmessage(Error,
"Can't copy intervals from %s to %s (corpus creation failed)\n",
cp->name, subcorpname);
return 0;
}
switch (mode) {
case SELECTED_LINES:
result = delete_intervals(new_sub, intervals, UNSELECTED_LINES);
break;
case UNSELECTED_LINES:
result = delete_intervals(new_sub, intervals, SELECTED_LINES);
break;
default:
cqpmessage(Error, "Illegal copy_intervals mode %d\n", mode);
dropcorpus(new_sub);
result = 0;
break;
}
}
else if (new_sub == cp) {
cqpmessage(Error, "Can't add/copy to myself!");
result = 0;
}
else if (new_sub->type == SYSTEM) {
cqpmessage(Error, "Can't add/copy intervals to a system corpus");
result = 0;
}
else if (strcmp(new_sub->mother_name, cp->mother_name) != 0) {
cqpmessage(Error,
"Underlying corpus of source (%s) and\n"
"underlying corpus of target (%s)\n"
"differ",
cp->mother_name, new_sub->mother_name);
result = 0;
}
else {
/* if we're here, then we are copying to an existing subcorpus
* that it is OK to copy to - so, try to do it. */
if (mode == UNSELECTED_LINES)
for (i = 0; i < cp->size; i++)
toggle_bit(intervals, i);
result = RangeSetop(new_sub, RUnion, cp, intervals);
}
if (result && auto_save && new_sub && new_sub->type == SUB && new_sub->saved == False)
save_subcorpus(new_sub, NULL);
return result;
} /* end else (query exists and has at least one hit */
}
int
calculate_ranges(CorpusList *cl, int cpos, Context spc, int *left, int *right)
{
int corpsize;
int rng_s, rng_e, rng_n, nrng_s, nrng_e, r1, r2, nr_rngs, d;
switch(spc.type) {
case word:
d = spc.size;
if (d < 0)
return 0;
corpsize = cl->mother_size;
assert(corpsize > 0);
*left = MAX(0, cpos - d);
d = MIN(d, (corpsize - 1) - cpos); /* avoid 32-bit wrap-around for very very large corpora (close to CL_MAX_CORPUS_SIZE) */
*right = cpos + d;
break;
case structure:
d = spc.size - 1;
if (d < 0)
return 0;
assert(spc.attrib);
if (!get_struc_attribute(spc.attrib, cpos, &rng_s, &rng_e))
return(0);
if (!get_num_of_struc(spc.attrib, cpos, &rng_n))
return(0);
/* determine the lower range number */
r1 = MAX(0, rng_n - d);
if (!get_bounds_of_nth_struc(spc.attrib,
r1,
&nrng_s,
&nrng_e))
return 0;
*left = nrng_s;
/* Ssame procedja as last yea */
/* determine the upper range number */
if (!get_nr_of_strucs(spc.attrib, &nr_rngs))
return 0;
r2 = MIN(nr_rngs-1, rng_n + d);
if (!get_bounds_of_nth_struc(spc.attrib,
r2,
&nrng_s,
&nrng_e))
return 0;
*right = nrng_e;
break;
default:
Rprintf("calculate_ranges: undefined space type %d detected\n", spc.type);
exit(1);
break;
}
return 1;
}
int
calculate_rightboundary(CorpusList *cl, int cpos, Context spc)
{
int left, right;
return (calculate_ranges(cl, cpos, spc, &left, &right)? right : -1);
}
int
calculate_leftboundary(CorpusList *cl, int cpos, Context spc)
{
int left, right;
return (calculate_ranges(cl, cpos, spc, &left, &right)? left : -1);
}
/** this is a rather specialised utility function for the UNION part of RangeSetop()
(copies range + keyword/target (if defined) in corpus into temporary lists)*/
void
rs_cp_range(Range *rng, int *target, int *keyword, int ins, CorpusList *corpus, int j)
{
rng[ins].start = corpus->range[j].start;
rng[ins].end = corpus->range[j].end;
if (target != NULL) { /* target/keyword vectors may be undefined */
if (corpus->targets)
target[ins] = corpus->targets[j];
else
target[ins] = -1;
}
if (keyword != NULL) {
if (corpus->keywords)
keyword[ins] = corpus->keywords[j];
else
keyword[ins] = -1;
}
}
/** Variable used by _RS_compare_ranges; global so data can be passed in
* without going through that function's parameter list! */
Range *_RS_range = NULL;
/** qsort() helper function for RangeSort() below */
int
_RS_compare_ranges (const void *pa, const void *pb)
{
Range *a = _RS_range + *((int *) pa); /* compare ranges #a and #b */
Range *b = _RS_range + *((int *) pb);
if (a->start < b->start) /* start(a) < start(b) */
return -1;
else if (a->start > b->start) /* start(a) > start(b) */
return 1;
else if (a->end > b->end) /* start(a) == start(b) -> larger match first */
return -1;
else if (a->end < b->end)
return 1;
else /* ranges are identical */
return 0;
}
/**
* Make sure that ranges are sorted in 'natural' order (i.e. by start and end cpos).
*
* This function has to be called when matching ranges are modified and may be needed
* when loading a query result (with "undump") that is not sorted in ascending order;
* with optional "mk_sortidx" flag, a sortidx corresponding to the original ordering
* is created.
*
* @param c The corpus (ie subcorpus/query) whose intervals ('ranges') are
* to be sorted.
* @param mk_sortidx Boolean flag: if true a sortidx is created.
*/
void
RangeSort(CorpusList *c, int mk_sortidx)
{
Range *new_range = NULL;
int *new_targets = NULL, *new_keywords = NULL;
int *new_sortidx = NULL;
int *index = NULL; /* sort index for qsort() function */
int size, i;
if (c->type != SUB && c->type != TEMP) {
/* function only works for named queries (= subcorpora) */
cqpmessage(Error, "Argument to internal function RangeSort() is not a named query result.");
return;
}
if (c->sortidx) {
/* sortidx will now longer be valid after operation and is deleted */
cqpmessage(Warning,
"Sort ordering of named query %s is out of date and has been deleted.\n"
"\tMatching ranges are now sorted in ascending corpus order.",
c->name);
cl_free(c->sortidx);
}
size = c->size; /* size of query result */
index = cl_malloc(size * sizeof(int)); /* allocate and initialise qsort() index */
for (i = 0; i < size; i++)
index[i] = i;
_RS_range = c->range; /* intialise global data for callback and run qsort() */
qsort(index, size, sizeof(int), _RS_compare_ranges);
/* printf("Resort index is:\n"); */
/* for (i = 0; i < size; i++) */
/* printf("\t%4d => [%d,%d]\n", index[i], c->range[index[i]].start, c->range[index[i]].end); */
new_range = cl_malloc(size * sizeof(Range)); /* allocate new range vector and fill it with sorted ranges */
for (i = 0; i < size; i++)
new_range[i] = c->range[index[i]];
cl_free(c->range); /* then free old vector and replace it with sorted one */
c->range = new_range;
if (c->targets) { /* same for targets (if present) */
new_targets = cl_malloc(size * sizeof(int));
for (i = 0; i < size; i++)
new_targets[i] = c->targets[index[i]];
cl_free(c->targets);
c->targets = new_targets;
}
if (c->keywords) { /* and keywords (if present) */
new_keywords = cl_malloc(size * sizeof(int));
for (i = 0; i < size; i++)
new_keywords[i] = c->keywords[index[i]];
cl_free(c->keywords);
c->keywords = new_keywords;
}
if (mk_sortidx) { /* create new sortidx so that user still sees previous ordering of the matches (used with "undump") */
new_sortidx = cl_malloc(size * sizeof(int));
if (mk_sortidx) {
for (i = 0; i < size; i++)
new_sortidx[index[i]] = i;
}
c->sortidx = new_sortidx;
}
cl_free(index); /* free temporary qsort() index vector */
}
/**
* Carries out one of a set of operations on corpus1.
*
* The operations that can be carried out are as follows:
*
* RUnion - copy intervals from corpus2 to corpus1 (no duplicates);
* RIntersection - remove from corpus1 any intervals that are not also in corpus2;
* RDiff
* RMaximalMatches - remove spurious matches according to "longest" strategy;
* RMinimalMatches - remove spurious matches according to "shortest" strategy;
* RLeftMaximalMatches - remove spurious matches according to "standard" strategy;
* RNonOverlapping
* RUniq - remove duplicate intervals from corpus1;
* RReduce - remove intervals marked for deletion (by having the start memebr set to -1).
*
* TODO to avopid confusion with the object, a better name for this function would be do_RangeSetOp
*
* @param corpus1 The corpus to be changed.
* @param operation Specifies which operation is to be carried out.
* @param corpus2 The corpus that is the second argument for this operation.
* Can be NULL if no corpus2 is required for operation.
* @param restrictor Specifies which intervals in corpus2 are to be taken notice of
* versus ignored. Can be NULL.
* @return Boolean, true for all OK, otherwise false.
*/
int
RangeSetop(CorpusList *corpus1,
RangeSetOp operation,
CorpusList *corpus2,
Bitfield restrictor)
{
int i, j, ins;
int intervals_to_copy;
Range *tmp;
int *tmp_target, *tmp_keyword;
int tmp_size;
/* switch across the different members of RangeSetOp... */
switch (operation) {
case RUnion:
/*
* -------------------- UNION
*/
if ((corpus2 == NULL) || (corpus2->size == 0)) {
/* the result is corpus1, so just return */
return 1;
}
else {
if (restrictor) {
/* count how many intervals are to be copied to corpus1 */
intervals_to_copy = 0;
for (i = 0; i < corpus2->size; i++)
if (get_bit(restrictor, i))
intervals_to_copy++;
}
else
/* we have to copy all the intervals from corpus2 */
intervals_to_copy = corpus2->size;
/* allocate a blob of memory big enough to hold all the Ranges in the union'ed corpus */
tmp_size = corpus1->size + intervals_to_copy;
tmp = (Range *)cl_malloc(sizeof(Range) * tmp_size);
/* allocate targets / keywords if they're present in one of the arguments */
if ((corpus1->targets != NULL) || (corpus2->targets != NULL))
tmp_target = (int *)cl_malloc(sizeof(int) * tmp_size);
else
tmp_target = NULL;
if ((corpus1->keywords != NULL) || (corpus2->keywords != NULL))
tmp_keyword = (int *)cl_malloc(sizeof(int) * tmp_size);
else
tmp_keyword = NULL;
i = 0; /* the position in corpus1 */
j = 0; /* the position in corpus2 */
ins = 0; /* the insertion point in the (unified) result list */
/* loop through the intervals in corpus1 and corpus2 to unify them */
while ( i < corpus1->size || j < corpus2->size ) {
/* while there are intervals left in either corpus... */
if (j >= corpus2->size ||
(i < corpus1->size && (corpus1->range[i].start < corpus2->range[j].start))
) {
/* if we have run out of intervals in corpus2, or if the next interval in
* corpus2 comes later on than the next interval in corpus1,
* copy an item from corpus1 */
rs_cp_range(tmp, tmp_target, tmp_keyword, ins, corpus1, i);
ins++;
/* increment i since we have copied from corpus 1 */
i++;
}
else if (i >= corpus1->size ||
/* NB j < corpus2->size assured in this branch */
(corpus1->range[i].start > corpus2->range[j].start)) {
/* if we have run out of intervals in corpus1, or if the next interval in
* corpus1 comes later on than the next interval in corpus2,
* copy an interval from corpus2 (allowing for the restrictor if necessry) */
if (restrictor == NULL || get_bit(restrictor, j)) {
rs_cp_range(tmp, tmp_target, tmp_keyword, ins, corpus2, j);
ins++;
}
/* increment j since we have copied from corpus 2 */
j++;
}
else {
/* both start positions are identical. Now check whether the end positions are also the same...
*
* => the ranges are identical and we'll copy target/keyword from corpus1
* => the range from corpus1 ends sooner, so we copy that one
* => the range from corpus2 ends sooner, so we copy that one, depending on the restrictor
*
* (for real duplicates, both i and j are incremented; otherwise,
* only the one copied is incremented, so the other is still on the
* pile of intervals to be whiled through.) */
if (corpus1->range[i].end == corpus2->range[j].end) {
rs_cp_range(tmp, tmp_target, tmp_keyword, ins, corpus1, i);
i++;
j++; /* skip the corresponding range in corpus2 */
ins++;
}
else if (corpus1->range[i].end < corpus2->range[j].end) {
rs_cp_range(tmp, tmp_target, tmp_keyword, ins, corpus1, i);
i++;
ins++;
}
else {
if (restrictor == NULL || get_bit(restrictor, j)) {
rs_cp_range(tmp, tmp_target, tmp_keyword, ins, corpus2, j);
ins++;
}
j++;
}
}
} /* endwhile there are intervals left in either corpus */
assert(ins <= tmp_size);
/* we did not eliminate any duplicates if ins == tmp.size => don't bother to realloc */
if (ins < tmp_size) {
tmp = (Range *)cl_realloc((char *)tmp, sizeof(Range) * ins);
if (tmp_target)
tmp_target = (int *)cl_realloc((char *)tmp_target, sizeof(int) * ins);
if (tmp_keyword)
tmp_keyword = (int *)cl_realloc((char *)tmp_keyword, sizeof(int) * ins);
}
/* replace corpus1's fields with temporary vectors */
cl_free(corpus1->range);
cl_free(corpus1->targets);
cl_free(corpus1->keywords);
corpus1->range = tmp;
corpus1->targets = tmp_target; /* may be NULL */
corpus1->keywords = tmp_keyword; /* may be NULL */
corpus1->size = ins;
touch_corpus(corpus1);
return 1;
} /* endif "corpus2 and corpus1 are not the same" */
break;
case RIntersection:
/*
* -------------------- INTERSECTION
* targets / keywords are copied from _left_ operand
*/
i = 0; /* the position in corpus1 */
j = 0; /* the position in corpus2 */
while (i < corpus1->size && j < corpus2->size) {
/* compare start positions; if not equal, advance subcorpus where start position is smaller */
if (corpus1->range[i].start < corpus2->range[j].start) {
corpus1->range[i].start = -1; /* not found -> mark for deletion & advance in corpus1 */
i++;
}
else if (corpus1->range[i].start > corpus2->range[j].start)
j++;
else {
/* both start positions are identical. Now check whether the end positions are also the same */
if (corpus1->range[i].end == corpus2->range[j].end) {
/* this range is in both subcorpora -> keep & advance both pointers */
i++;
j++;
}
else {
/* end positions are not the same -> advance subcorpus where end position is smaller */
if (corpus1->range[i].end < corpus2->range[j].end) {
corpus1->range[i].start = -1; /* not found -> mark for deletion & advance in corpus1 */
i++;
}
else
j++;
}
}
}
/* remove remaining intervals from corpus1 (if corpus2 reached end first) */
while (i < corpus1->size) {
corpus1->range[i].start = -1;
i++;
}
/* remove ranges marked for deletion */
RangeSetop(corpus1, RReduce, NULL, NULL);
touch_corpus(corpus1);
break;
case RDiff:
/*
* -------------------- DIFFERENCE
* (implementation virtually identical to intersection)
*/
i = 0; /* the position in corpus1 */
j = 0; /* the position in corpus2 */
while (i < corpus1->size && j < corpus2->size)
/* compare start positions; if not equal, advance subcorpus where start position is smaller */
if (corpus1->range[i].start < corpus2->range[j].start)
i++;
else if (corpus1->range[i].start > corpus2->range[j].start)
j++;
else {
/* both start positions are identical. Now check whether the end positions are also the same */
if (corpus1->range[i].end == corpus2->range[j].end) {
/* only ranges found in both subcorpora are deleted */
corpus1->range[i].start = -1;
i++;
j++;
}
else {
/* end positions are not the same -> advance subcorpus where end position is smaller */
if (corpus1->range[i].end < corpus2->range[j].end)
i++;
else
j++;
}
}
/* remove ranges marked for deletion */
RangeSetop(corpus1, RReduce, NULL, NULL);
touch_corpus(corpus1);
break;
/* The current DFA evaluation strategy often produces several spurious matches for each real match.
*
* To delete the extra matches we need three variants of the RUniq operator.
* (a) matching strategy 'standard' -> RLeftMaximalMatches
* use the match with the leftmost start and end points;
* since we cannot know which ranges belong to the same real match, we have to select the first
* and shortest range, thus deleting any potential overlapping matches in the process
* (might lead to strange effects occasionally -- evaluation strategy should be reimplemented in CWB-4.0)
* (b) matching strategy 'longest' -> RMaximalMatches
* use the match with the leftmost start point and rightmost end point,
* which is implemented by deleting all matches contained in another, longer interval;
* (which does _not_ automatically delete overlapping matches!)
* (c) matching strategy 'shortest' -> RMinimalMatches
* opposite of (b): use the match with the rightmost start point and leftmost end point,
* which is implemented by deleting all matches that contain another, shorter interval;
* (which, again, does _not_ automatically delete overlapping matches!)
*/
case RMinimalMatches:
/*
* -------------------- MINIMAL MATCHES
* is a cousin of UNIQ ... it removes all intervals from corpus1 which contain another (shorter) interval
*/
i = 0; /* point */
for (i = 0; i < corpus1->size; i++) {
if (corpus1->range[i].start != -1) { /* skip intervals we've already deleted */
int start = corpus1->range[i].start;
j = i+1; /* i becomes mark, j is now point */
while ((j < corpus1->size) &&
(corpus1->range[j].start <= corpus1->range[i].end))
{
if (corpus1->range[j].end <= corpus1->range[i].end) { /* j.start >= i.start implied by j > i */
corpus1->range[i].start = -1; /* delete i if j is fully contained in it */
break; /* no need to continue the inner loop if interval i is already deleted */
}
else {
/* we may have multiple matches with the same starting point; because of the ordering used,
we must forward delete in this case (the first match in the row is the shortest) */
if (start == corpus1->range[j].start)
corpus1->range[j].start = -1; /* delete i if i is contained in j */
j++;
}
}
}
}
/* remove ranges marked for deletion */
RangeSetop(corpus1, RReduce, NULL, NULL);
touch_corpus(corpus1);
break;
case RMaximalMatches:
/*
* -------------------- MAXIMAL MATCHES
* is a cousin of UNIQ ... it removes all intervals from corpus1 which are contained in another (longer) interval
*/
i = 0; /* point */
for (i = 0; i < corpus1->size; i++) {
if (corpus1->range[i].start != -1) { /* skip intervals we've already deleted */
int start = corpus1->range[i].start;
j = i+1; /* i becomes mark, j is now point */
while ((j < corpus1->size) &&
(corpus1->range[j].start <= corpus1->range[i].end))
{
if (corpus1->range[j].end <= corpus1->range[i].end) /* j.start >= i.start implied by j > i */
corpus1->range[j].start = -1; /* delete j if j is contained in i */
else
/* we may have multiple matches with the same starting point; because of the ordering used,
we must backward delete in this case (the last match will be the longest) */
if (start == corpus1->range[j].start)
corpus1->range[i].start = -1; /* delete i if i is contained in j */
j++;
}
}
}
/* remove ranges marked for deletion */
RangeSetop(corpus1, RReduce, NULL, NULL);
touch_corpus(corpus1);
break;
case RLeftMaximalMatches:
/*
* -------------------- LEFT MAXIMAL MATCHES
* used for the shortest match strategy ... delete additional matches inserted by our multi-pass strategy
* [keep shortest match from all matches with same start point, then keep longest one from all matches with same end point]
*/
i = 0; /* point */
for (i = 0; i < corpus1->size; i++) {
if (corpus1->range[i].start != -1) { /* skip intervals we've already deleted */
j = i+1; /* i becomes mark, j is now point */
/* delete all ranges overlapping with the current mark */
while ((j < corpus1->size) && (corpus1->range[j].start == corpus1->range[i].start)) {
corpus1->range[j].start = -1; /* delete all matches j with the same start point as i (-> i is shorter) */
j++;
}
}
}
RangeSetop(corpus1, RReduce, NULL, NULL); /* remove matches deleted in first pass */
i = 0; /* point */
for (i = 0; i < corpus1->size; i++) {
if (corpus1->range[i].start != -1) { /* skip intervals we've already deleted */
j = i+1; /* i becomes mark, j is now point */
while ((j < corpus1->size) && (corpus1->range[j].start <= corpus1->range[i].end)) {
if (corpus1->range[j].end == corpus1->range[i].end) /* j.start >= i.start implied by j > i */
corpus1->range[j].start = -1; /* delete all matches j with the same end point as i (-> j is shorter) */
j++;
}
}
}
RangeSetop(corpus1, RReduce, NULL, NULL); /* remove matches deleted in second pass */
touch_corpus(corpus1);
break;
case RNonOverlapping:
/*
* -------------------- NON-OVERLAPPING MATCHES
* delete overlapping matches before executing subquery (chooses earliest match)
*/
i = 0; /* point */
for (i = 0; i < corpus1->size; i++) {
if (corpus1->range[i].start != -1) { /* skip intervals we've already deleted */
j = i+1; /* i becomes mark, j is now point */
/* delete all ranges overlapping with match i */
while ((j < corpus1->size) &&
(corpus1->range[j].start <= corpus1->range[i].end))
{
corpus1->range[j].start = -1;
j++;
}
}
}
/* remove ranges marked for deletion */
RangeSetop(corpus1, RReduce, NULL, NULL);
touch_corpus(corpus1);
break;
case RUniq:
/*
* -------------------- UNIQ
* remove duplicate intervals from corpus1 (working destructively on it);
* targets/keywords taken from first occurrence
*/
/* Why delete intervals where start points are identical but end points different?
It doesn't solve the problem of overlapping ranges in subqueries, so what was
Oli's intention? Simplest algorithm he could think of? */
/* complete rewrite follows: */
i = 0; /* point */
for (i = 0; i < corpus1->size; i++) {
if (corpus1->range[i].start != -1) { /* skip intervals we've already deleted */
j = i+1; /* i becomes mark, j is now point */
while ((j < corpus1->size) &&
(corpus1->range[i].start == corpus1->range[j].start) &&
(corpus1->range[i].end == corpus1->range[j].end))
{
corpus1->range[j].start = -1; /* delete all but the first */
j++;
}
}
}
/* remove ranges marked for deletion */
RangeSetop(corpus1, RReduce, NULL, NULL);
touch_corpus(corpus1);
break;
/*
* -------------------- REDUCE
* remove intervals marked for deletion (-1) from corpus1;
* adjust target & keyword vectors
*/
case RReduce:
if (corpus1->range && (corpus1->size > 0)) {
ins = 0; /* the insertion point */
for (i = 0; i < corpus1->size; i++) {
if (corpus1->range[i].start < 0 || corpus1->range[i].end < 0) {
/* if this interval is marked as -1 in either member, do nothing */
}
else {
/* otherwise, copy this to the insertion point */
if (i != ins) {
corpus1->range[ins].start = corpus1->range[i].start;
corpus1->range[ins].end = corpus1->range[i].end;
if (corpus1->targets)
corpus1->targets[ins] = corpus1->targets[i];
if (corpus1->keywords)
corpus1->keywords[ins] = corpus1->keywords[i];
}
ins++;
/* if i IS the same as the insertion point, we don't need to copy -
* we haven't encountered any deletables yet, so just keep scrolling
* both i and ins. */
}
} /* endfor each interval in the corpus */
if (ins != corpus1->size) {
/* no elements were deleted from the list when ins == size. So
* we do not have to do anything then.
* Otherwise, the list was used destructively. Free up used space.
*/
corpus1->range = (Range *)cl_realloc(corpus1->range, sizeof(Range) * ins);
if (corpus1->targets)
corpus1->targets = (int *)cl_realloc(corpus1->targets, sizeof(int) * ins);
if (corpus1->keywords)
corpus1->keywords = (int *)cl_realloc(corpus1->keywords, sizeof(int) * ins);
corpus1->size = ins;
cl_free(corpus1->sortidx); /* the sort index is no longer valid in this case */
/* TODO, shouldn't sortidx be set to NULL then? */
touch_corpus(corpus1);
}
}
break;
default:
Rprintf("Operation was %d, ranges from %d to %d\n", operation, RUnion, RReduce);
assert("Illegal operator in RangeSetOp" && 0);
return 0;
break;
} /* end of big switch across all the various operations */
return 1;
}
/* -------------------------------------------------- SORTING and COUNTING */
/* static data for sort function callbacks (shared by external sorting);
* note much of this replicates the contents of a SortClause object, q.v. */
static CorpusList *srt_cl; /**< The CorpusList object representing a query to be sorted. */
static Attribute *srt_attribute; /**< The )p-)Attribute on which a query is to be sorted. */
static int *srt_start; /**< When sorting a query, this contains start positions of intervals to be sorted */
static int *srt_end; /**< When sorting a query, this contains end positions of intervals to be sorted */
static FieldType srt_anchor1; /**< In a query sort, indicates the field type of the start of sort region */
static int srt_offset1; /**< In a query sort, indicates the offset of the start of sort region */
static FieldType srt_anchor2; /**< In a query sort, indicates the field type of the end of sort region */
static int srt_offset2; /**< In a query sort, indicates the offset of the end of sort region */
/*static unsigned char *srt_maptable; / **< character mapping for %c and %d flags TODO deleted in unicode-version. */
static int srt_flags; /**< Whether to use the %c and/or %d flags when sorting a query. */
static int srt_ascending; /**< boolean: sort query into ascending order or not */
static int srt_reverse; /**< boolean: sort query on reversed-character-sequence strings
(and reversed sequences OF strings) or not */
static int text_size; /**< When sorting a query - this represents the size of the corpus the query belongs to */
static int break_ties; /**< whether to break ties (by comparison without %cd flags,
and by line number in the last instance) */
static unsigned int *random_sort_keys; /**< random keys for randomized sort order (ties are broken by cpos of matches) */
/* static data for count function callbacks */
static int *group_first; /**< first match for each group of identical (or equivalent) sort strings */
static int *group_size; /**< number of matches for each group of identical (or equivalent) sort strings */
static int *current_sortidx; /**< alias to newly created sortidx, so it can be accessed by the callback function */
/**
* Use an external program to sort a query.
*
* No parameters - the assumption is that everything is set up
* already by the SortSubCorpus function which calls this one.
*/
/*
int
SortExternally(void)
{
char temporary_name[TEMP_FILENAME_BUFSIZE];
FILE *fd;
FILE *pipe;
char sort_call[CL_MAX_LINE_LENGTH];
if ((fd = open_temporary_file(temporary_name)) != NULL) {
int line, p1start, p1end, plen, step, token, l;
line = -1;
if (text_size > 0) {
for (line = 0; line < srt_cl->size; line++) {
Rprintf("%d ", line);
switch (srt_anchor1) {
case MatchField:
p1start = srt_cl->range[line].start + srt_offset1;
break;
case MatchEndField:
p1start = srt_cl->range[line].end + srt_offset1;
break;
case KeywordField:
p1start = srt_cl->keywords[line] + srt_offset1;
break;
case TargetField:
p1start = srt_cl->targets[line] + srt_offset1;
break;
default:
assert(0 && "Oopsie -- illegal first anchor in SortExternally()");
break;
}
switch (srt_anchor2) {
case MatchField:
p1end = srt_cl->range[line].start + srt_offset2;
break;
case MatchEndField:
p1end = srt_cl->range[line].end + srt_offset2;
break;
case KeywordField:
p1end = srt_cl->keywords[line] + srt_offset2;
break;
case TargetField:
p1end = srt_cl->targets[line] + srt_offset2;
break;
default:
assert(0 && "Oopsie -- illegal second anchor in SortExternally()");
break;
}
if (p1start < 0)
p1start = 0;
else if (p1start >= text_size)
p1start = text_size - 1;
if (p1end < 0)
p1end = 0;
else if (p1end >= text_size)
p1end = text_size - 1;
if (srt_reverse) {
int temp;
temp = p1start; p1start = p1end; p1end = temp;
}
step = (p1end >= p1start) ? 1 : -1;
plen = abs(p1end - p1start) + 1;
if (srt_flags) {
token = p1start;
for (l=1 ; l <= plen ; l++) {
char *value = cl_cpos2str(srt_attribute, token);
int del_value = 0;
if (value) {
int i, p = strlen((char *) value);
if (srt_flags) {
value = cl_string_canonical(value, srt_cl->corpus->charset, srt_flags, CL_STRING_CANONICAL_STRDUP);
del_value = 1;
}
if (srt_reverse) {
char *newvalue = cl_string_reverse(value, srt_cl->corpus->charset);
if (del_value)
cl_free(value);
value = newvalue;
del_value = 1;
}
for (i = 0; i < p; i++)
fputc((unsigned char) value[i], fd);
fputc(' ', fd);
if (del_value)
cl_free(value);
}
token += step;
}
Rprintf("\t");
}
token = p1start;
for (l = 1 ; l <= plen ; l++) {
char *value = cl_cpos2str(srt_attribute, token);
int del_value = 0;
if (value) {
int i, p = strlen((char *) value);
if (srt_reverse) {
del_value = 1;
value = cl_string_reverse(value, srt_cl->corpus->charset);
}
for (i = 0; i < p; i++)
fputc((unsigned char) value[i], fd);
fputc(' ', fd);
if (del_value)
cl_free(value);
}
token += step;
}
Rprintf("\n");
}
fclose(fd);
sprintf(sort_call, "%s %s %s | gawk '{print $1}'", ExternalSortingCommand, (srt_ascending ? "" : "-r"), temporary_name);
if (SORT_DEBUG)
Rprintf("Running sort: \n\t%s\n", sort_call);
line = -1;
if ((pipe = popen(sort_call, "r")) == NULL) {
perror("Failure opening sort pipe");
cqpmessage(Error, "Can't execute external sort:\n\t%s\n"
"Disable external sorting with 'set UseExternalSorting off;'",
sort_call);
}
else {
if (! srt_cl->sortidx)
srt_cl->sortidx = (int *)cl_malloc(srt_cl->size * sizeof(int));
for (line = 0; line < srt_cl->size; line++)
srt_cl->sortidx[line] = -1;
line = 0;
while (fgets(sort_call, CL_MAX_LINE_LENGTH, pipe)) {
if (line < srt_cl->size) {
int num = atoi(sort_call);
if (num < 0 || num >= srt_cl->size) {
Rprintf("Error in externally sorted file - line number #%d out of range\n", num);
break;
}
srt_cl->sortidx[line] = num;
line++;
}
else
Rprintf("Warning: too many lines from external sort command (ignored).\n");
}
pclose(pipe);
}
}
if (unlink(temporary_name) != 0) {
perror(temporary_name);
cqpmessage(Warning, "Couldn't remove temporary file %s (ignored)\n"
"\tPlease remove the file manually.", temporary_name);
}
if (line == srt_cl->size)
return 1;
else {
cqpmessage(Error, "External sort failed (reset to default ordering).");
cl_free(srt_cl->sortidx);
return 0;
}
}
else {
perror("Can't create temporary file");
cqpmessage(Error, "Couldn't create temporary file for external sort (aborted).");
return 0;
}
}
*/
/**
* Defined if a sort cache is to be used in sorting concordance lines.
*
* The sort cache (caching the lexicon IDs of the first two tokens to be compared in each line)
* is indispensable for the internal sorting algorithm since random accesses to a compressed corpus
* are painfully slow; when sorting variable length matches such as German NPs on word forms,
* the current implementation has a hit rate of around 99%.
*/
#define USE_SORT_CACHE
/* another tweaking option would be memoization of comparisons results, requiring 2 ints + 1 bit
* per comp. for storage, probably in a hash; I have no idea how much that would improve the
* performance, esp. with a fixed hash size; other options are a hash table for identical lines
* or an incremental sort (sort on first token, group lines for which compare identical, then
* sort each group on second token, etc.); note that an incremental sort would probably enforce
* the slightly incorrect semantics of case-/diacritic-insensitive in the current implementation;
* it might be possible to reuse a custom qsort algorithm implemented for the fdist command (but
* perhaps I can just fall back on the standard qsort there);
* external sorting isn't such a bad idea after all :-) */
#ifdef USE_SORT_CACHE
/** Pointer to the sort cache @see USE_SORT_CACHE */
static int *sort_id_cache = NULL;
#endif
/**
* String comparison function used in query result sorting.
*
* This is NOT unicode compatible - it uses a maptable, which is baaaaad, mmkay.
*
* This function can be deleted once it has been checked that
* all calls to it have been replaced with cl_string_qsort_compare
*
*
static int
srt_strcmp(unsigned char *s1, unsigned char *s2, unsigned char *maptable, int reverse)
{
int l1, l2, minl, i, c1, c2, step;
unsigned char *p1, *p2;
step = (reverse) ? -1 : +1;
l1 = strlen((char *) s1);
l2 = strlen((char *) s2);
p1 = (reverse) ? s1 + l1 - 1 : s1;
p2 = (reverse) ? s2 + l2 - 1 : s2;
minl = MIN(l1, l2);
for (i = 1; i <= minl; i++) {
if (maptable) {
c1 = maptable[*p1];
c2 = maptable[*p2];
}
else {
c1 = *p1;
c2 = *p2;
}
p1 += step;
p2 += step;
if (c1 < c2)
return -1;
else if (c1 > c2)
return 1;
}
if (l1 < l2)
return -1;
else if (l1 > l2)
return 1;
else
return 0;
}
*/
/**
* Compare two matches according to current sort settings in static variables
* (qsort callback used in query result sorting).
*
* This is the primary query-hit-comparison function. It wraps cl_string_qsort_compare
* for string comparison, but does much more as well, because we are not just comparing
* individual strings but rather, potentially, whole bundles of strings from various
* different positions.
*
* @param vidx1 Pointer to the integer index of the first of the intervals to be
* compared (ie an index into an array of start/end positions).
* @param vidx2 Pointer to the integer index of the second of the intervals to be
* compared.
* @return Usual returns for qsort callbacks.
*/
static int
i2compare(const void *vidx1, const void *vidx2)
{
const int *idx1 = vidx1, *idx2 = vidx2;
int p1start, p1end; /* boundaries of sort intervals */
int p2start, p2end;
int step1, step2; /* direction of comparison (might actually be different for the two matches *ouch*) */
int pos1, pos2;
int len1, len2, minlen;
int pass, i;
int comp; /* the comparison result */
if (! EvaluationIsRunning)
return 0; /* user interrupt (Ctrl-C) => force qsort to finish quickly */
if (*idx1 == *idx2)
return 0; /* self-comparison: return equality */
/* determine start and end position of sort interval for both matches */
p1start = srt_start[*idx1];
p1end = srt_end[*idx1];
p2start = srt_start[*idx2];
p2end = srt_end[*idx2];
/* direction of comparison
(might be different if inconsistently set targets are used, but that's the user's fault) */
step1 = (p1end < p1start) ? -1 : 1;
step2 = (p2end < p2start) ? -1 : 1;
/*
* now compare the interval [p1start, p1end] with the interval [p2start, p2end],
* incrementing the cpos after each comparison by step1 and step2, respectively
* (similar to the standard comparison algorithm in cl_string_qsort_compare() above)
*/
if (SORT_DEBUG)
Rprintf("Comparing [%d,%d](%+d) with [%d,%d](%+d)\n",
p1start, p1end, step1, p2start, p2end, step2);
len1 = abs(p1end - p1start) + 1;
len2 = abs(p2end - p2start) + 1;
minlen = MIN(len1, len2);
comp = 0;
/* first pass does case-/diacritic-insensitive comparison (may be skipped), second pass does plain comparison */
for (pass = (srt_flags) ? 1 : 2 ; pass <= 2 && comp == 0 ; pass++) {
pos1 = p1start;
pos2 = p2start;
for (i = 1; (i <= minlen) && (comp == 0); i++) {
int id1, id2;
unsigned char *s1, *s2;
#ifdef USE_SORT_CACHE
/* use cache for first comparison only (to avoid repeated overwriting) */
if (i == 1) {
id1 = sort_id_cache[2*(*idx1)];
id2 = sort_id_cache[2*(*idx2)];
}
else if (i == 2) {
id1 = sort_id_cache[2*(*idx1)+1];
id2 = sort_id_cache[2*(*idx2)+1];
}
else {
id1 = cl_cpos2id(srt_attribute, pos1);
id2 = cl_cpos2id(srt_attribute, pos2);
}
#else
id1 = cl_cpos2id(srt_attribute, pos1);
id2 = cl_cpos2id(srt_attribute, pos2);
#endif
if (id1 != id2) { /* same lexicon IDs always compare equal */
s1 = (unsigned char *) cl_id2str(srt_attribute, id1);
s2 = (unsigned char *) cl_id2str(srt_attribute, id2);
if (pass == 1)
/* compare normalised strings in first pass (srt_flags are set in this case) */
comp = cl_string_qsort_compare((char *)s1, (char *)s2, srt_cl->corpus->charset, srt_flags, srt_reverse);
/* old version: comp = srt_strcmp(s1, s2, srt_maptable, srt_reverse); */
else
/* in pass 2, compare without flags. */
comp = cl_string_qsort_compare((char *)s1, (char *)s2, srt_cl->corpus->charset, 0, srt_reverse);
/* old version: comp = srt_strcmp(s1, s2, NULL, srt_reverse); */
}
pos1 += step1;
pos2 += step2;
}
if (comp == 0) { /* intervals compared equal up to the length of the shorter one -> compare lengths */
if (len1 > len2)
comp = 1;
else if (len1 < len2)
comp = -1;
}
/* may try without %cd flags to break ties, but only if that variable is set */
if (! break_ties)
break;
} /* endfor each of the two passes */
if ((comp == 0) && break_ties) {
if (idx1 > idx2) /* break ties in order of original matchlist */
comp = 1;
else
comp = -1;
}
if (! srt_ascending) /* adjust sort order for descending sort */
comp = -comp;
return comp;
}
/** Compares two groups of equivalent matches by group sizes (descending), breaking ties through i2compare. */
static int
group2compare(const void *vidx1, const void *vidx2)
{
const int *idx1 = vidx1, *idx2 = vidx2;
int s1, s2;
if (! EvaluationIsRunning)
return 0;
if (*idx1 == *idx2)
return 0;
s1 = group_size[*idx1];
s2 = group_size[*idx2];
if (s1 > s2) /* descending sort order */
return -1;
else if (s1 < s2)
return 1;
else
return i2compare(&(current_sortidx[group_first[*idx1]]), &(current_sortidx[group_first[*idx2]]));
}
/* simulate Perl's spaceship operator A <=> B */
#define spaceship(A,B) ((A) > (B)) ? 1 : ((A) < (B)) ? -1 : 0
/**
* Sorts hits in random order by comparing random numbers in the vector random_sort_keys[],
* breaking ties by start and end positions of matches (from *srt_cl) in order to ensure stable sorting.
*
* This is another qsort callback function.
*/
static int
random_compare(const void *vidx1, const void *vidx2)
{
int idx1 = *((int *) vidx1), idx2 = *((int *) vidx2);
int result = spaceship(random_sort_keys[idx1], random_sort_keys[idx2]);
if (result == 0)
result = spaceship(srt_cl->range[idx1].start, srt_cl->range[idx2].start);
if (result == 0)
result = -spaceship(srt_cl->range[idx1].end, srt_cl->range[idx2].end);
return result;
}
/**
* Sorts a query result in random order.
*
* If seed > 0, a reproducible and stable ordering is generated
* based on the start and end corpus positions of matches
* (i.e. two given matches will always be sorted in the same
* order).
*
* @param cl Corpus-list object representing the query to sort.
* @param seed Seed for the randomiser; should ideally be a prime number
* (2^31 is a particularly bad choice); if it is 0, then
* the internal RNG's standard random order is used.
*/
int
SortSubcorpusRandomize(CorpusList *cl, int seed)
{
int n_matches, i, ok;
if (cl == NULL) {
cqpmessage(Error, "No query result specified for sorting.");
return 0;
}
if (cl->size <= 0) {
cqpmessage(Info, "Nothing to sort (ignored),");
return 0;
}
if (!access_corpus(cl)) {
cqpmessage(Error, "Can't access query result %s (aborted).", cl->name);
return 0;
}
srt_cl = cl; /* has been validated, so it can safely be used by the callback function */
n_matches = cl->size;
/* initialise random sort keys (using supplied seed) */
if (random_sort_keys != NULL)
/* in case it's still allocated from last call... */
cl_free(random_sort_keys);
random_sort_keys = (unsigned int *) cl_malloc(n_matches * sizeof(unsigned int));
if (seed) {
/* stable randomized order (calculated from match range by RNG transformation) */
for (i = 0; i < n_matches; i++) {
/* completely arbitrary */
cl_set_rng_state(cl->range[i].start + seed,
(seed * (cl->range[i].end - cl->range[i].start)) ^ cl->range[i].end
);
/* apply RNG transformation 3 times to destroy systematic patterns in initialisation */
cl_random();
cl_random();
random_sort_keys[i] = cl_random();
}
}
else {
/* standard randomized order (using internal RNG) */
for (i = 0; i < n_matches; i++)
random_sort_keys[i] = cl_random();
}
/* allocate and initialise sorted index */
if (cl->sortidx == NULL)
cl->sortidx = (int *) cl_malloc(n_matches * sizeof(int));
for (i = 0; i < n_matches; i++)
cl->sortidx[i] = i;
EvaluationIsRunning = 1;
ok = 1;
qsort(cl->sortidx, cl->size, sizeof(int), random_compare);
if (! EvaluationIsRunning) {
cqpmessage(Warning, "Sort/count operation aborted by user (reset to default ordering).");
if (which_app == cqp)
install_signal_handler();
cl_free(cl->sortidx);
ok = 0;
}
EvaluationIsRunning = 0;
/* clean up and return status */
cl_free(random_sort_keys);
touch_corpus(cl);
return ok;
}
/**
* Sort the (query) subcorpus specified by cl, or count frequencies of matching strings.
*
* (Note that frequency counting and query result sorting are done via the same sorting
* algorithm.)
*
* If the sort was not performed successfully, the sort index is reset to the default
* sort order, and the function returns false.
*
* @param cl Subcorpus designating the query to sort.
* @param sc A sort clause. sc = NULL resets the sort index to the default sort
* order (i.e. sorted by corpus position).
* @param count_mode Boolean: run the function in count frequency mode?
* @param redir Redir object for where the output of string-counting is to be
* displayed.
* @return Boolean: true for successful sort, false for unsuccessful.
*/
int
SortSubcorpus(CorpusList *cl, SortClause sc, int count_mode, struct Redir *redir)
{
int i, k, ok;
char *srt_att_name;
if (cl == NULL) {
cqpmessage(Error, "No query result specified for sorting.");
return 0;
}
if (cl->size <= 0) {
cqpmessage(Info, "Nothing to sort (ignored),");
return 0;
}
if (!access_corpus(cl)) {
cqpmessage(Error, "Can't access query result %s (aborted).", cl->name);
return 0;
}
if (sc == NULL) { /* sort by corpus position, i.e. delete sortidx */
if (count_mode) {
cqpmessage(Error, "Count what? (e.g. 'by word')");
return 0;
}
else {
cl_free(cl->sortidx);
touch_corpus(cl);
return 1;
}
}
/* set up static attributes for sort callback functions */
srt_att_name = (sc->attribute_name) ? sc->attribute_name : DEFAULT_ATT_NAME;
srt_attribute = find_attribute(cl->corpus, srt_att_name, ATT_POS, NULL);
if (srt_attribute == NULL) {
cqpmessage(Error, "Can't find %s attribute for sorting (aborted).", srt_att_name);
return 0;
}
text_size = cl_max_cpos(srt_attribute);
srt_cl = cl;
srt_ascending = sc->sort_ascending;
srt_reverse = sc->sort_reverse;
break_ties = 1;
srt_flags = sc->flags;
/* test whether anchors for sort interval are defined */
srt_anchor1 = sc->anchor1;
srt_offset1 = sc->offset1;
/* this test will be simplified and made more robust when we have a full match table implementation */
if ((srt_anchor1 == KeywordField) && (cl->keywords == NULL)) {
cqpmessage(Error, "No keyword anchors defined (aborted).");
return 0;
}
if ((srt_anchor1 == TargetField) && (cl->targets == NULL)) {
cqpmessage(Error, "No target anchors defined (aborted).");
return 0;
}
assert(srt_anchor1 != NoField);
srt_anchor2 = sc->anchor2;
srt_offset2 = sc->offset2;
if ((srt_anchor2 == KeywordField) && (cl->keywords == NULL)) {
cqpmessage(Error, "No keyword anchors defined (aborted).");
return 0;
}
if ((srt_anchor2 == TargetField) && (cl->targets == NULL)) {
cqpmessage(Error, "No target anchors defined (aborted).");
return 0;
}
assert(srt_anchor2 != NoField);
ok = 1;
if (UseExternalSorting && !insecure && !count_mode) {
/* ok = SortExternally(); */
}
else {
/* precompute tables for start and end position of sort interval */
srt_start = cl_malloc(cl->size * sizeof(int));
srt_end = cl_malloc(cl->size * sizeof(int));
switch (srt_anchor1) {
case MatchField:
for (i = 0; i < cl->size; i++)
srt_start[i] = srt_cl->range[i].start + srt_offset1;
break;
case MatchEndField:
for (i = 0; i < cl->size; i++)
srt_start[i] = srt_cl->range[i].end + srt_offset1;
break;
case KeywordField:
for (i = 0; i < cl->size; i++)
srt_start[i] = srt_cl->keywords[i] + srt_offset1;
break;
case TargetField:
for (i = 0; i < cl->size; i++)
srt_start[i] = srt_cl->targets[i] + srt_offset1;
break;
default:
assert(0 && "Oopsie -- illegal first anchor in SortSubcorpus()");
break;
}
for (i = 0; i < cl->size; i++) {
if (srt_start[i] < 0)
srt_start[i] = 0;
else if (srt_start[i] >= text_size)
srt_start[i] = text_size - 1;
}
switch (srt_anchor2) {
case MatchField:
for (i = 0; i < cl->size; i++)
srt_end[i] = srt_cl->range[i].start + srt_offset2;
break;
case MatchEndField:
for (i = 0; i < cl->size; i++)
srt_end[i] = srt_cl->range[i].end + srt_offset2;
break;
case KeywordField:
for (i = 0; i < cl->size; i++)
srt_end[i] = srt_cl->keywords[i] + srt_offset2;
break;
case TargetField:
for (i = 0; i < cl->size; i++)
srt_end[i] = srt_cl->targets[i] + srt_offset2;
break;
default:
assert(0 && "Critical error -- illegal first anchor in SortSubcorpus()");
break;
}
for (i = 0; i < cl->size; i++) {
if (srt_end[i] < 0)
srt_end[i] = 0;
else if (srt_end[i] >= text_size)
srt_end[i] = text_size - 1;
}
/* ok, so now the positions have been moved from the srt_cl to the
* global sorting-variables. */
/* swap start and end positions in reverse sort */
if (srt_reverse) {
int *temp;
temp = srt_start; srt_start = srt_end; srt_end = temp;
}
/* allocate and initialise sorted index */
if (cl->sortidx == NULL)
cl->sortidx = (int *)cl_malloc(cl->size * sizeof(int));
for (i = 0; i < cl->size; i++)
cl->sortidx[i] = i;
#ifdef USE_SORT_CACHE
/* load up the sort cache.... */
sort_id_cache = (int *)cl_malloc(cl->size * 2 * sizeof(int));
for (i = 0; i < cl->size; i++) {
int cpos1 = srt_start[i];
int cpos2 = srt_end[i];
int len = abs(cpos2 - cpos1) + 1;
int step = (cpos2 >= cpos1) ? 1 : -1;
sort_id_cache[2*i] = cl_cpos2id(srt_attribute, cpos1);
if (len > 1)
sort_id_cache[2*i+1] = cl_cpos2id(srt_attribute, cpos1 + step);
else
sort_id_cache[2*i+1] = 0;
}
#endif
/* the business end... the sorting happens here! */
EvaluationIsRunning = 1;
qsort(cl->sortidx, cl->size, sizeof(int), i2compare);
if (! EvaluationIsRunning) {
cqpmessage(Warning, "Sort/count operation aborted by user (reset to default ordering).");
if (which_app == cqp) install_signal_handler();
cl_free(cl->sortidx);
ok = 0;
}
EvaluationIsRunning = 0;
/* note that, unless we are in count mode, this is more or less the end of it.... */
/* in count mode, group identical (or equivalent) sort strings, then sort by group sizes */
if (ok && count_mode) {
int *groupidx = NULL;
int n_groups, first;
current_sortidx = cl->sortidx;
group_first = cl_malloc(cl->size * sizeof(int)); /* worst case: cl->size groups with f = 1 */
group_size = cl_malloc(cl->size * sizeof(int));
break_ties = 0; /* don't break ties for grouping */
n_groups = 0;
first = group_first[n_groups] = 0;
EvaluationIsRunning = 1;
/* collect equivalent matches into groups */
for (i = 0; (i < cl->size) && EvaluationIsRunning; i++) {
if (i > 0) {
if (i2compare(current_sortidx + first, current_sortidx + i)) {
group_size[n_groups] = i - first;
first = group_first[++n_groups] = i;
}
}
}
group_size[n_groups++] = i - first;
/* sort groups by their size (= frequency of sort string) in descending order */
if (EvaluationIsRunning) {
groupidx = cl_malloc(n_groups * sizeof(int));
for (i = 0; i < n_groups; i++) groupidx[i] = i;
qsort(groupidx, n_groups, sizeof(int), group2compare);
}
if (! EvaluationIsRunning) {
cqpmessage(Warning, "Count operation aborted by user.");
if (which_app == cqp) install_signal_handler();
ok = 0;
}
EvaluationIsRunning = 0;
/* if successful, display groups with their frequencies */
if (open_stream(redir, cl->corpus->charset)) {
for (i = 0; (i < n_groups) && !cl_broken_pipe; i++) {
int first = group_first[groupidx[i]];
int size = group_size[groupidx[i]];
if (size >= count_mode) {
int start = srt_start[current_sortidx[first]]; /* cpos range of sort string */
int end = srt_end[current_sortidx[first]];
int len = abs(end - start) + 1;
int step = (end >= start) ? 1 : -1;
Rprintf("%d\t", size);
if (! pretty_print) /* without pretty-printing: show first match in second column, for automatic processing */
Rprintf("%d\t", first);
for (k = 0; k < len; k++) {
int cpos = start + step * k;
char *token_readonly = cl_cpos2str(srt_attribute, cpos);
/* normalise token if %cd was given */
char *token = cl_string_canonical(token_readonly, cl->corpus->charset, sc->flags, CL_STRING_CANONICAL_STRDUP);
if (srt_reverse) {
/* reverse the token */
char *temp = cl_string_reverse(token, cl->corpus->charset);
cl_free(token);
token = temp;
}
if (k > 0)
Rprintf(" ");
Rprintf("%s", token);
cl_free(token);
}
if (pretty_print) { /* with pretty-printing: append range of matches belonging to group (in sorted corpus) */
if (size > 1)
Rprintf(" [#%d-#%d]", first, first + size - 1);
else
Rprintf(" [#%d]", first);
}
Rprintf("\n");
fflush(redir->stream);
}
}
close_stream(redir);
}
if (groupidx)
cl_free(groupidx);
cl_free(group_first);
cl_free(group_size);
} /* endif "we are in count mode!" */
#ifdef USE_SORT_CACHE
cl_free(sort_id_cache);
#endif
cl_free(srt_start);
cl_free(srt_end);
} /* end of "if not external sorting" */
touch_corpus(cl);
return ok;
}
/**
* Frees a SortClause object.
*/
void
FreeSortClause(SortClause sc)
{
if (sc) {
cl_free(sc->attribute_name);
cl_free(sc);
}
}
|
myoKun345/RcppCWB
|
src/cwb/cl/ngram-hash.c
|
<gh_stars>0
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
#include "globals.h"
#include "macros.h"
#include "lexhash.h"
#include "ngram-hash.h"
#include <math.h>
void Rprintf(const char *, ...);
/** Defines the default number of buckets in an n-gram hash. */
#define DEFAULT_NR_OF_BUCKETS 250000
/** Default parameters for auto-growing the table of buckets (@see cl_ngram_hash_auto_grow_fillrate for details). */
#define DEFAULT_FILLRATE_LIMIT(n) 5.0
#define DEFAULT_FILLRATE_TARGET(n) 1.0 /**< keep memory overhead for bucket table below 50% */
/* -- fill rate limits could also be adapted to n-gram size, but this doesn't seem to improve speed much --
#define DEFAULT_FILLRATE_LIMIT(n) ((n >=5) ? 3.0 : 5.0)
#define DEFAULT_FILLRATE_TARGET(n) ((n >= 5) ? 0.5 : 1.0)
*/
/** Maximum number of buckets n-gram hash will try to allocate when auto-growing. */
#define MAX_BUCKETS 1000000007 /**< 1 billion (incremented to next prime number) */
/** Maximum number of entries that can be stored in the n-gram hash */
#define MAX_ENTRIES 2147483647 /**< 2^31 - 1 */
/*
* basic utility functions
*/
/* find_prime() has been imported from "lexhash.h" */
/** Computes 32bit hash value for n-gram */
unsigned int
hash_ngram(int N, int *tuple)
{
unsigned int result = 5381; /* seed value from DJB2, seems slightly better than original seed 0 */
unsigned char *buffer = (unsigned char *)tuple;
int i;
/* hash function is designed for byte sequence and has poor distribution if applied directly to ints */
for(i = 0 ; i < N * sizeof(int); i++)
result = (result * 33) ^ (result >> 27) ^ buffer[i];
return result;
}
/** TODO: consider alternative hash functions (see cl/lexhash.h) */
/*
* cl_ngram_hash / cl_ngram_hash_entry object definition
*/
/* cl_ngram_hash_entry is in <cl.h> */
/* typedef struct _cl_ngram_hash *cl_ngram_hash; in <cl.h> */
/**
* Underlying structure for the cl_ngram_hash object.
*
* A cl_ngram_hash contains a number of buckets. Each bucket is
* a linked-list of cl_ngram_hash_entry objects.
*
*/
struct _cl_ngram_hash {
cl_ngram_hash_entry *table; /**< table of buckets; each "bucket" is a pointer to the list of entries that make up that bucket */
unsigned int buckets; /**< number of buckets in the hash table */
int N; /**< n-gram size */
int entries; /**< current number of entries in this hash */
int auto_grow; /**< boolean: whether to expand this hash automatically; true by default */
double fillrate_limit; /**< fillrate limit that triggers expansion of bucket table (with auto_grow) */
double fillrate_target; /**< target fillrate after expansion of bucket table (with auto_grow) */
int iter_bucket; /**< bucket currently processed by the single iterator of the hash table */
cl_ngram_hash_entry iter_point; /**< next entry to be returned by the iterator (NULL -> go to next bucket) */
};
/*
* cl_ngram_hash methods
*/
/**
* Creates a new cl_ngram_hash object.
*
* @param N N-gram size
* @param buckets The number of buckets in the newly-created cl_ngram_hash;
* set to 0 to use the default number of buckets.
* @return The new cl_ngram_hash.
*/
cl_ngram_hash
cl_new_ngram_hash(int N, int buckets)
{
cl_ngram_hash hash;
assert(N >= 1 && "cl_new_ngram_hash(): invalid N-gram size");
if (buckets <= 0)
buckets = DEFAULT_NR_OF_BUCKETS;
hash = (cl_ngram_hash) cl_malloc(sizeof(struct _cl_ngram_hash));
hash->N = N;
hash->buckets = find_prime(buckets);
hash->table = cl_calloc(hash->buckets, sizeof(cl_ngram_hash_entry));
hash->entries = 0;
hash->auto_grow = 1;
hash->fillrate_limit = DEFAULT_FILLRATE_LIMIT(N);
hash->fillrate_target = DEFAULT_FILLRATE_TARGET(N);
hash->iter_bucket = -1;
hash->iter_point = NULL;
return hash;
}
/**
* Deletes a cl_ngram_hash object.
*
* This deletes all the entries in all the buckets in the ngram_hash,
* plus the cl_ngram_hash itself.
*
* @param hash The cl_ngram_hash to delete.
*/
void
cl_delete_ngram_hash(cl_ngram_hash hash)
{
int i;
cl_ngram_hash_entry entry;
if (hash != NULL && hash->table != NULL) {
for (i = 0; i < hash->buckets; i++) {
entry = hash->table[i];
while (entry != NULL) {
/* temp = entry; */
entry = entry->next;
cl_free(entry);
}
}
}
cl_free(hash->table);
cl_free(hash);
}
/**
* Turns a cl_ngram_hash's ability to auto-grow on or off.
*
* When this setting is switched on, the ngram_hash will grow
* automatically to avoid performance degradation.
*
* Note the default value for this setting is SWITCHED ON.
*
* @see cl_ngram_hash_auto_grow_fillrate, cl_ngram_hash_check_grow
* @param hash The hash that will be affected.
* @param flag New value for autogrow setting: boolean where
* true is on and false is off.
*/
void
cl_ngram_hash_auto_grow(cl_ngram_hash hash, int flag)
{
if (hash != NULL)
hash->auto_grow = flag;
}
/**
* Configure auto-grow parameters.
*
* These settings are only relevant if auto-growing is enabled.
*
* The decision to expand the bucket table of a ngram_hash is based
* on its fill rate, i.e. the average number of entries in each
* bucket. Under normal circumstances, this value corresponds to
* the average number of comparisons required to insert a new
* entry into the hash (locating an existing value should require
* roughly half as many comparisons).
*
* Auto-growing is triggered if the fill rate exceeds a specified
* limit. The new number of buckets is chosen so that the fill
* rate after expansion corresponds to the specified target value.
*
* The two fill rate parameters represent a trade-off between memory
* overhead (8 bytes for each bucket) and performance (average number
* of entries that have been checked for each hash access), which
* depends crucially on the value of N (i.e. n-gram size).
*
* For N=1, a bucket table with low fill rate incurs a substantial
* memory overhead, which may even exceed the storage required for the
* entries themselves. For large N, the relative memory overhead is
* much smaller, while checking the list of entries in a bucket becomes
* more expensive (N integer comparisons for each item).
*
* Note that the ratio limit / target determines how often the bucket
* table has to be reallocated; it should not be smaller than 4.0.
*
* A reasonable values for the fill rate limit seems to be around 5.0;
* if speed is crucial, N is relatively large, and memory footprint
* isn't a concern, smaller values down to 2.0 might be chosen.
* The target fill rate should not be set too low for small N.
* If N=1, a target fill rate of 0.5 results in 100% memory overhead
* after expansion of the bucket table (16 bytes per entry vs. 8 bytes
* each for twice as many buckets as there are entries).
*
* When working on very large data sets, it is recommended to disable
* auto-grow and initialise the n-gram hash with a sufficiently large
* number of buckets.
*
* @see cl_ngram_hash_auto_grow, cl_ngram_hash_check_grow
* @param hash The hash that will be affected.
* @param limit Fill rate limit, which triggers expansion of the n-gram hash
* @param target Target fill rate after expansion (determines new number of buckets)
*/
void
cl_ngram_hash_auto_grow_fillrate(cl_ngram_hash hash, double limit, double target)
{
if (hash != NULL) {
/* set parameters with basic sanity checks */
hash->fillrate_target = (target > 0.01) ? target : 0.01;
hash->fillrate_limit = (limit > 2 * hash->fillrate_target) ? limit : 2 * hash->fillrate_target;
}
}
/**
* Grows a ngram_hash table, increasing the number of buckets, if necessary.
*
* This functions is called after inserting a new entry into the n-gram hash.
* If checks whether the current fill rate exceeds the specified limit.
* If this is the case, and auto_grow is enabled, then the hash is expanded
* by increasing the number of buckets, such that the new average fill rate
* corresponds to the specified target value. This gives the
* hash better performance and makes it capable of absorbing more keys.
*
* If the bucket table would be expanded to more than MAX_BUCKETS entries,
* auto-grow is automatically disabled for this ngram_hash.
*
* Note: this function also implements the hashing algorithm and must be
* consistent with cl_ngram_hash_find_i().
*
* Usage: expanded = cl_ngram_hash_check_grow(cl_ngram_hash hash);
*
* This is a non-exported function.
*
* @see cl_ngram_hash_auto_grow, cl_ngram_hash_auto_grow_fillrate
* @param hash The cl_ngram_hash to autogrow.
* @return Always 0.
*/
int
cl_ngram_hash_check_grow(cl_ngram_hash hash)
{
double fill_rate, target_size;
cl_ngram_hash temp;
cl_ngram_hash_entry entry, next;
int idx, offset, old_buckets, new_buckets, N;
old_buckets = hash->buckets;
fill_rate = ((double) hash->entries) / old_buckets;
if (hash->auto_grow && (fill_rate > hash->fillrate_limit)) {
/* auto-grow is triggered */
target_size = floor(((double) hash->entries) / hash->fillrate_target);
if (target_size > MAX_BUCKETS) {
if (cl_debug) {
Rprintf("[n-gram hash autogrow: size limit %f exceeded by new target size %f, auto-growing will be disabled]\n",
(double) MAX_BUCKETS, target_size);
}
hash->auto_grow = 0; /* disable auto-grow to avoid further unnecessary attempts */
/* grow ngram_hash to maximum size, but not if this would extend bucket vector by less than 2x (to avoid large reallocation for little benefit) */
if (old_buckets > target_size / 2.0) {
return 0;
}
else {
target_size = MAX_BUCKETS;
}
}
/* now grow bucket table from old_buckets entries to new_buckets entries */
new_buckets = (int) target_size;
old_buckets = hash->buckets;
if (cl_debug) {
Rprintf("[n-gram hash autogrow: triggered by fill rate = %3.1f (%d/%d)]\n",
fill_rate, hash->entries, old_buckets);
if (cl_debug >= 2)
cl_ngram_hash_print_stats(hash, 12);
}
N = hash->N;
temp = cl_new_ngram_hash(N, new_buckets); /* create new hash with target fill rate */
new_buckets = temp->buckets; /* the actual number of entries (next prime number) */
/* move all entries from hash to the appropriate bucket in temp */
for (idx = 0; idx < old_buckets; idx++) {
entry = hash->table[idx];
while (entry != NULL) {
next = entry->next; /* remember pointer to next entry */
offset = hash_ngram(N, entry->ngram) % new_buckets;
entry->next = temp->table[offset]; /* insert entry into its bucket in temp (most buckets should contain only 1 entry, as long as hash->fillrate_target is less than 1) */
temp->table[offset] = entry;
temp->entries++;
entry = next; /* continue while loop */
}
}
assert((temp->entries == hash->entries) && "ngram-hash.c: inconsistency during hash expansion");
cl_free(hash->table); /* old hash table should be empty and can be deallocated */
hash->table = temp->table; /* update hash from temp (copy hash table and its size) */
hash->buckets = temp->buckets;
cl_free(temp); /* we can simply deallocate temp now, having stolen its hash table */
if (cl_debug) {
fill_rate = ((double) hash->entries) / hash->buckets;
Rprintf("[n-gram hash autogrow: new fill rate = %3.1f (%d/%d)]\n",
fill_rate, hash->entries, hash->buckets);
}
return 1;
}
return 0;
}
/**
* Finds the entry corresponding to a particular n-gram in a cl_ngram_hash.
*
* This function is the same as cl_ngram_hash_find(), but *ret_offset is set to
* the hashtable offset computed for token (i.e. the index of the bucket within
* the hashtable), unless *ret_offset == NULL.
*
* Note that this function hides the hashing algorithm details from the
* rest of the n-gram hash implementation (except cl_ngram_hash_check_grow, which
* re-implements the hashing algorithm for performance reasons).
*
* Usage: entry = cl_ngram_hash_find_i(cl_ngram_hash hash, char *token, unsigned int *ret_offset);
*
* This is a non-exported function.
*
* @param hash The hash to search.
* @param ngram The ngram to look for.
* @param ret_offset This integer address will be filled with the token's
* hashtable offset (can be NULL, in which case, ignored).
* @return The entry that is found (or NULL if the string is not
* in the hash).
*/
cl_ngram_hash_entry
cl_ngram_hash_find_i(cl_ngram_hash hash, int *ngram, unsigned int *ret_offset)
{
unsigned int offset;
int N;
cl_ngram_hash_entry entry;
assert((hash != NULL && hash->table != NULL && hash->buckets > 0) && "cl_ngram_hash object was not properly initialised");
N = hash->N;
/* get the offset of the bucket to look in by computing the hash of the string */
offset = hash_ngram(N, ngram) % hash->buckets;
if (ret_offset != NULL)
*ret_offset = offset;
/* check all entries in this bucket against the specified key */
entry = hash->table[offset];
while (entry != NULL && memcmp(entry->ngram, ngram, N * sizeof(int)) != 0)
entry = entry->next;
return entry;
}
/**
* Finds the entry corresponding to a particular n-gram within a cl_ngram_hash.
*
* This function is basically a wrapper around the internal function cl_ngram_hash_find_i.
*
* @see cl_ngram_hash_find_i
* @param hash The hash to search.
* @param n-gram The n-gram to look for.
* @return The entry that is found (or NULL if the n-gram is not
* in the hash).
*/
cl_ngram_hash_entry
cl_ngram_hash_find(cl_ngram_hash hash, int *ngram)
{
return cl_ngram_hash_find_i(hash, ngram, NULL);
}
/**
* Adds an n-gram to a cl_ngram_hash table.
*
* If the n-gram is already in the hash, its frequency count
* is increased by the specified value f.
*
* Otherwise, a new entry is created and its frequency count
* is set to f. The n-gram is embedded in the new hash entry,
* so the original array does not need to be kept in memory.
*
* @param hash The hash table to add to.
* @param ngram The n-gram to add.
* @param f Frequency count of the n-gram.
* @return A pointer to a (new or existing) entry
*/
cl_ngram_hash_entry
cl_ngram_hash_add(cl_ngram_hash hash, int *ngram, unsigned int f)
{
cl_ngram_hash_entry entry, insert_point;
unsigned int offset; /* this will be set to the index of the bucket this token should go in
by the call to cl_ngram_hash_find_i */
int N;
entry = cl_ngram_hash_find_i(hash, ngram, &offset);
N = hash->N;
if (entry != NULL) {
/* token already in hash -> increment frequency count */
entry->freq += f;
}
else {
/* token not in hash -> add new entry for this token */
assert((hash->entries < MAX_ENTRIES) && "ngram-hash.c: maximum capacity of n-gram hash exceeded -- program abort");
/* allocate enough space for n-gram appended to the struct */
entry = (cl_ngram_hash_entry) cl_malloc(sizeof(struct _cl_ngram_hash_entry) + (N - 1) * sizeof(int));
memcpy(entry->ngram, ngram, N * sizeof(int)); /* embed copy of n-gram in struct */
entry->freq = f;
entry->next = NULL;
/* insert entry into its bucket in the hash table */
insert_point = hash->table[offset];
if (insert_point == NULL) {
hash->table[offset] = entry; /* only entry in this bucket so far */
}
else {
/* always insert a new entry as the last entry in its bucket (because of Zipf's Law:
* frequent lexemes tend to occur early in the corpus and should be first in their buckets for faster access) */
while (insert_point->next != NULL)
insert_point = insert_point->next;
insert_point->next = entry;
}
hash->entries++;
/* check whether hash needs to auto-grow */
if (hash->auto_grow && hash->entries > (hash->fillrate_limit * hash->buckets))
cl_ngram_hash_check_grow(hash);
}
return entry;
}
/**
* Gets the frequency of a particular n-gram within a cl_ngram_hash.
*
* @param hash The hash to look in.
* @param ngram The ngram to look for.
* @return The frequency of that n-gram, or 0 if it is not in the hash
*/
int
cl_ngram_hash_freq(cl_ngram_hash hash, int *ngram)
{
cl_ngram_hash_entry entry;
entry = cl_ngram_hash_find_i(hash, ngram, NULL);
return (entry != NULL) ? entry->freq : 0;
}
/**
* Deletes an n-gram from a hash.
*
* The entry corresponding to the specified n-gram is
* removed from the cl_ngram_hash. If the n-gram is not in the
* hash to begin with, no action is taken.
*
* @param hash The hash to alter.
* @param ngram The n-gram to remove.
* @return The frequency of the deleted entry (0 if not found).
*/
int
cl_ngram_hash_del(cl_ngram_hash hash, int *ngram)
{
cl_ngram_hash_entry entry, previous;
unsigned int offset, f;
entry = cl_ngram_hash_find_i(hash, ngram, &offset);
if (entry == NULL) {
return 0; /* not in n-gram hash */
}
else {
f = entry->freq;
if (hash->table[offset] == entry) {
hash->table[offset] = entry->next;
}
else {
previous = hash->table[offset];
while (previous->next != entry)
previous = previous->next;
previous->next = entry->next;
}
cl_free(entry);
hash->entries--;
return f;
}
}
/**
* Gets the number of distinct n-grams stored in a cl_ngram_hash.
*
* This returns the total number of entries in all the
* buckets in the whole hash table.
*
* @param hash The hash to size up.
*/
int
cl_ngram_hash_size(cl_ngram_hash hash)
{
return (hash != NULL) ? hash->entries : 0;
}
/**
* Get an array of all entries in an n-gram hash.
*
* This function returns a newly allocated array of cl_ngram_hash_entry
* pointers enumerating all entries of the hash in an unspecified order.
*
* @param hash The n-gram hash to operate on.
* @param ret_size If not NULL, the number of entries in the returned
* array will be stored in this location.
*/
cl_ngram_hash_entry *
cl_ngram_hash_get_entries(cl_ngram_hash hash, int *ret_size)
{
cl_ngram_hash_entry *result, entry;
int size, point;
unsigned int offset;
assert((hash != NULL && hash->table != NULL && hash->buckets > 0) && "cl_ngram_hash object was not properly initialised");
/* allocate memory for enumeration of entries */
size = hash->entries;
result = cl_malloc(size * sizeof(cl_ngram_hash_entry));
if (ret_size != NULL)
*ret_size = size;
/* traverse hash and insert all entries into the array */
point = 0;
for (offset = 0; offset < hash->buckets; offset++) {
entry = hash->table[offset];
while (entry != NULL) {
assert((point < size) && "ngram-hash.c: major internal inconsistency");
result[point++] = entry;
entry = entry->next;
}
}
assert((point == size) && "ngram-hash.c: major internal inconsistency");
return result;
}
/**
* Iterate over all entries in an n-gram hash.
*
* Note that there is only a single iterator for each cl_ngram_hash object,
* so different parts of the application code must not try to iterate through
* the hash at the same time.
*
* This function resets the iterator to the start of the hash.
*
* @param hash The n-gram hash to iterate over.
*/
void
cl_ngram_hash_iterator_reset(cl_ngram_hash hash)
{
assert((hash != NULL && hash->table != NULL && hash->buckets > 0) && "cl_ngram_hash object was not properly initialised");
hash->iter_bucket = -1;
hash->iter_point = NULL;
}
/**
* Iterate over all entries in an n-gram hash.
*
* Note that there is only a single iterator for each cl_ngram_hash object,
* so different parts of the application code must not try to iterate through
* the hash at the same time.
*
* This function returns the next entry from the hash, or NULL if there are
* no more entries. Keep in mind that the hash is traversed in an unspecified order.
*
* @param hash The n-gram hash to iterate over.
*/
cl_ngram_hash_entry
cl_ngram_hash_iterator_next(cl_ngram_hash hash)
{
cl_ngram_hash_entry point;
point = hash->iter_point;
while (point == NULL) {
hash->iter_bucket++;
if (hash->iter_bucket >= hash->buckets)
return NULL; /* we've reached the end of the hash */
point = hash->table[hash->iter_bucket];
}
hash->iter_point = point->next;
return point;
}
/**
* Compute statistics on bucket fill rates (for debugging and optimization).
*
* This function returns an allocated integer array of length max_n + 1, whose
* i-th entry specifies the number of buckets containing i keys. For i == 0, this
* is the number of empty buckets. The last entry (i == max_n) is the cumulative
* number of buckets containing i or more entries.
*
* @param hash The n-gram hash.
* @param max_n Count buckets with up to max_n entries.
*/
int *
cl_ngram_hash_stats(cl_ngram_hash hash, int max_n)
{
int *stats;
int i, n;
cl_ngram_hash_entry point;
assert(max_n > 0);
assert((hash != NULL && hash->table != NULL && hash->buckets > 0) && "cl_ngram_hash object was not properly initialised");
stats = cl_calloc(max_n + 1, sizeof(int));
for (i = 0; i < hash->buckets; i++) {
point = hash->table[i];
n = 0;
while (point) {
point = point->next;
n++;
}
if (n >= max_n)
stats[max_n]++;
else
stats[n]++;
}
return stats;
}
/**
* Display statistics on bucket fill rates (for debugging and optimization).
*
* This function prints a table showing the distribution of bucket sizes, i.e.
* how many buckets contain a given number of keys. The table will be printed
* to STDERR, as all debugging output in CWB.
*
* @param hash The n-gram hash.
* @param max_n Count buckets with up to max_n entries.
*/
void
cl_ngram_hash_print_stats(cl_ngram_hash hash, int max_n)
{
int *stats = cl_ngram_hash_stats(hash, max_n); /* also performs sanity checks */
double rate, p;
int i;
rate = ((double) hash->entries) / hash->buckets;
Rprintf("N-gram hash fill rate: %5.2f (%d entries in %d buckets)\n",
rate, hash->entries, hash->buckets);
Rprintf("# entries: ");
for (i = 0; i <= max_n; i++)
Rprintf("%8d", i);
Rprintf("+\n");
Rprintf("bucket cnt:");
for (i = 0; i <= max_n; i++)
Rprintf("%8d", stats[i]);
Rprintf("\n");
Rprintf("expected: ");
p = exp(-rate); /* expected number of entries for ideal hash function (Poisson distribution) */
for (i = 0; i < max_n; i++) {
Rprintf("%8.0f", p * hash->buckets);
p *= rate / (i + 1);
}
Rprintf("\n");
cl_free(stats);
}
|
myoKun345/RcppCWB
|
src/cwb/cqp/hash.c
|
<filename>src/cwb/cqp/hash.c
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
/*
int
is_prime(int n) {
int i;
for(i = 2; i*i <= n; i++)
if ((n % i) == 0)
return 0;
return 1;
}
*/
/*
int
find_prime(int n) {
for( ; n > 0 ; n++)
if (is_prime(n))
return n;
return 0;
}
*/
/*
unsigned int
hash_string(char *string) {
unsigned char *s = (unsigned char *)string;
unsigned int result = 0;
for( ; *s; s++)
result = (result * 33 ) ^ (result >> 27) ^ *s;
return result;
}
*/
unsigned int
hash_macro(char *macro_name, unsigned int args) {
unsigned char *name = (unsigned char *)macro_name;
unsigned int result = args;
for( ; *name; name++)
result = (result * 33 ) ^ (result >> 27) ^ *name;
return result;
}
|
myoKun345/RcppCWB
|
src/cwb/cl/cdaccess.c
|
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
#include <stdarg.h>
#include <math.h>
#include <ctype.h>
#include <sys/types.h>
#include <errno.h>
#include "globals.h"
#include "endian2.h"
#include "macros.h"
#include "attributes.h"
#include "special-chars.h"
#include "bitio.h"
#include "compression.h"
#include "regopt.h"
#include "cdaccess.h"
void Rprintf(const char *, ...);
/**
* If COMPRESS_DEBUG is set to a positive integer, cl_cpos2id() will
* print debugging messages. (2 prints more than 1!)
*/
#define COMPRESS_DEBUG 0
/**
* Error number for CL: is set after access to any of various corpus-data-access functions.
*/
int cl_errno = CDA_OK;
/**
* Checks an Attribute passed as a function argument for usability in that function.
*
* (a) arg must not be NULL.
* (b) arg type has to be the type specified in atyp.
*
* If these conditions are not fulfilled, the current function returns rval, and
* cl_errno is set.
*/
#define check_arg(arg,atyp,rval) \
if (arg == NULL) { \
cl_errno = CDA_ENULLATT; return rval; \
} \
else if (arg->type != atyp) { \
cl_errno = CDA_EATTTYPE; return rval; \
}
/**
* CL internal string comparison (uses signed char on all platforms).
*/
int
cl_strcmp(char *s1, char *s2)
{
/* BIG BIG BIG warning:
although it says unsigned_char_strcmp it really operates
on SIGNED char strings (and it didn't even say that explicitly, so the
whole thing broke down on 'unsigned char'-machines) !!! */
register signed char* c1;
register signed char* c2;
c1 = (signed char *)s1;
c2 = (signed char *)s2;
for ( ; *c1 == *c2; c1++,c2++)
if ( *c1 == '\0')
return 0;
return *c1 - *c2;
}
/**
* Gets a string describing the error identified by an error number.
*
* The string is a pointer to an internal constant string, i.e.,
* do not modify or free it!
*
* @param error_num Error number integer (a CDA_* constant as defined in cl.h)
*/
char *
cl_error_string(int error_num)
{
char *s;
switch (error_num) {
case CDA_OK:
s = "CL: No error";
break;
case CDA_ENULLATT:
s = "CL: NULL passed as attribute argument of function";
break;
case CDA_EATTTYPE:
s = "CL: function called with illegal attribute type";
break;
case CDA_EIDORNG:
s = "CL: id is out of range";
break;
case CDA_EPOSORNG:
s = "CL: position is out of range";
break;
case CDA_EIDXORNG:
s = "CL: index is out of range";
break;
case CDA_ENOSTRING:
s = "CL: no such string encoded";
break;
case CDA_EPATTERN:
s = "CL: illegal regular expression/illegal pattern";
break;
case CDA_ESTRUC:
s = "CL: no structure defined for this position";
break;
case CDA_EALIGN:
s = "CL: no alignment defined for this position";
break;
case CDA_EREMOTE:
s = "CL: error during access of remote data";
break;
case CDA_ENODATA:
s = "CL: can't load and/or create necessary data";
break;
case CDA_EARGS:
s = "CL: error in arguments of dynamic call or CL function";
break;
case CDA_ENOMEM:
s = "CL: not enough memory";
break;
case CDA_EOTHER:
s = "CL: unspecified error";
break;
case CDA_ENYI:
s = "CL: unimplemented feature/not yet implemented";
break;
case CDA_EBADREGEX:
s = "CL: bad regular expression";
break;
case CDA_EFSETINV:
s = "CL: invalid feature set (syntax error)";
break;
case CDA_EBUFFER:
s = "CL: internal buffer overflow";
break;
case CDA_EINTERNAL:
s = "CL: internal data inconsistency";
break;
case CDA_EACCESS:
s = "CL: insufficient access permissions";
break;
case CDA_EPOSIX:
s = strerror(errno);
break;
default:
s = "CL: ILLEGAL ERROR NUMBER";
break;
}
return s;
}
/**
* Prints an error message, together with a string identifying the current error number.
*/
void
cl_error(char *message)
{
if (message != NULL)
Rprintf("%s: %s\n", cl_error_string(cl_errno), message);
else
Rprintf("%s\n", cl_error_string(cl_errno));
}
/* ================================================== POSITIONAL ATTRIBUTES */
/* ==================== the mapping between strings and their ids */
/**
* Gets the string that corresponds to the specified item on the given P-attribute.
*
* @param attribute The Attribute to look the item up on
* @param id Identifier of an item on this attribute.
* @return The string (pointer to actual data within the
* attribute, DO NOT FREE!), or NULL if there is an error.
*/
char *
cl_id2str(Attribute *attribute, int id)
{
Component *lex;
Component *lexidx;
check_arg(attribute, ATT_POS, NULL);
lex = ensure_component(attribute, CompLexicon, 0);
lexidx = ensure_component(attribute, CompLexiconIdx, 0);
if ((lex == NULL) || (lexidx == NULL)) {
cl_errno = CDA_ENODATA;
return NULL;
}
else if ((id < 0) || (id >= lexidx->size)) {
cl_errno = CDA_EIDORNG;
return NULL;
}
else {
cl_errno = CDA_OK;
return ((char *)lex->data.data + ntohl(lexidx->data.data[id]));
}
assert("Not reached" && 0);
return NULL;
}
/**
* Gets the ID code that corresponds to the specified string on the given P-attribute.
*
* @param attribute The (positional) Attribute to look the string up on
* @param id_string The string of an item on this attribute
* @return Either the integer ID of the item, or an error code (if less than 0).
* In the latter case, the error code will also be written to cl_errno.
*/
int
cl_str2id(Attribute *attribute, char *id_string)
{
int low, high, nr, mid, comp;
Component *lexidx;
Component *lexsrt;
Component *lex;
char *str2;
check_arg(attribute, ATT_POS, cl_errno);
lexidx = ensure_component(attribute, CompLexiconIdx, 0);
lexsrt = ensure_component(attribute, CompLexiconSrt, 0);
lex = ensure_component(attribute, CompLexicon, 0);
if ((lexidx == NULL) || (lexsrt == NULL) || (lex == NULL)) {
cl_errno = CDA_ENODATA;
return cl_errno;
}
else {
low = 0;
high = lexidx->size;
/* simple binary search */
for(nr = 0; ; nr++) {
if (nr >= 1000000) {
Rprintf("get_id_of_string: too many comparisons with %s\n", id_string);
cl_errno = CDA_EOTHER;
return cl_errno;
}
mid = low + (high - low)/2;
str2 = (char *)(lex->data.data) +
ntohl(lexidx->data.data[ntohl(lexsrt->data.data[mid])]);
comp = cl_strcmp(id_string, str2);
if(comp == 0) {
cl_errno = CDA_OK;
return ntohl(lexsrt->data.data[mid]);
}
if(mid == low) {
cl_errno = CDA_ENOSTRING;
return cl_errno;
}
if(comp > 0)
low = mid;
else
high = mid;
}
}
assert("Not reached" && 0);
return 0;
}
/**
* Calculates the length of the string that corresponds to the specified
* item on the given P-attribute.
*
* @param attribute The (positional) Attribute to look up the item on
* @param id Identifier of an item on this attribute.
* @return The length of the string, or a CDA_ error code
*/
int
cl_id2strlen(Attribute *attribute, int id)
{
Component *lexidx;
char *s;
check_arg(attribute, ATT_POS, cl_errno);
lexidx = ensure_component(attribute, CompLexiconIdx, 0);
if (lexidx == NULL) {
cl_errno = CDA_ENODATA;
return CDA_ENODATA;
}
else if ((id < 0) || (id >= lexidx->size)) {
cl_errno = CDA_EIDORNG;
return CDA_EIDORNG;
}
else {
if ((id + 1) == lexidx->size) {
/* last word */
s = cl_id2str(attribute, id);
if (s != NULL) {
cl_errno = CDA_OK;
return strlen(s);
}
else if (cl_errno != CDA_OK)
return cl_errno;
else
return CDA_EOTHER;
}
else {
cl_errno = CDA_OK;
return (ntohl(lexidx->data.data[id+1]) -
ntohl(lexidx->data.data[id])) - 1;
}
}
assert("Not reached" && 0);
return 0;
}
/**
* Gets the ID code of the item at the specified position in the Attribute's sorted wordlist index.
*
* That is, given a sort-order position, the actual ID of the corresponding item is generated.
*
* @see get_sortidxpos_of_id
* @param attribute The (positional) Attribute whose index is to be searched.
* @param sort_index_position The offset in the index where the ID code is to be found.
* @return Either the integer ID, or an error code (if less than 0)
*/
int
cl_sort2id(Attribute *attribute, int sort_index_position)
{
Component *srtidx;
check_arg(attribute, ATT_POS, cl_errno);
srtidx = ensure_component(attribute, CompLexiconSrt, 0);
if (srtidx == NULL) {
cl_errno = CDA_ENODATA;
return CDA_ENODATA;
}
if ((sort_index_position >=0) && (sort_index_position < srtidx->size)) {
cl_errno = CDA_OK;
return ntohl(srtidx->data.data[sort_index_position]);
}
else {
cl_errno = CDA_EIDXORNG;
return CDA_EIDXORNG;
}
assert("Not reached" && 0);
return 0;
}
/**
* Gets the position in the Attribute's sorted wordlist index of the item
* with the specified ID code.
*
* This function is NOT YET IMPLEMENTED.
*
* @see get_id_from_sortidx
* @param attribute The (positional) Attribute whose index is to be searched
* @param id Identifier of an item on this attribute.
* @return The offset of that item in the sorted wordlist index.
*/
int
cl_id2sort(Attribute *attribute, int id)
{
Component *srtidx;
check_arg(attribute, ATT_POS, cl_errno);
srtidx = ensure_component(attribute, CompLexiconSrt, 0);
if (srtidx == NULL) {
cl_errno = CDA_ENODATA;
return CDA_ENODATA;
}
if ((id >=0) && (id < srtidx->size)) {
cl_errno = CDA_OK;
cl_errno = CDA_ENYI;
return CDA_ENYI;
}
assert("Not reached" && 0);
return 0;
}
/* ==================== information about the corpus */
/**
* Checks whether the item sequence of the given P-attribute is compressed.
*
* See comments in body of function for what counts as "compressed".
*
* @return Boolean.
*/
int
cl_sequence_compressed(Attribute *attribute)
{
ComponentState state;
check_arg(attribute, ATT_POS, cl_errno);
/* The item sequence is compressed iff all three components
* (CompHuffSeq, CompHuffCodes, CompHuffSync) are loaded or unloaded
* OR when the code description block is already initialized */
/* further, the CompCorpus component shouldn't be in memory. This is
* a trick, so that uncompressed access can be enforced if the
* CompCorpus is ensure'd. */
if (attribute->pos.hc != NULL)
return 1;
else {
/* if CompCorpus is in memory, we do not access the compressed
* sequence.
*/
state = component_state(attribute, CompCorpus);
if (state == ComponentLoaded)
return 0;
state = component_state(attribute, CompHuffSeq);
if (!(state == ComponentLoaded || state == ComponentUnloaded))
return 0;
state = component_state(attribute, CompHuffCodes);
if (!(state == ComponentLoaded || state == ComponentUnloaded))
return 0;
state = component_state(attribute, CompHuffSync);
if (!(state == ComponentLoaded || state == ComponentUnloaded))
return 0;
return 1;
}
}
/**
* Check whether the reverse-corpus index (inverted file) of the given P-attribute is compressed.
*
* See comments in body of function for what counts as "compressed".
*
* @return Boolean.
*/
int
cl_index_compressed(Attribute *attribute)
{
ComponentState state;
check_arg(attribute, ATT_POS, cl_errno);
/* The inverted file is compressed iff both two components
* (CompCompRF, CompCompRFX) are loaded or unloaded */
/* as above: when CompRevCorpus and CompRevCorpusIdx are already
* in memory, we do not use the compressed inverted file.
*/
if ((component_state(attribute, CompRevCorpus) == ComponentLoaded) &&
(component_state(attribute, CompRevCorpusIdx) == ComponentLoaded))
return 0;
state = component_state(attribute, CompCompRF);
if (!(state == ComponentLoaded || state == ComponentUnloaded))
return 0;
state = component_state(attribute, CompCompRFX);
if (!(state == ComponentLoaded || state == ComponentUnloaded))
return 0;
return 1;
}
/* ------------------------------------------------------------ */
/**
* Gets the maximum position on this P-attribute (ie the size of the
* attribute).
*
* The result of this function is equal to the number of tokens
* in the attribute.
*
* If the attribute's item sequence is compressed, this is read from
* the attribute's Huffman code descriptor block.
*
* Otherwise, it is read from the size member of the Attribute's
* CompCorpus component.
*
* @return The maximum corpus position, or an error code (if less than 0)
*/
int
cl_max_cpos(Attribute *attribute)
{
Component *corpus;
check_arg(attribute, ATT_POS, cl_errno);
if (cl_sequence_compressed(attribute) == 1) {
ensure_component(attribute, CompHuffCodes, 0);
if (attribute->pos.hc == NULL) {
cl_errno = CDA_ENODATA;
return CDA_ENODATA;
}
cl_errno = CDA_OK;
return attribute->pos.hc->length;
}
else {
corpus = ensure_component(attribute, CompCorpus, 0);
if (corpus == NULL) {
cl_errno = CDA_ENODATA;
return CDA_ENODATA;
}
else {
cl_errno = CDA_OK;
return corpus->size;
}
}
assert("Not reached" && 0);
return 0;
}
/**
* Gets the maximum id on this P-attribute (ie the range of the attribute's ID codes).
*
* The result of this function is equal to the number of types in this attribute.
*
* @see get_attribute_size
*
* @return The maximum Id, or an error code (if less than 0)
*/
int
cl_max_id(Attribute *attribute)
{
Component *comp;
check_arg(attribute, ATT_POS, cl_errno);
comp = ensure_component(attribute, CompLexiconIdx, 0);
if (comp == NULL) {
cl_errno = CDA_ENODATA;
return CDA_ENODATA;
}
else {
cl_errno = CDA_OK;
return comp->size;
}
assert("Not reached" && 0);
return 0;
}
/* ==================== the relation between ids and the corpus */
/**
* Gets the frequency of an item on this attribute.
*
* @param attribute The P-attribute to look on
* @param id Identifier of an item on this attribute.
* @return The frequency count of the item specified
* by id, or an error code (if less than 0)
*/
int
cl_id2freq(Attribute *attribute, int id)
{
Component *freqs;
check_arg(attribute, ATT_POS, cl_errno);
freqs = ensure_component(attribute, CompCorpusFreqs, 0);
if (freqs == NULL) {
cl_errno = CDA_ENODATA;
return CDA_ENODATA;
}
else if ((id >= 0) && (id < freqs->size)) {
cl_errno = CDA_OK;
return ntohl(freqs->data.data[id]);
}
else {
cl_errno = CDA_EIDXORNG;
return CDA_EIDXORNG;
}
assert("Not reached" && 0);
return 0;
}
/* ============================================================ */
/**
* Gets all the corpus positions where the specified item is
* found on the given P-attribute.
*
* The restrictor list is a set of ranges in which instances of
* the item MUST occur to be collected by this function. If no
* restrictor list is specified (i.e. restrictor_list is NULL),
* then ALL corpus positions where the item occurs are returned.
*
* This restrictor list has the form of a list of ranges {start,end}
* of size restrictor_list_size, that is, the number of ints in
* this area is 2 * restrictor_list_size!!!
*
* This function is "oldstyle" because in the "newstyle" function,
* there is no restrictor list. (And in fact, the newstyle
* function is implemented as a macro to this one with the last
* two arguments NULL and 0.)
*
* @see
*
* @param attribute The P-attribute to look on.
* @param id The id of the item to look
* for.
* @param freq The frequency of the specified
* item is written here. This will
* be 0 in the case of errors.
* @param restrictor_list A list of pairs of integers
* specifying ranges {start,end}
* in the corpus
* @param restrictor_list_size The number of PAIRS of ints in
* the restrictor list.
* @return Pointer to the list of corpus
* positions; or NULL in case of
* error.
*/
int *
cl_id2cpos_oldstyle(Attribute *attribute, int id, int *freq, int *restrictor_list, int restrictor_list_size)
{
Component *revcorp, *revcidx;
int *buffer;
int size, range;
check_arg(attribute, ATT_POS, NULL);
size = cl_max_cpos(attribute);
if ((size <= 0) || (cl_errno != CDA_OK)) {
/* Rprintf("Cannot determine size of PA %s\n", */
/* attribute->any.name); */
return NULL;
}
range = cl_max_id(attribute);
if ((range <= 0) || (cl_errno != CDA_OK)) {
/* Rprintf("Cannot determine ID range of PA %s\n", */
/* attribute->any.name); */
return NULL;
}
if ((id <0) || (id >= range)) {
cl_errno = CDA_EIDORNG;
/* Rprintf("ID %d out of range of PA %s\n", */
/* id, attribute->any.name); */
*freq = 0;
return NULL;
}
*freq = cl_id2freq(attribute, id);
if ((*freq < 0) || (cl_errno != CDA_OK)) {
/* Rprintf("Frequency %d of ID %d illegal (PA %s)\n", */
/* *freq, id, attribute->any.name); */
return NULL;
}
/* there are no items in a P-Attribute with freq 0 - we don't have to
catch that special case. */
buffer = (int *)cl_malloc(*freq * sizeof(int));
if (cl_index_compressed(attribute)) {
BStream bs;
unsigned int i, b, last_pos, gap, offset, ins_ptr, res_ptr;
revcorp = ensure_component(attribute, CompCompRF, 0);
revcidx = ensure_component(attribute, CompCompRFX, 0);
if (revcorp == NULL || revcidx == NULL) {
cl_errno = CDA_ENODATA;
*freq = 0;
return NULL;
}
b = compute_ba(*freq, size);
offset = ntohl(revcidx->data.data[id]); /* byte offset in RFC */
BSopen((unsigned char *)revcorp->data.data, "r", &bs);
BSseek(&bs, offset);
last_pos = 0;
ins_ptr = 0;
res_ptr = 0;
for (i = 0; i < *freq; i++) {
gap = read_golomb_code_bs(b, &bs);
last_pos += gap;
/* when the end of the restrictor list is reached, we can
also leave the for loop above -- TODO
*/
if (restrictor_list && restrictor_list_size > 0) {
while (res_ptr < restrictor_list_size &&
last_pos > restrictor_list[res_ptr * 2 + 1]) {
/* beyond last restricting range */
res_ptr++;
}
if (res_ptr < restrictor_list_size &&
last_pos >= restrictor_list[res_ptr * 2] &&
last_pos <= restrictor_list[res_ptr * 2 + 1]) {
buffer[ins_ptr++] = last_pos;
}
}
else {
/* no restrictor list: copy */
buffer[ins_ptr++] = last_pos;
}
}
BSclose(&bs);
/* reduce, if possible */
if (ins_ptr < *freq && ins_ptr != *freq) {
if (ins_ptr == 0) {
assert(buffer != NULL);
cl_free(buffer);
}
else {
buffer = cl_realloc(buffer, ins_ptr * sizeof(int));
}
*freq = ins_ptr;
}
} /* endif cl_index_compressed */
else {
revcorp = ensure_component(attribute, CompRevCorpus, 0);
revcidx = ensure_component(attribute, CompRevCorpusIdx, 0);
if (revcorp == NULL || revcidx == NULL) {
cl_errno = CDA_ENODATA;
/* Rprintf("Cannot load REVCORP or REVCIDX component of %s\n", */
/* attribute->any.name); */
*freq = 0;
return NULL;
}
memcpy(buffer,
revcorp->data.data + ntohl(revcidx->data.data[id]),
*freq * sizeof(int));
{ /* convert network byte order to native integers */
int i;
for (i = 0; i < *freq; i++)
buffer[i] = ntohl(buffer[i]);
}
if (restrictor_list != NULL && restrictor_list_size > 0) {
int res_ptr, buf_ptr, ins_ptr;
/* force all items to be within the restrictor's ranges */
ins_ptr = 0;
res_ptr = 0;
buf_ptr = 0;
while (buf_ptr < *freq && res_ptr < restrictor_list_size) {
if (buffer[buf_ptr] < restrictor_list[res_ptr*2]) {
/* before start */
buf_ptr++;
}
else if (buffer[buf_ptr] > restrictor_list[res_ptr*2+1]) {
/* beyond end */
res_ptr++;
}
else {
/* within range */
buffer[ins_ptr++] = buffer[buf_ptr++];
}
}
if (ins_ptr < *freq && ins_ptr != *freq) {
if (ins_ptr == 0) {
cl_free(buffer);
}
else {
buffer = cl_realloc(buffer, ins_ptr * sizeof(int));
}
*freq = ins_ptr;
}
}
}
cl_errno = CDA_OK;
return buffer;
assert("Not reached" && 0);
return NULL;
}
/* ---------------------------------------- stream-like reading */
/**
* Underlying structure for the PositionStream object.
*
* PositionStreams are used for accessing Attributes.
* Each one represents a stream of corpus positions,
* representing positions where a given item occurs.
*
*/
typedef struct _position_stream_rec_ {
Attribute *attribute; /**< The Attribute on which this PositionStream has been opened. */
int id; /**< The item whose positions this PositionStream will read */
int id_freq; /**< id frequency (ie frequency of the item in question);
maximum number of positions that can be read */
int nr_items; /**< how many items delivered so far */
int is_compressed; /**< Boolean: attribute REVCORP is compressed? */
/** for compressed streams, the stream is a BStream object rather than just a pointer. */
BStream bs;
int b; /**< relevent for compressed streams */
int last_pos; /**< relevent for compressed streams */
/** pointer to base of stream for uncompressed streams. */
int *base;
} PositionStreamRecord;
/**
* Creates a new PositionStream object.
*
* @param attribute The P-attribute to open the position stream on
* @param id The id that the new PositionStream will have.
* This the id of an item on the specified attribute.
* @return The new object, or NULL in case of problem.
*/
PositionStream
cl_new_stream(Attribute *attribute,
int id)
{
Component *revcorp, *revcidx;
int size, freq, range;
PositionStream ps = NULL;
check_arg(attribute, ATT_POS, NULL);
size = get_attribute_size(attribute);
if ((size <= 0) || (cl_errno != CDA_OK))
return NULL;
range = get_id_range(attribute);
if ((range <= 0) || (cl_errno != CDA_OK))
return NULL;
if ((id <0) || (id >= range)) {
cl_errno = CDA_EIDORNG;
return NULL;
}
freq = get_id_frequency(attribute, id);
if ((freq < 0) || (cl_errno != CDA_OK))
return NULL;
ps = new(PositionStreamRecord);
assert(ps);
ps->attribute = attribute;
ps->id = id;
ps->id_freq = freq;
ps->nr_items = 0;
ps->is_compressed = 0;
ps->b = 0; ps->last_pos = 0;
ps->base = NULL;
if (cl_index_compressed(attribute)) {
int offset;
ps->is_compressed = 1;
revcorp = ensure_component(attribute, CompCompRF, 0);
revcidx = ensure_component(attribute, CompCompRFX, 0);
if (revcorp == NULL || revcidx == NULL) {
cl_errno = CDA_ENODATA;
free(ps);
return NULL;
}
ps->b = compute_ba(ps->id_freq, size);
offset = ntohl(revcidx->data.data[id]); /* byte offset in RFC */
BSopen((unsigned char *)revcorp->data.data, "r", &(ps->bs));
BSseek(&(ps->bs), offset);
ps->last_pos = 0;
}
else {
ps->is_compressed = 0;
revcorp = ensure_component(attribute, CompRevCorpus, 0);
revcidx = ensure_component(attribute, CompRevCorpusIdx, 0);
if (revcorp == NULL || revcidx == NULL) {
cl_errno = CDA_ENODATA;
free(ps);
return NULL;
}
ps->base = revcorp->data.data + ntohl(revcidx->data.data[ps->id]);
}
return ps;
}
/**
* Deletes a PositionStream object.
*/
int
cl_delete_stream(PositionStream *ps)
{
assert(ps && *ps);
(*ps)->attribute = NULL;
(*ps)->id = -1;
(*ps)->id_freq = -1;
(*ps)->nr_items = -1;
(*ps)->is_compressed = 0;
if ((*ps)->is_compressed) {
BSclose(&((*ps)->bs));
(*ps)->b = 0;
(*ps)->last_pos = 0;
}
else {
(*ps)->base = NULL;
}
free(*ps);
*ps = NULL;
return 1;
}
/**
* Reads corpus positions from a position stream to a buffer.
*
* @param ps The position stream to read.
* @param buffer Location to put the resulting item positions.
* @param buffer_size Maximum number of item positions to read.
* (Fewer will be read if fewer are available).
* @return The number of item positions that have been
* read. This may be less than buffer_size (and
* will be 0 if there are no instances of this item left).
*/
int
cl_read_stream(PositionStream ps,
int *buffer,
int buffer_size)
{
int items_to_read;
assert(ps);
assert(buffer);
/* return 0 if we have already read >= freq items */
if (ps->nr_items >= ps->id_freq)
return 0;
if (ps->nr_items + buffer_size > ps->id_freq) {
items_to_read = ps->id_freq - ps->nr_items;
}
else {
items_to_read = buffer_size;
}
assert(items_to_read >= 0);
if (items_to_read == 0)
return 0;
if (ps->is_compressed) {
int gap, i;
for (i = 0; i < items_to_read; i++,ps->nr_items++) {
gap = read_golomb_code_bs(ps->b, &(ps->bs));
ps->last_pos += gap;
*buffer = ps->last_pos;
buffer++;
}
}
else {
memcpy(buffer,
ps->base + ps->nr_items,
items_to_read * sizeof(int));
ps->nr_items += items_to_read;
{
/* convert network byte order to native integers */
int i;
for (i = 0; i < items_to_read; i++)
buffer[i] = ntohl(buffer[i]);
}
}
return items_to_read;
}
/**
* Gets the integer ID of the item at the specified
* position on the given p-attribute.
*
* @param attribute The P-attribute to look on.
* @param position The corpus position to look at.
* @return The id of the item at that position
* on this attribute, OR a negative value
* if there is an error.
*/
int
cl_cpos2id(Attribute *attribute, int position)
{
Component *corpus;
check_arg(attribute, ATT_POS, cl_errno);
if (item_sequence_is_compressed(attribute) == 1) {
Component *cis;
Component *cis_sync;
Component *cis_map;
BStream bs;
unsigned char bit;
int item;
unsigned int block, rest, offset, max, v, l, i;
if (COMPRESS_DEBUG > 1)
Rprintf("Accessing position %d of %s via compressed item sequence\n",
position, attribute->any.name);
cis = ensure_component(attribute, CompHuffSeq, 0);
cis_map = ensure_component(attribute, CompHuffCodes, 0);
cis_sync = ensure_component(attribute, CompHuffSync, 0);
if ((cis == NULL) || (cis_map == NULL) || (cis_sync == NULL)) {
cl_errno = CDA_ENODATA;
return CDA_ENODATA;
}
if ((position >= 0) && (position < attribute->pos.hc->length)) {
block = position / SYNCHRONIZATION;
rest = position % SYNCHRONIZATION;
if (attribute->pos.this_block_nr != block) {
/* the current block in the decompression buffer is not the
* block we need. So we read the proper block into the buffer
* and hope that we'll get a cache hit next time. */
if (COMPRESS_DEBUG > 0)
Rprintf("Block miss: have %d, want %d\n",
attribute->pos.this_block_nr, block);
/* is the block we read the last block of the corpus? Then, we
* cannot read SYNC items, but only as much as there are left.
* */
max = attribute->pos.hc->length - block * SYNCHRONIZATION;
if (max > SYNCHRONIZATION)
max = SYNCHRONIZATION;
attribute->pos.this_block_nr = block;
offset = ntohl(cis_sync->data.data[block]);
if (COMPRESS_DEBUG > 1)
Rprintf("-> Block %d, rest %d, offset %d\n",
block, rest, offset);
BSopen((unsigned char *)cis->data.data, "r", &bs);
BSseek(&bs, offset);
for (i = 0; i < max; i++) {
if (!BSread(&bit, 1, &bs)) {
Rprintf("cdaccess:decompressed read: Read error/1\n");
cl_errno = CDA_ENODATA;
return cl_errno;
}
v = (bit ? 1 : 0);
l = 1;
while (v < attribute->pos.hc->min_code[l]) {
if (!BSread(&bit, 1, &bs)) {
Rprintf("cdaccess:decompressed read: Read error/2\n");
cl_errno = CDA_ENODATA;
return cl_errno;
}
v <<= 1;
if (bit)
v++;
l++;
}
/* we now have the item - store it in the decompression block */
item = ntohl(attribute->pos.hc->symbols[attribute->pos.hc->symindex[l] + v -
attribute->pos.hc->min_code[l]]);
attribute->pos.this_block[i] = item;
}
BSclose(&bs);
}
else if (COMPRESS_DEBUG > 0)
Rprintf("Block hit: block[%d,%d]\n", block, rest);
assert(rest < SYNCHRONIZATION);
cl_errno = CDA_OK; /* hi 'Oli' ! */
return attribute->pos.this_block[rest];
}
else {
cl_errno = CDA_EPOSORNG;
return CDA_EPOSORNG;
}
}
else {
corpus = ensure_component(attribute, CompCorpus, 0);
if (corpus == NULL) {
cl_errno = CDA_ENODATA;
return CDA_ENODATA;
}
if ((position >= 0) && (position < corpus->size)) {
cl_errno = CDA_OK;
return ntohl(corpus->data.data[position]);
}
else {
cl_errno = CDA_EPOSORNG;
return CDA_EPOSORNG;
}
}
assert("Not reached" && 0);
return 0;
}
/**
* Gets the string of the item at the specified
* position on the given p-attribute.
*
* @param attribute The P-attribute to look on.
* @param position The corpus position to look at.
* @return The string of the item at that position
* on this attribute (pointer to actual data within the
* attribute, DO NOT FREE!), or NULL
* if there is an error.
*/
char *
cl_cpos2str(Attribute *attribute, int position)
{
int id;
check_arg(attribute, ATT_POS, NULL);
id = cl_cpos2id(attribute, position);
if ((id < 0) || (cl_errno != CDA_OK))
return NULL;
return cl_id2str(attribute, id);
}
/* ========== some high-level constructs */
/**
* Gets the string of the item with the specified
* ID on the given p-attribute.
*
* As well as returning the string, other information
* about the item is inserted into locations specified
* by other parameters.
*
* @param attribute The P-attribute to look on.
* @param index The ID of the item to look at.
* @param freq Will be set to the frequency of the item.
* @param slen Will be set to the string-length of the
* item.
* @return The string of the item at that position
* on this attribute, OR NULL
* if there is an error.
*/
char *
cl_id2all(Attribute *attribute, int index, int *freq, int *slen)
{
check_arg(attribute, ATT_POS, NULL);
*freq = get_id_frequency(attribute, index);
if ((*freq < 0) || (cl_errno != CDA_OK))
return NULL;
*slen = get_id_string_len(attribute, index);
if ((*slen < 0) || (cl_errno != CDA_OK))
return NULL;
return get_string_of_id(attribute, index);
}
/**
* Gets a list of the ids of those items on a given Attribute that
* match a particular regular-expression pattern.
*
* The pattern is interpreted internally with the CL regex engine, q.v.
*
* The function returns a pointer to a sequence of ints of size number_of_matches. The list
* is allocated with malloc(), so do a cl_free() when you don't need it any more.
*
* @see cl_new_regex
* @param attribute The p-attribute to look on.
* @param pattern String containing the pattern against which to match each item on the attribute.
* Note: this pattern is a regular expression, but it is passed as a string, not
* a CL_Regex object. The CL_Regex object is created internally.
* @param flags Flags for the regular expression system via cl_new_regex.
* @param number_of_matches This is set to the number of item ids found, i.e. the size of the returned buffer.
* @return A pointer to the list of item ids.
*/
int *
cl_regex2id(Attribute *attribute, char *pattern, int flags, int *number_of_matches)
{
Component *lexidx;
Component *lex;
int *lexidx_data;
char *lex_data;
int *table; /* list of matching IDs */
int match_count; /* count matches in local variable while scanning */
/* results are stored as a a bitmap: one bit per lexicon item */
/* note that it would also be possible to use a Bitfield <bitfield.h>, but this custom implementation is somewhat more efficient */
unsigned char *bitmap = NULL; /* use bitmap while scanning lexicon to reduce memory footprint and avoid large realloc() */
int bitmap_size; /* size of allocated bitmap in bytes */
int bitmap_offset; /* current bitmap offset (in bytes) */
unsigned char bitmap_mask; /* current bitmap offset (within-byte part, as bit mask) */
/* TODO might move bitmap to static variable and re-allocate only when necessary ... */
int idx, i, lexsize;
int optimised;
CL_Regex rx;
char *word;
check_arg(attribute, ATT_POS, NULL);
lexidx = ensure_component(attribute, CompLexiconIdx, 0);
lex = ensure_component(attribute, CompLexicon, 0);
if ((lexidx == NULL) || (lex == NULL)) {
cl_errno = CDA_ENODATA;
return NULL;
}
lexsize = lexidx->size;
lexidx_data = (int *) lexidx->data.data;
lex_data = (char *) lex->data.data;
match_count = 0;
rx = cl_new_regex(pattern, flags, attribute->pos.mother->charset);
if (rx == NULL) {
Rprintf("Regex Compile Error: %s\n", cl_regex_error);
cl_errno = CDA_EBADREGEX;
return NULL;
}
optimised = cl_regex_optimised(rx);
/* allocate bitmap for matching IDs */
bitmap_size = (lexsize + 7) / 8; /* this is the exact number of bytes needed, I hope */
bitmap = (unsigned char *) cl_calloc(bitmap_size, sizeof(unsigned char)); /* initialise: no bits set */
bitmap_offset = 0;
bitmap_mask = 0x80; /* start with MSB of first byte */
cl_regopt_count_reset(); /* report how often we have a grain match when using optimised search */
/* for each index in the lexicon... */
for (idx = 0; idx < lexsize; idx++) {
int off_start; /* start and end offset of current lexicon entry */
/* char *p; */
/* int i; */
/* compute start offset and length of current lexicon entry from lexidx, if possible)
* -- no longer necessary because we can't pass len to cl_regex_match
* -- although 'twould be a good optimisation if possible to avoid calling strlen
* -- pass in via a global variable cl_regopt_haystack_strlenin? */
off_start = ntohl(lexidx_data[idx]);
word = lex_data + off_start;
if (idx < lexsize-1) {
/* off_end = ntohl(lexidx_data[idx + 1]) - 1; */
/* len = off_end - off_start; */
}
else {
/* len = strlen(word); */
}
if (cl_regex_match(rx, word, 0)) { /* regex match */
bitmap[bitmap_offset] |= bitmap_mask; /* set bit */
match_count++;
}
bitmap_mask >>= 1;
if (bitmap_mask == 0) {
bitmap_offset++;
bitmap_mask = 0x80;
}
} /* endfor (loop across lexicon items) */
if (cl_debug && optimised)
Rprintf("CL: regexp optimiser avoided calling regex engine for %d candidates out of %d strings\n"
" (%d matching strings in total) \n", cl_regopt_count_get(), lexsize, match_count);
if (match_count == 0) { /* no matches */
table = NULL;
}
else { /* generate list of matching IDs from bitmap */
table = (int *) cl_malloc(match_count * sizeof(int));
bitmap_offset = 0;
bitmap_mask = 0x80;
idx = 0;
for (i = 0; i < lexsize; i++) {
if (bitmap[bitmap_offset] & bitmap_mask) {
table[idx] = i;
idx++;
}
bitmap_mask >>= 1;
if (bitmap_mask == 0) {
bitmap_offset++;
bitmap_mask = 0x80;
}
}
assert((idx == match_count) && "cl_regex2id(): bitmap inconsistency");
}
*number_of_matches = match_count;
cl_free(bitmap);
cl_delete_regex(rx);
cl_errno = CDA_OK;
return table;
}
/**
* Calculates the total frequency of all items on a list of item IDs.
*
* This function returns the sum of the word frequencies of words,
* which is an array of word_ids with length number_of_words.
*
* The result is therefore the number of corpus positions which
* match one of the words.
*
* @param attribute P-attribute on which these items are found.
* @param word_ids An array of item IDs.
* @param number_of_words Length of the word_ids array.
* @return Sum of all the frequencies; less than 0 for an error.
*/
int cl_idlist2freq(Attribute *attribute,
int *word_ids,
int number_of_words)
{
int k, sum;
check_arg(attribute, ATT_POS, cl_errno);
sum = 0;
if (word_ids == NULL) {
cl_errno = CDA_ENODATA;
return CDA_ENODATA;
}
else {
for (k = 0; k < number_of_words; k++) {
sum += cl_id2freq(attribute, word_ids[k]);
if (cl_errno != CDA_OK)
return cl_errno;
}
cl_errno = CDA_OK;
return sum;
}
assert("Not reached" && 0);
return 0;
}
/* this is the way qsort(..) is meant to be used: give it void * args
and cast them to the actual type in the compare function;
this definition conforms to ANSI and POSIX standards according to the LDP */
/** internal function for use with qsort */
static int intcompare(const void *i, const void *j)
{ return(*(int *)i - *(int *)j); }
/* this is used in the following function, thus why it's here. */
/**
* Gets a list of corpus positions matching a list of ids.
*
* This function returns an (ordered) list of all corpus positions which
* match one of the ids given in the list of ids. The table is allocated
* with malloc, so free it when you don't need any more.
*
* The list itself is returned; its size is placed in size_of_table.
* This size is, of course, the same as the cumulative id frequency
* of the ids (because each corpus position matching one of the ids
* is added into the list).
*
* BEWARE: when the id list is rather big or there are highly-frequent
* ids in the id list (for example, after a call to collect_matching_ids
* with the pattern ".*") this will give a copy of the corpus -- for
* which you probably don't have enough memory!!! It is therefore a good
* idea to call cumulative_id_frequency before and to introduce some
* kind of bias.
*
* This function is DEPRACATED in favour of cl_idlist2cpos().
*
* This function is "oldstyle" because it has the "restrictor list"
* parameters, which are not available through the "newstyle" function
* cl_idlist2cpos() (which is currently just a macro to this).
*
* A note on the last two parameters, which are currently unused:
* restrictor_list is a list of integer pairs [a,b] which means that
* the returned value only contains positions which fall within at
* least one of these intervals. The list must be sorted by the start
* positions, and secondarily by b. restrictor_list_size is the number of
* integers in this list, NOT THE NUMBER OF PAIRS.
* WARNING: CURRENTLY UNIMPLEMENTED
* {NB -- this description of restrictor_list_size DOESN'T MATCH
* the one for get_positions(), which this function calls...
*
* REMEMBER: this monster returns a list of corpus indices, not a list
* of ids.
*
* @see collect_matching_ids
* @see get_positions
* @see cl_idlist2cpos
*
* @param attribute The P-attribute we are looking in
* @param word_ids A list of item ids (i.e. id codes for
* items on this attribute).
* @param number_of_words The length of this list.
* @param sort boolean: return sorted list?
* @param size_of_table The size of the allocated table will be
* placed here.
* @param restrictor_list See function description.
* @param restrictor_list_size See function description.
* @return Pointer to the list of corpus positions.
*/
int *
cl_idlist2cpos_oldstyle(Attribute *attribute,
int *word_ids,
int number_of_words,
int sort,
int *size_of_table,
int *restrictor_list,
int restrictor_list_size)
{
int size, k, p, word_id, freq;
int *table, *start;
Component *lexidx;
check_arg(attribute, ATT_POS, NULL);
*size_of_table = 0;
lexidx = ensure_component(attribute, CompLexiconIdx, 0);
if ((lexidx == NULL) || (word_ids == NULL)) {
cl_errno = CDA_ENODATA;
return NULL;
}
size = cl_idlist2freq(attribute, word_ids, number_of_words);
if ((size < 0) || (cl_errno != CDA_OK)) {
return NULL;
}
if (size > 0) {
table = (int *)cl_malloc(size * sizeof(int));
p = 0;
for (k = 0; k < number_of_words; k++) {
word_id = word_ids[k];
if ((word_id < 0) || (word_id >= lexidx->size)) {
cl_errno = CDA_EIDORNG;
free(table);
return NULL;
}
start = get_positions(attribute, word_id, &freq, NULL, 0);
if ((freq < 0) || (cl_errno != CDA_OK)) {
free(table);
return NULL;
}
/* lets hack: */
memcpy(&table[p], start, freq * sizeof(int));
p += freq;
/* f_o now always mallocs. */
free(start);
}
assert(p == size);
if (sort)
qsort(table, size, sizeof(int), intcompare);
*size_of_table = size;
cl_errno = CDA_OK;
return table;
}
else {
*size_of_table = 0;
cl_errno = CDA_OK;
return NULL;
}
assert("Not reached" && 0);
return NULL;
}
/* ================================================== UTILITY FUNCTIONS */
/**
* Gets a pointer to the location where a structure is stored.
*
* The structure (instance of an s-attribute) that is found
* is the one in which the specified corpus position occurs.
*
* Non-exported function.
*
* @param data "data.data" member of an s-attribute
* @param size "size" member of the same s-attribute
* @param position The corpus position to look for.
* @return Pointer to the integers in data where
* the start point of the structure at this
* corpus position can be found. NULL if
* not found.
*/
int *
get_previous_mark(int *data, int size, int position)
{
int nr;
int mid, high, low, comp;
int max = size/2;
low = 0;
nr = 0;
high = max - 1;
while (low <= high) {
nr++;
if (nr > 100000) {
Rprintf("Binary search in get_surrounding_positions failed\n");
return NULL;
}
mid = (low + high)/2;
comp = position - ntohl(data[mid*2]);
if (comp == 0)
return &data[mid*2];
else if (comp > 0) {
if (position <= ntohl(data[mid*2+1]))
return &data[mid*2];
else
low = mid + 1;
}
else if (mid == low) {
/* fail; */
return NULL;
}
else /* comp < 0 */
high = mid - 1;
}
return NULL;
}
/* ================================================== STRUCTURAL ATTRIBUTES */
/* first, some new style functions with normalised behaviour */
/**
* Gets the ID number of a structure (instance of an s-attribute)
* that is found at the given corpus position.
*
* This is a wrapper of the "old" function get_num_of_struc() that
* normalises it to standard return value behaviour.
*
* @param a The s-attribute on which to search.
* @param cpos The corpus position to look for.
* @return The number of the structure that is found.
*/
int
cl_cpos2struc(Attribute *a, int cpos)
{
int struc = -1;
if (cl_cpos2struc_oldstyle(a, cpos, &struc))
return struc;
else
return cl_errno;
}
/**
* Compares the location of a corpus position to
* the regions of an s-attribute.
*
* This determines whether the specified corpus position
* is within a region (i.e. a structure, an instance of
* that s-attribute) on the given s-attribute; and/or on
* a boundary; or outside a region.
*
* @see STRUC_INSIDE
* @see STRUC_LBOUND
* @see STRUC_RBOUND
*
* @param a The s-attribute on which to search.
* @param cpos The corpus position to look for.
* @return 0 if this position is outside a region;
* some combination of flags if it is within
* a region or on a bound; or a negative
* number (error code) in case of error.
*/
int
cl_cpos2boundary(Attribute *a, int cpos) {
/* convenience function: within region or at boundary? */
int start = -1, end = -1;
if (cl_cpos2struc2cpos(a, cpos, &start, &end)) {
int flags = STRUC_INSIDE;
if (cpos == start)
flags |= STRUC_LBOUND;
if (cpos == end)
flags |= STRUC_RBOUND;
return flags;
}
else if (cl_errno == CDA_ESTRUC) {
return 0; /* outside region */
}
else
return cl_errno; /* some error occurred */
}
/**
* Gets the maximum for this S-attribute (ie the size of the
* S-attribute).
*
* The result of this function is equal to the number of instances
* of this s-attribute in the corpus.
*
* This function works as a wrapper round cl_max_struc_oldstyle that
* normalises it to standard return value behaviour.
*
* @a The s-attribute to evaluate.
* @return The maximum corpus position, or an error code (if less than 0)
*/
int
cl_max_struc(Attribute *a)
{
int nr = -1;
if (cl_max_struc_oldstyle(a, &nr))
return nr;
else
return cl_errno;
}
/**
* Gets the start and end positions of the instance of the given S-attribute
* found at the specified corpus position.
*
* This function finds one particular instance of the S-attribute, and assigns
* its start and end points to the locations given as arguments.
*
* @param attribute The s-attribute to search.
* @param position The corpus position to search for.
* @param struc_start Location for the start position of the instance.
* @param struc_end Location for the end position of the instance.
*
* @return Boolean: true for all OK, false for error.
*
*/
int
cl_cpos2struc2cpos(Attribute *attribute,
int position,
int *struc_start,
int *struc_end)
{
Component *struc_data;
int *val;
check_arg(attribute, ATT_STRUC, cl_errno);
*struc_start = 0;
*struc_end = 0;
struc_data = ensure_component(attribute, CompStrucData, 0);
if (struc_data == NULL) {
cl_errno = CDA_ENODATA;
return 0;
}
val = get_previous_mark(struc_data->data.data,
struc_data->size,
position);
if (val != NULL) {
*struc_start = ntohl(*val);
*struc_end = ntohl(*(val + 1));
cl_errno = CDA_OK;
return 1;
}
else {
cl_errno = CDA_ESTRUC;
return 0;
}
assert("Not reached" && 0);
return 0;
}
/**
* Gets the ID number of a structure (instance of an s-attribute)
* that is found at the given corpus position.
*
* Depracated function: use cl_cpos2struc.
*
* @see cl_cpos2struc
*
* @param attribute The s-attribute on which to search.
* @param position The corpus position to look for.
* @param struc_num Location where the number of the structure that
* is found will be put.
* @return Boolean: true for all OK, false for error.
*/
int
cl_cpos2struc_oldstyle(Attribute *attribute, int position, int *struc_num)
{
Component *struc_data;
int *val;
check_arg(attribute, ATT_STRUC, cl_errno);
struc_data = ensure_component(attribute, CompStrucData, 0);
if (struc_data == NULL) {
cl_errno = CDA_ENODATA;
return 0;
}
val = get_previous_mark(struc_data->data.data,
struc_data->size,
position);
if (val != NULL) {
*struc_num = (val - struc_data->data.data)/2;
cl_errno = CDA_OK;
return 1;
}
else {
cl_errno = CDA_ESTRUC;
return 0;
}
assert("Not reached" && 0);
return 0;
}
/**
* Retrieves the start-and-end corpus positions of a specified structure
* of the given s-attribute type.
*
* @param attribute An s-attribute.
* @param struc_num The instance of that s-attribute to retrieve
* (i.e. the struc_num'th instance of this s-attribute
* in the corpus).
* @param struc_start Location to put the starting corpus position.
* @param struc_end Location to put the ending corpus position.
* @return boolean: true for all OK, 0 for problem
*/
int
cl_struc2cpos(Attribute *attribute,
int struc_num,
int *struc_start,
int *struc_end)
{
Component *struc_data;
check_arg(attribute, ATT_STRUC, cl_errno);
struc_data = ensure_component(attribute, CompStrucData, 0);
if (struc_data == NULL) {
cl_errno = CDA_ENODATA;
return 0;
}
if ((struc_num < 0) || (struc_num >= (struc_data->size / 2))) {
cl_errno = CDA_EIDXORNG;
return 0;
}
else {
*struc_start = ntohl(struc_data->data.data[struc_num * 2]);
*struc_end = ntohl(struc_data->data.data[(struc_num * 2)+1]);
cl_errno = CDA_OK;
return 1;
}
assert("Not reached" && 0);
return 0;
}
/**
* Gets the number of instances of an s-attribute in the corpus.
*
* Depracated: use cl_max_struc instead.
*
* @see cl_max_struc.
*
* @param attribute The s-attribute to count.
* @param nr_strucs The number of instances is put here.
* @return boolean: true for all OK, false for problem.
*/
int
cl_max_struc_oldstyle(Attribute *attribute, int *nr_strucs)
{
Component *struc_data;
check_arg(attribute, ATT_STRUC, cl_errno);
struc_data = ensure_component(attribute, CompStrucData, 0);
if (struc_data == NULL) {
cl_errno = CDA_ENODATA;
return 0;
}
*nr_strucs = struc_data->size / 2;
cl_errno = CDA_OK;
return 1;
assert("Not reached" && 0);
return 0;
}
/**
* Checks whether this s-attribute has attribute values.
*
* @return Boolean.
*/
int
cl_struc_values(Attribute *attribute) {
check_arg(attribute, ATT_STRUC, cl_errno);
if (attribute->struc.has_attribute_values < 0) {
/* if h_a_v < 0 then we didn't yet test whether it has values or not */
ComponentState avs_state, avx_state;
avs_state = component_state(attribute, CompStrucAVS);
avx_state = component_state(attribute, CompStrucAVX);
if ((avs_state == ComponentLoaded || avs_state == ComponentUnloaded) &&
(avx_state == ComponentLoaded || avx_state == ComponentUnloaded))
attribute->struc.has_attribute_values = 1;
else
attribute->struc.has_attribute_values = 0;
}
cl_errno = CDA_OK;
return attribute->struc.has_attribute_values;
}
/**
* A non-exported function used by cl_struc2str
*/
int
s_v_comp(const void *v1, const void *v2)
{
return ntohl(*((int *)v1)) - ntohl(*((int *)v2));
}
/**
* Gets the value that is associated with the specified instance
* of the given s-attribute.
*
* @param attribute An S-attribute.
* @param struc_num ID of the structure whose value is wanted
* (ie, function gets value of struc_num'th
* instance of this s-attribute)
* @return A string; or NULL in case of error. Note that
* this string is a pointer to the depths of the
* Attribute object itself, as this function does
* not strdup() its result -- so don't free this
* return value!
*
*/
char *
cl_struc2str(Attribute *attribute, int struc_num)
{
check_arg(attribute, ATT_STRUC, NULL);
if (cl_struc_values(attribute) && (cl_errno == CDA_OK)) {
/* local structure */
typedef struct _idx_el {
int id;
int offset;
} IndexElement;
Component *avs;
Component *avx;
IndexElement key, *idx;
avs = ensure_component(attribute, CompStrucAVS, 0);
avx = ensure_component(attribute, CompStrucAVX, 0);
if (avs == NULL || avx == NULL) {
cl_errno = CDA_ENODATA;
return 0;
}
key.id = htonl(struc_num);
/* current redundant file format allows regions without annotations, so the index file (avx)
* consists of (region index, ptr) pairs, where ptr is an offset into the lexicon file (avs)
*/
idx = (IndexElement *)bsearch(&key, avx->data.data, avx->size / 2,
2 * sizeof(int), s_v_comp);
if (idx) {
int offset;
offset = ntohl(idx->offset);
if (offset >= 0 && offset < avs->data.size) {
cl_errno = CDA_OK;
return (char *)(avs->data.data) + offset;
}
else {
cl_errno = CDA_EINTERNAL; /* this is a bad data inconsistency! */
return NULL;
}
}
else {
/* we don't allow regions with missing annotations, so this must be an index error */
cl_errno = CDA_EIDXORNG;
return NULL;
}
}
else
return NULL;
}
/**
* Gets the value associated with the instance of the given s-attribute
* that occurs at the specified corpus position.
*
* @param struc The s-attribute to search through.
* @param position The corpus position being queried.
* @return The value of the instance of the s-attribute,
* or NULL for error.
*/
char *
structure_value_at_position(Attribute *struc, int position)
{
int snum = -1;
if ((struc == NULL) ||
(!get_num_of_struc(struc, position, &snum)))
return NULL;
else
return cl_struc2str(struc, snum);
}
/* ================================================== ALIGNMENT ATTRIBUTES */
/**
* Gets the id number of the alignment at the specified corpus position.
*
* For use with non-extended alignments. Requires members of the ALIGN
* component as arguments.
*
* Not an exported function!
*
* {Query:am I correct that "position" here means a cpos?? -- AH}
* {If I'm not, other docblocks in cdaccess also have errors}
*
* @see cl_cpos2alg
* @see get_extended_alignment
*
* @param data The data member of a CompAlignData component.
* @param size The size member of the same CompAlignData component.
* @param position The corpus position to look at.
* @return The id of the alignment at this corpus position,
* or -1 for error.
*/
int
get_alignment(int *data, int size, int position) /* ALIGN component */
{
int nr;
int mid, high, low, comp;
int max = size/2;
/* organisation of ALIGN component is
source boundary #1
target boundary #1
source boundary #2
target boundary #2
...
*/
low = 0;
nr = 0;
high = max - 1;
while (low <= high) {
nr++;
if (nr > 100000) {
Rprintf("Binary search in get_alignment failed\n");
return -1;
}
mid = (low + high)/2;
comp = position - ntohl(data[mid*2]);
if (comp == 0)
return mid;
else if (comp > 0) {
if ((mid*2 < size) && (position < ntohl(data[(mid+1)*2])))
return mid;
else
low = mid + 1;
}
else if (mid == low) {
/* fail; */
return -1;
}
else /* comp < 0 */
high = mid - 1;
}
return -1;
}
/**
* Gets the id number of the alignment at the specified corpus position.
*
* For use with extended alignments. Requires members of the XALIGN
* component as arguments.
*
* Not an exported function!
*
*
* @see cl_cpos2alg
* @see get_alignment
*
* @param data The data member of a CompXAlignData component.
* @param size The size member of the same CompXAlignData component.
* @param position The corpus position to look at.
* @return The id of the alignment at this corpus position,
* or -1 for error.
*/
int
get_extended_alignment(int *data, int size, int position) /* XALIGN component */
{
int nr;
int mid, high, low, start, end;
int max = size/4;
/* organisation of XALIGN component is
source region #1 start
source region #1 end
target region #1 start
target region #1 end
source region #2 start
...
*/
low = 0;
nr = 0;
high = max - 1;
while (low <= high) {
nr++;
if (nr > 100000) {
Rprintf("Binary search in get_extended_alignment_item failed\n");
return -1;
}
mid = (low + high)/2;
start = ntohl(data[mid*4]);
end = ntohl(data[mid*4 + 1]);
if (start <= position) {
if (position <= end) {
return mid; /* return nr of alignment region */
}
else {
low = mid + 1;
}
}
else {
high = mid - 1;
}
}
return CDA_EALIGN; /* high < low --> search failed */
}
/**
* Gets the corpus positions of an alignment on the given align-attribute.
*
* This is for old-style alignments only: it doesn't (can't) deal with
* extended alignments. Depracated: use cl_alg2cpos instead (but note its
* parameters are not identical).
*
* @see cl_alg2cpos.
*
* @param attribute The align-attribute to look on.
* @param position The corpus position {??} of the alignment whose positions are wanted.
* @param source_corpus_start Location to put source corpus start position.
* @param source_corpus_end Location to put source corpus end position.
* @param aligned_corpus_start Location to put target corpus start position.
* @param aligned_corpus_end Location to put target corpus end position.
* @return Boolean: true = all OK, false = problem.
*/
int
cl_cpos2alg2cpos_oldstyle(Attribute *attribute, /* accesses alignment attribute */
int position,
int *source_corpus_start,
int *source_corpus_end,
int *aligned_corpus_start,
int *aligned_corpus_end)
{
int *val;
int alg; /* nr of alignment region */
Component *align_data;
check_arg(attribute, ATT_ALIGN, cl_errno);
*source_corpus_start = -1;
*aligned_corpus_start = -1;
*source_corpus_end = -1;
*aligned_corpus_end = -1;
align_data = ensure_component(attribute, CompAlignData, 0);
if (align_data == NULL) {
cl_errno = CDA_ENODATA;
return 0;
}
alg = get_alignment(align_data->data.data,
align_data->size,
position);
if (alg >= 0) {
val = align_data->data.data + (alg * 2);
*source_corpus_start = ntohl(val[0]);
*aligned_corpus_start = ntohl(val[1]);
if (val + 3 - align_data->data.data >= align_data->size) {
*source_corpus_end = -1;
*aligned_corpus_end = -1;
}
else {
*source_corpus_end = ntohl(val[2])-1;
*aligned_corpus_end = ntohl(val[3])-1;
}
cl_errno = CDA_OK;
return 1;
}
else {
cl_errno = CDA_EPOSORNG;
return 0;
}
assert("Not reached" && 0);
return 0;
}
/**
* Checks whether an attribute's XALIGN component exists,
* that is, whether or not it has extended alignment.
*
* @param attribute An align-attribute.
* @return Boolean.
*/
int
cl_has_extended_alignment(Attribute *attribute)
{
ComponentState xalign;
check_arg(attribute, ATT_ALIGN, cl_errno);
xalign = component_state(attribute, CompXAlignData);
if ((xalign == ComponentLoaded) || (xalign == ComponentUnloaded)) {
return 1; /* XALIGN component exists */
}
else {
return 0;
}
}
/**
* Gets the id number of alignments on this align-attribute
*
* This is equal to the maximum alignment on this attribute.
*
* @param attribute An align-attribute.
* @return The number of alignments on this attribute.
*/
int
cl_max_alg(Attribute *attribute)
{
Component *align_data;
/* call to cl_has_extended_alignment subsumes check_arg() */
if (! cl_has_extended_alignment(attribute)) {
align_data = ensure_component(attribute, CompAlignData, 0);
if (align_data == NULL) {
cl_errno = CDA_ENODATA;
return cl_errno;
}
cl_errno = CDA_OK;
return (align_data->size / 2) - 1; /* last alignment boundary doesn't correspond to region */
}
else {
align_data = ensure_component(attribute, CompXAlignData, 0);
if (align_data == NULL) {
cl_errno = CDA_ENODATA;
return cl_errno;
}
cl_errno = CDA_OK;
return (align_data->size / 4);
}
}
/**
* Gets the id number of the alignment at the specified corpus position.
*
* @param attribute The align-attribute to look on.
* @param cpos The corpus position to look at.
* @return The id number of the alignment at this position,
* or a negative int error code.
*/
int
cl_cpos2alg(Attribute *attribute, int cpos)
{
int alg;
Component *align_data;
/* call to cl_has_extended_alignment subsumes check_arg() */
if (! cl_has_extended_alignment(attribute)) {
align_data = ensure_component(attribute, CompAlignData, 0);
if (align_data == NULL) {
cl_errno = CDA_ENODATA;
return cl_errno;
}
alg = get_alignment(align_data->data.data,
align_data->size,
cpos);
if (alg >= 0) {
cl_errno = CDA_OK;
return alg;
}
else {
cl_errno = CDA_EPOSORNG; /* old alignment files don't allow gaps -> index error */
return cl_errno;
}
}
else {
align_data = ensure_component(attribute, CompXAlignData, 0);
if (align_data == NULL) {
cl_errno = CDA_ENODATA;
return cl_errno;
}
alg = get_extended_alignment(align_data->data.data,
align_data->size,
cpos);
if (alg >= 0) {
cl_errno = CDA_OK;
return alg;
}
else {
cl_errno = CDA_EALIGN;
return alg; /* not a real error (just an "exception" condition) */
}
}
}
/**
* Gets the corpus positions of an alignment on the given align-attribute.
*
* Note that four corpus positions are retrieved, into the addresses
* given as parameters.
*
* @param attribute The align-attribute to look on.
* @param alg The ID of the alignment whose positions are wanted.
* @param source_region_start Location to put source corpus start position.
* @param source_region_end Location to put source corpus end position.
* @param target_region_start Location to put target corpus start position.
* @param target_region_end Location to put target corpus end position.
* @return Boolean: true = all OK, false = problem.
*/
int
cl_alg2cpos(Attribute *attribute,
int alg,
int *source_region_start,
int *source_region_end,
int *target_region_start,
int *target_region_end)
{
int *val, size;
Component *align_data;
*source_region_start = -1;
*target_region_start = -1;
*source_region_end = -1;
*target_region_end = -1;
/* call to cl_has_extended_alignment subsumes check_arg() */
if (! cl_has_extended_alignment(attribute)) {
align_data = ensure_component(attribute, CompAlignData, 0);
if (align_data == NULL) {
cl_errno = CDA_ENODATA;
return 0;
}
size = (align_data->size / 2) - 1; /* last alignment boundary doesn't correspond to region */
if ((alg < 0) || (alg >= size)) {
cl_errno = CDA_EIDXORNG;
return 0;
}
val = align_data->data.data + (alg * 2);
*source_region_start = ntohl(val[0]);
*target_region_start = ntohl(val[1]);
*source_region_end = ntohl(val[2]) - 1;
*target_region_end = ntohl(val[3]) - 1;
cl_errno = CDA_OK;
return 1;
}
else {
align_data = ensure_component(attribute, CompXAlignData, 0);
if (align_data == NULL) {
cl_errno = CDA_ENODATA;
return 0;
}
size = align_data->size / 4;
if ((alg < 0) || (alg >= size)) {
cl_errno = CDA_EIDXORNG;
return 0;
}
val = align_data->data.data + (alg * 4);
*source_region_start = ntohl(val[0]);
*source_region_end = ntohl(val[1]);
*target_region_start = ntohl(val[2]);
*target_region_end = ntohl(val[3]);
cl_errno = CDA_OK;
return 1;
}
}
/* ================================================== DYNAMIC ATTRIBUTES */
/**
* Calls a dynamic attribute.
*
* This is the attribute access function for dynamic attributes.
*
* @param attribute The (dynamic) attribute in question.
* @param dcr Location for the result (*int or *char).
* @param args Location of the parameters (of *int or *char).
* @param nr_args Number of parameters.
* @return Boolean: True for all OK, false for error.
*/
int
cl_dynamic_call(Attribute *attribute,
DynCallResult *dcr,
DynCallResult *args,
int nr_args)
{
char call[CL_MAX_LINE_LENGTH];
char istr[32];
int i, k, ap, ins;
FILE *pipe;
/* DynCallResult arg; */
int argnum, val;
DynArg *p;
char c;
check_arg(attribute, ATT_DYN, cl_errno);
if ((args == NULL) || (nr_args <= 0))
goto error;
p = attribute->dyn.arglist;
argnum = 0;
while ((p != NULL) && (argnum < nr_args)) {
/* arg = args[argnum]; */
if ((p->type == args->type) ||
((p->type == ATTAT_POS) && (args->type == ATTAT_INT))) {
p = p->next;
argnum++;
}
else if (p->type == ATTAT_VAR) {
argnum++;
}
else
goto error;
}
if (((p == NULL) && (argnum == nr_args)) ||
((p != NULL) && (p->type == ATTAT_VAR))) {
/* everything should be OK then. */
/* build the call string */
i = 0; ins = 0;
while ((c = attribute->dyn.call[i]) != '\0') {
if ((c == '$') && isdigit(attribute->dyn.call[i+1])) {
/* reference */
i++;
val = 0;
while (isdigit(attribute->dyn.call[i])) {
val = val * 10 + attribute->dyn.call[i] - '0';
i++;
}
/* find the corresponding argument in the definition of args */
if ((val > 0) && (val <= nr_args)) {
p = attribute->dyn.arglist;
k = val - 1; /* 0 .. max. nr_args-1 */
ap = 0;
while ((p != NULL) && (p->type != ATTAT_VAR) && (k > 0)) {
p = p->next;
ap++;
k--;
}
if (p != NULL) {
assert(ap < nr_args);
if (p->type == ATTAT_VAR) {
/* put all args >= ap into the call string */
for (; ap < nr_args; ap++)
switch (args[ap].type) {
case ATTAT_STRING:
for (k = 0; args[ap].value.charres[k]; k++)
call[ins++] = args[ap].value.charres[k];
break;
case ATTAT_INT:
case ATTAT_POS:
sprintf(istr, "%d", args[ap].value.intres);
for (k = 0; istr[k]; k++)
call[ins++] = istr[k];
break;
case ATTAT_FLOAT:
sprintf(istr, "%f", args[ap].value.floatres);
for (k = 0; istr[k]; k++)
call[ins++] = istr[k];
break;
case ATTAT_NONE:
case ATTAT_VAR:
case ATTAT_PAREF:
default:
goto error;
break;
}
}
else {
/* just put arg ap into the call string */
switch (args[ap].type) {
case ATTAT_STRING:
for (k = 0; args[ap].value.charres[k]; k++)
call[ins++] = args[ap].value.charres[k];
break;
case ATTAT_INT:
case ATTAT_POS:
sprintf(istr, "%d", args[ap].value.intres);
for (k = 0; istr[k]; k++)
call[ins++] = istr[k];
break;
case ATTAT_FLOAT:
sprintf(istr, "%f", args[ap].value.floatres);
for (k = 0; istr[k]; k++)
call[ins++] = istr[k];
break;
case ATTAT_NONE:
case ATTAT_VAR:
case ATTAT_PAREF:
default:
goto error;
break;
}
}
}
else
goto error;
}
else
goto error;
}
else {
call[ins++] = c;
call[ins] = '\0'; /* for debugging */
i++; /* get next char */
}
}
call[ins++] = '\0';
/* Rprintf("Composed dynamic call: \"%s\"\n", call); */
pipe = popen(call, "r");
if (pipe == NULL)
goto error;
dcr->type = attribute->dyn.res_type;
switch (attribute->dyn.res_type) {
case ATTAT_POS: /* convert output to int */
case ATTAT_INT:
if (fscanf(pipe, "%d", &(dcr->value.intres)) == 0)
dcr->value.intres = -1;
break;
case ATTAT_STRING: /* copy output */
fgets(call, CL_MAX_LINE_LENGTH, pipe);
dcr->value.charres = (char *)cl_strdup(call);
break;
case ATTAT_FLOAT:
if (fscanf(pipe, "%lf", &(dcr->value.floatres)) == 0)
dcr->value.floatres = 0.0;
break;
case ATTAT_NONE:
case ATTAT_VAR: /* not possible */
case ATTAT_PAREF:
default:
goto error;
break;
}
pclose(pipe);
cl_errno = CDA_OK;
return 1;
}
else
goto error;
error:
cl_errno = CDA_EARGS;
dcr->type = ATTAT_NONE;
return 0;
}
/**
* Count the number of arguments on a dynamic attribute's argument list.
*
* @param attribute pointer to the Attribute object to analyse; it must
* be a dynamic attribute.
* @return integer specifying the number of arguments;
* a negative integer is returned if for any argument
* on dyn.arglist, the type is equal to ATTAT_VAR
*/
int
cl_dynamic_numargs(Attribute *attribute)
{
int nr;
DynArg *arg;
check_arg(attribute, ATT_DYN, cl_errno);
nr = 0;
for (arg = attribute->dyn.arglist; arg != NULL; arg = arg->next)
if (arg->type == ATTAT_VAR) {
nr = -nr;
break;
}
else
nr++;
cl_errno = CDA_OK;
return nr;
assert("Not reached" && 0);
return 0;
}
/* ================================================== EOF */
|
myoKun345/RcppCWB
|
src/cwb/cl/storage.c
|
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
void Rprintf(const char *, ...);
#include <sys/types.h>
#ifndef __MINGW__
#include <sys/mman.h>
#else
#include "windows-mmap.h"
#endif
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include "globals.h"
#include "endian2.h"
#include "macros.h"
#include "storage.h"
/**
* Flags used in calls to mmap.
* TODO: actually, only used when calling mmap() for read: should be renamed to indicate this.
* @see mmapfile
*/
#if defined(__FreeBSD__)
#define MMAPFLAGS MAP_FILE | MAP_PRIVATE
#elif defined(__svr4__)
#define MMAPFLAGS MAP_PRIVATE | MAP_NORESERVE
#else
#define MMAPFLAGS MAP_PRIVATE
#endif
#define MMAP_EMPTY_LEN 8 /* can't mmap() 0 bytes, so mmap() MMAP_EMPTY_LEN bytes beyond end-of-file for empty files */
/* ============================================================ */
/* TODO Nwrite / Nread belong elsewhere surely? */
/**
* Writes a 32-bit integer to file, converting to network byte order.
*
* Other than the byte order conversion, amd the fact that it exits
* the program upon error (so the user of this function can assume
* success), this is the same as
*
* fwrite(&val, sizeof(int), 1, fd) .
*
* @param val The integer to write.
* @param fd File handle to write to.
*/
void
NwriteInt(int val, FILE *fd)
{
int word;
word = htonl(val);
if (1 != fwrite(&word, sizeof(int), 1, fd)) {
perror("File write error");
exit(1);
}
}
/**
* Reads a 32-bit integer from file, converting from network byte order.
*
* This function does all the error checking for you, and will abort
* the program if the int cannot be read.
*
* @param val Location to put the resulting int.
* @param fd File handle to read from
*/
void
NreadInt(int *val, FILE *fd)
{
int word;
if (1 != fread(&word, sizeof(int), 1, fd)) {
perror("File read error");
exit(1);
}
*val = ntohl(word);
}
/**
* Writes an array of 32-bit integers to file, converting to network byte order.
*
* Other than the byte order conversion, this is the same as
* fwrite(vals, sizeof(int), nr_vals, fd) .
*
* @param vals Pointer to the location of the block of integers to write.
* @param nr_vals Number of integers to write.
* @param fd File handle to write to.
*/
void
NwriteInts(int *vals, int nr_vals, FILE *fd)
{
int word, k;
/* I strongly believe in buffered IO (;-) */
for (k = 0; k < nr_vals; k++) {
word = htonl(vals[k]);
if (1 != fwrite(&word, sizeof(int), 1, fd)) {
perror("File write error");
exit(1);
}
}
}
/**
* Reads an array of 32-bit integers from file, converting from network byte order.
*
* This function does all the error checking for you, and will abort
* the program if the requested number of ints cannot be read.
*
* @param vals Pointer to location to put the resulting array of ints.
* (This memory must have been allocated by the caller.)
* @param nr_vals Number of integers to read.
* @param fd File handle to read from
*/
void
NreadInts(int *vals, int nr_vals, FILE *fd)
{
int word, k;
/* I strongly believe in buffered IO (;-) */
for (k = 0; k < nr_vals; k++) {
if (1 != fread(&word, sizeof(int), 1, fd)) {
perror("File read error");
exit(1);
}
vals[k] = ntohl(word);
}
}
/* ============================================================ */
/**
* Clears all fields in a MemBlob, regardless of their usage,
* and puts the blob back to its virginal state.
*
* Note that it doesn't free blob->data - just sets it to NULL.
*/
void
init_mblob(MemBlob *blob)
{
assert((blob != NULL) && "CL Memblob: init_mblob(): You can't pass a NULL blob!");
blob->data = NULL;
blob->size = 0;
blob->item_size = 0;
blob->nr_items = 0;
blob->allocation_method = UNALLOCATED;
blob->writeable = 0;
blob->changed = 0;
blob->fname = NULL;
blob->fsize = 0;
blob->offset = 0;
}
/**
* Allocates memory for a blob of the requested size, using malloc(2).
*
* A block of memory holding nr_items of size item_size is created
* in the specified MemBlob.
*
* @param blob The MemBlob in which to place the memory.
* @param nr_items The number of items the MemBlob is to hold as data.
* @param item_size The size of one item.
* @param clear_blob boolean: if true, all bytes in the data space will be initialised to 0
* @return boolean: true 1 if OK, false on error
*/
int
alloc_mblob(MemBlob *blob, int nr_items, int item_size, int clear_blob)
{
int size;
assert( (blob != NULL) && "CL MemBlob: alloc_mblob(): You can't pass a NULL blob!");
assert( (item_size >= 0) && "CL MemBlob: alloc_mblob(): item_size must be >= 0!");
assert( (nr_items > 0) && "CL MemBlob: alloc_mblob(): nr_items must be > 0!");
blob->item_size = item_size;
blob->nr_items = nr_items;
if (item_size == SIZE_BIT) {
size = nr_items / 8;
if (size * 8 < nr_items) {
size++; /* make room for 'extra' bits */
}
}
else {
size = nr_items * item_size;
}
blob->size = size;
if (clear_blob) {
blob->data = (int *) cl_calloc(size, 1);
}
else {
blob->data = (int *) cl_malloc(size);
}
blob->allocation_method = MALLOCED;
blob->writeable = 1;
blob->changed = 0;
blob->fname = NULL;
blob->fsize = 0;
blob->offset = 0;
return 1;
}
/**
* Frees the memory used by a MemBlob.
*
* This works regardless of the method used to allocate the blob.
*/
void
mfree(MemBlob *blob)
{
unsigned int map_len;
assert((blob != NULL) && "You can't pass a NULL blob to mfree");
if (blob->data != NULL) {
switch (blob->allocation_method) {
case UNALLOCATED:
Rprintf("CL MemBlob:mfree(): Blob flag is UNALLOCATED, but data present -- no free\n");
break;
case MMAPPED:
map_len = (blob->size > 0) ? blob->size : MMAP_EMPTY_LEN;
if (munmap((void *)blob->data, map_len) < 0)
perror("CL MemBlob:munmap()");
break;
case MALLOCED:
cl_free(blob->data);
break;
default:
assert("CL MemBlob:mfree(): Illegal memory storage class" && 0);
break;
}
cl_free(blob->fname);
init_mblob(blob);
}
else {
if (blob->allocation_method != UNALLOCATED)
Rprintf("CL MemBlob:mfree(): No data, but MemBlob flag isn't UNALLOCATED\n");
}
}
/**
* Maps a file into memory in either read or write mode.
*
* @param filename Name of the file to map.
* @param len_ptr The number of bytes the returned pointer points to.
* @param mode Can be either "r", "w", "rb" or "wb". (a "+" can be used too, but is ignored.)
* If mode is "r", the amount of memory allocated (size of file) is placed in len_ptr.
* If mode is "w", len_ptr is taken as an input parameter (*len_ptr bytes
* are allocated).
* @return The contents of file in filename as a pointer to a memory area.
*/
void *
mmapfile(char *filename, size_t *len_ptr, char *mode)
{
struct stat stat_buf;
int fd;
int binflag = 0; /* set to O_BINARY if we want to use the binary flag with open() */
void *space;
size_t map_len; /* should probably be off_t (for file sizes) rather than size_t (for size of objects), according to SUS */
/* allow for: r+b, w+b, rb+, wb+ */
binflag = (mode[1] == 'b' || (mode[1] == '+' && mode[2] == 'b') ) ? O_BINARY : 0;
space = NULL;
switch(mode[0]) {
case 'r':
fd = open(filename, O_RDONLY|binflag);
if (fd == EOF) {
Rprintf("CL MemBlob:mmapfile(): Can't open file %s ... \n\tReason: ", filename);
perror(NULL);
}
else if(fstat(fd, &stat_buf) == EOF) {
Rprintf("CL MemBlob:mmapfile(): Can't fstat() file %s ... \n\tReason: ", filename);
perror(NULL);
}
else {
*len_ptr = stat_buf.st_size;
/* if file is empty, mmap() beyond end of file, but report empty size to CL */
map_len = (stat_buf.st_size > 0) ? stat_buf.st_size : MMAP_EMPTY_LEN;
space = mmap(NULL, map_len, PROT_READ, MMAPFLAGS, fd, 0);
}
if (fd != EOF)
close(fd);
break;
case 'w':
/* if the file does not exist, create; then mmap it, unless both open/create were unsuccessful. */
if ((fd = open(filename, O_RDWR|O_CREAT|binflag, 0666)) == EOF)
fd = creat(filename, 0666);
if (fd == EOF) {
Rprintf("CL MemBlob:mmapfile(): Can't create file %s ...\n\tReason: ", filename);
perror(NULL);
}
else {
/* scroll to the len_ptr'th byte, then overwrite the last integer with a random integer (why? not sure -- AH),
* then rewind file */
lseek(fd, *len_ptr - sizeof(int), SEEK_SET);
write(fd, &fd, sizeof(int));
lseek(fd, 0, SEEK_SET);
space = mmap(NULL, *len_ptr, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
}
if (fd != EOF)
close(fd);
break;
default:
Rprintf("CL MemBlob:mmapfile(): Mode '%s' is not supported ...\n", mode);
}
if (space == MAP_FAILED) {
Rprintf("CL MemBlob:mmapfile(): Can't mmap() file %s ...\n"
"\tYou have probably run out of memory / address space!\n"
"\tError Message: ",
filename);
perror(NULL);
space = NULL;
}
return space;
}
/**
* Maps a file into memory.
*
* This function does virtually the same as mmapfile (same parameters, same return
* value), but the memory is taken with malloc(3), not with mmap(2).
*
* @see mmapfile
*/
void *
mallocfile(char *filename, size_t *len_ptr, char *mode)
{
struct stat stat_buf;
int fd;
int binflag = 0; /* set to O_BINARY if we want to use the binary flag with open() */
void *space;
/* allow for: r+b, w+b, rb+, wb+, rb, wb */
binflag = (mode[1] == 'b' || (mode[1] == '+' && mode[2] == 'b') ) ? O_BINARY : 0;
space = NULL;
switch(mode[0]) {
case 'r':
fd = open(filename, O_RDONLY|binflag);
if (fd == EOF) {
Rprintf("CL MemBlob:mallocfile(): can't open %s -- ", filename);
perror(NULL);
}
else if(fstat(fd, &stat_buf) == EOF) {
Rprintf("CL MemBlob:mallocfile(): can't stat %s -- ", filename);
perror(NULL);
}
else {
*len_ptr = stat_buf.st_size;
space = (void *)cl_malloc(*len_ptr);
if (read(fd, space, *len_ptr) != *len_ptr) {
Rprintf("CL MemBlob:mallocfile(): couldn't read file contents -- ");
perror(NULL);
cl_free(space);
space = NULL;
}
}
if (fd != EOF)
close(fd);
break;
case 'w':
if ((fd = open(filename, O_RDWR|O_CREAT|binflag, 0666)) == EOF)
fd = creat(filename, 0666);
if(fd == EOF) {
Rprintf("CL MemBlob:mallocfile(): can't open/create %s for writing -- ", filename);
perror(NULL);
}
else {
space = cl_malloc(*len_ptr);
if (write(fd, space, *len_ptr) != *len_ptr) {
Rprintf("CL MemBlob:mallocfile(): couldn't write file -- ");
perror(NULL);
cl_free(space);
space = NULL;
}
}
if (fd != EOF)
close(fd);
break;
default:
Rprintf("CL MemBlob:mallocfile(): mode %s is not supported\n", mode);
}
return space;
}
/**
* Reads the contents of a file into memory represented by blob.
*
* You can choose the memory allocation method - MMAPPED is faster, but
* writeable areas of memory should be taken with care. MALLOCED is
* slower (and far more space consuming), but writing data into malloced
* memory is no problem.
*
* In Windows, the read is always binary-mode.
*
* @param filename The file to read in.
* @param allocation_method MMAPPED or MALLOCED (see function description)
* @param item_size This is used for MemBlob access methods, it
* is simply copied into the MemBlob data
* structure.
* @param blob The MemBlob to read the file into. It must not
* be in use -- the fields are overwritten.
* @return 0 on failure, 1 if everything went fine.
*/
int
read_file_into_blob(char *filename,
int allocation_method,
int item_size,
MemBlob *blob)
{
int result;
assert("CL MemBlob:read_file_into_blob(): You must not pass a NULL blob!" && (blob != NULL));
blob->item_size = item_size;
blob->allocation_method = allocation_method;
blob->writeable = 0;
blob->changed = 0;
if (allocation_method == MMAPPED)
blob->data = (int *)mmapfile(filename, &(blob->size), "rb");
else if (allocation_method == MALLOCED)
blob->data = (int *)mallocfile(filename, &(blob->size), "rb");
else {
Rprintf("CL MemBlob:read_file_into_blob(): allocation method %d is not supported\n", allocation_method);
return 0;
}
if (blob->data == NULL) {
result = 0;
blob->nr_items = 0;
blob->allocation_method = UNALLOCATED;
}
else {
result = 1;
blob->nr_items = (item_size == SIZE_BIT) ? blob->size * 8
: blob->size / item_size;
}
return result;
}
/**
* Writes the data stored in a blob to file.
*
* Note that here we are writing to a new file: we are *not*
* writing back to the file the data came from, if MMAPPED.
*
* In Windows, the write is always binary-mode.
*
* @param filename The file to write to.
* @param blob The MemBlob to write to file.
* @param convert_to_nbo boolean: if true, data is converted to
* network byte order before it's written.
* @return 0 on failure, 1 if everything went fine.
*/
int
write_file_from_blob(char *filename,
MemBlob *blob,
int convert_to_nbo)
{
int result = 0;
FILE *fd;
assert("CL MemBlob:write_file_from_blob(): You must not pass a NULL blob!" && (blob != NULL));
blob->changed = 0;
if ((blob->data == NULL) || (blob->size == 0)) {
Rprintf("CL MemBlob:write_file_from_blob(): no data in blob, nothing to write...\n");
result = 0;
}
else {
switch (blob->allocation_method) {
case UNALLOCATED:
Rprintf("CL MemBlob:write_file_from_blob(): tried to write unallocated blob...\n");
result = 0;
break;
case MMAPPED:
case MALLOCED:
if ((fd = fopen(filename, "wb")) == NULL) {
Rprintf("CL MemBlob:write_file_from_blob(): Can't open output file %s\n", filename);
result = 0;
}
else {
if (convert_to_nbo)
NwriteInts((int *)blob->data, blob->size/4, fd);
else
fwrite(blob->data, 1, blob->size, fd);
fclose(fd);
result = 1;
}
break;
default:
Rprintf("CL MemBlob:write_file_from_blob(): unsupported allocation method # %d...\n", blob->allocation_method);
result = 0;
break;
}
}
return result;
}
|
myoKun345/RcppCWB
|
src/cwb/utils/_cwb_huffcode.c
|
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
/*
* MODIFICATIONS:
* - progrname commented out
* - function 'usage' and placeholder for usage deleted
* - Rcpp.h included
* - includes moved to extern "C" {}
* - all uses of 'protocol' commented out
* - exit(1); replaced by return 1;
* - return value of decode_check_huff turned into 'int'
* - corpus_id is passed explicitly into decode_check_huff
*/
void Rprintf(const char *, ...); /* alternative to include R_ext/Print.h */
#include "../cl/globals.h"
#include "../cl/cl.h"
#include "../cl/corpus.h"
#include "../cl/attributes.h"
#include "../cl/storage.h"
#include "../cl/bitio.h"
#include "../cl/macros.h"
/** Level of progress-info (inc compression protocol) message output: 0 = none. */
int do_protocol = 1;
/** File handle for this program's progress-info output: always stdout */
/* FILE *protocol; */ /* " = stdout;" init moved to main() for Gnuwin32 compatibility */
/* ---------------------------------------------------------------------- */
/* char *progname; */
extern Corpus *corpus;
char *corpus_id = NULL;
int debug = 0;
/* ---------------------------------------------------------------------- */
/**
* Prints a binary representation of an integer to a stream.
*
* @param i Integer to print
* @param width Number of bits in the integer
* @param stream Where to print to.
*/
void
bprintf(unsigned int i, int width, FILE *stream)
{
putc((width <= 31) ? ' ' : (i & 1<<31 ? '1' : '0'), stream);
putc((width <= 30) ? ' ' : (i & 1<<30 ? '1' : '0'), stream);
putc((width <= 29) ? ' ' : (i & 1<<29 ? '1' : '0'), stream);
putc((width <= 28) ? ' ' : (i & 1<<28 ? '1' : '0'), stream);
putc((width <= 27) ? ' ' : (i & 1<<27 ? '1' : '0'), stream);
putc((width <= 26) ? ' ' : (i & 1<<26 ? '1' : '0'), stream);
putc((width <= 25) ? ' ' : (i & 1<<25 ? '1' : '0'), stream);
putc((width <= 24) ? ' ' : (i & 1<<24 ? '1' : '0'), stream);
putc('.', stream);
putc((width <= 23) ? ' ' : (i & 1<<23 ? '1' : '0'), stream);
putc((width <= 22) ? ' ' : (i & 1<<22 ? '1' : '0'), stream);
putc((width <= 21) ? ' ' : (i & 1<<21 ? '1' : '0'), stream);
putc((width <= 20) ? ' ' : (i & 1<<20 ? '1' : '0'), stream);
putc((width <= 19) ? ' ' : (i & 1<<19 ? '1' : '0'), stream);
putc((width <= 18) ? ' ' : (i & 1<<18 ? '1' : '0'), stream);
putc((width <= 17) ? ' ' : (i & 1<<17 ? '1' : '0'), stream);
putc((width <= 16) ? ' ' : (i & 1<<16 ? '1' : '0'), stream);
putc('.', stream);
putc((width <= 15) ? ' ' : (i & 1<<15 ? '1' : '0'), stream);
putc((width <= 14) ? ' ' : (i & 1<<14 ? '1' : '0'), stream);
putc((width <= 13) ? ' ' : (i & 1<<13 ? '1' : '0'), stream);
putc((width <= 12) ? ' ' : (i & 1<<12 ? '1' : '0'), stream);
putc((width <= 11) ? ' ' : (i & 1<<11 ? '1' : '0'), stream);
putc((width <= 10) ? ' ' : (i & 1<<10 ? '1' : '0'), stream);
putc((width <= 9) ? ' ' : (i & 1<<9 ? '1' : '0'), stream);
putc((width <= 8) ? ' ' : (i & 1<<8 ? '1' : '0'), stream);
putc('.', stream);
putc((width <= 7) ? ' ' : (i & 1<<7 ? '1' : '0'), stream);
putc((width <= 6) ? ' ' : (i & 1<<6 ? '1' : '0'), stream);
putc((width <= 5) ? ' ' : (i & 1<<5 ? '1' : '0'), stream);
putc((width <= 4) ? ' ' : (i & 1<<4 ? '1' : '0'), stream);
putc((width <= 3) ? ' ' : (i & 1<<3 ? '1' : '0'), stream);
putc((width <= 2) ? ' ' : (i & 1<<2 ? '1' : '0'), stream);
putc((width <= 1) ? ' ' : (i & 1<<1 ? '1' : '0'), stream);
putc((width <= 0) ? ' ' : (i & 1 ? '1' : '0'), stream);
}
/* ---------------------------------------------------------------------- */
/**
* Dumps the specified heap of memory to the program output stream.
*
* @see protocol
* @param heap Location of the heap to dump.
* @param heap_size Number of nodes in the heap.
* @param node Heap at which to begin dumping.
* @param indent How many tabs to indent the start of each line.
*
*/
void
dump_heap(int *heap, int heap_size, int node, int indent)
{
/* int i; */
if (node <= heap_size) {
/* for (i = 0; i < indent * 3; i++) putc((i % 3) == 0 ? '|' : ' ', protocol); */
Rprintf("Node %d (p: %d, f: %d)\n", node, heap[node-1], heap[heap[node-1]]);
dump_heap(heap, heap_size, 2 * node, indent + 1);
dump_heap(heap, heap_size, 2 * node + 1, indent + 1);
}
}
/**
* Prints a description of the specified heap of memory to the program output stream.
*
* @see protocol
* @param heap Location of the heap to print.
* @param heap_size Number of nodes in the heap.
* @param title Title of the heap to print.
*/
void
print_heap(int *heap, int heap_size, char *title)
{
/* int node, depth; */
/* node = 1; */
/* depth = 0; */
Rprintf("\nDump of %s (size %d)\n\n", title, heap_size);
dump_heap(heap, heap_size, 1, 0);
Rprintf("");
}
/**
* Sifts the heap into order.
*
* @param heap Location of the heap to sift.
* @param heap_size Number of nodes in the heap.
* @param node Node at which to begin sifting.
*/
static int
sift(int *heap, int heap_size, int node)
{
register int child;
register int tmp;
int swaps = 0;
child = node * 2;
/* we address the heap in the following manner: when we start
* indices at 1, the left child is at 2i, and the right child is at
* 2i+1. So we maintain this scheme and decrement just before
* addressing the array.
*
* left child in 2*node, right child in 2*node + 1, parent in
* node */
while (child <= heap_size) {
if ((child < heap_size) &&
(heap[heap[child]] < heap[heap[child-1]])) {
/* select right branch in heap[child+1-1] */
child++;
}
if (heap[heap[node-1]] > heap[heap[child-1]]) {
/* root is larger than selected child, so we have to swap and
* recurse down */
swaps++;
tmp = heap[child-1];
heap[child-1] = heap[node-1];
heap[node-1] = tmp;
/* recurse downwards */
node = child;
child = node * 2;
}
else
/* heap constraints seem to be in order */
break;
}
return swaps;
}
/**
* Writes a Huffman code descriptor to file.
*
* @param filename Path to file where descriptor is to be saved.
* @param hc Pointer to the descriptor block to save.
* @return Boolean: true for all OK, false for error.
*/
int
WriteHCD(char *filename, HCD *hc)
{
FILE *fd;
if ((fd = fopen(filename, "w")) == NULL) {
perror(filename);
return 0;
}
else {
NwriteInt(hc->size, fd);
NwriteInt(hc->length, fd);
NwriteInt(hc->min_codelen, fd);
NwriteInt(hc->max_codelen, fd);
NwriteInts(hc->lcount, MAXCODELEN, fd);
NwriteInts(hc->symindex, MAXCODELEN, fd);
NwriteInts(hc->min_code, MAXCODELEN, fd);
assert(hc->symbols);
NwriteInts(hc->symbols, hc->size, fd);
fclose(fd);
return 1;
}
}
/**
* Reads a Huffman compressed sequence from file.
*
* @param filename Path to file where compressed sequence is saved.
* @param hc Pointer to location where the sequence's descriptor block will be loaded to.
* @return Boolean: true for all OK, false for error.
*/
int
ReadHCD(char *filename, HCD *hc)
{
FILE *fd;
if ((fd = fopen(filename, "r")) == NULL) {
perror(filename);
return 0;
}
else {
NreadInt(&hc->size, fd);
NreadInt(&hc->length, fd);
NreadInt(&hc->min_codelen, fd);
NreadInt(&hc->max_codelen, fd);
NreadInts(hc->lcount, MAXCODELEN, fd);
NreadInts(hc->symindex, MAXCODELEN, fd);
NreadInts(hc->min_code, MAXCODELEN, fd);
hc->symbols = (int *)cl_malloc(sizeof(int) * hc->size);
NreadInts(hc->symbols, hc->size, fd);
fclose(fd);
return 1;
}
}
/* should these two functions perhaps be in cl/attributes.h? (prototype of HCD is in attributes.h) or all HCD object in separate module? */
/* ================================================== COMPRESSION */
/**
* Compresses the token stream of a p-attribute.
*
* Three files are created: the compressed token stream, the descriptor block,
* and a sync file.
*
* @param attr The attribute to compress.
* @param hc Location for the resulting Huffmann code descriptor block.
* @param fname Base filename for the resulting files.
*/
int
compute_code_lengths(Attribute *attr, HCD *hc, char *fname)
{
int id, i, h;
/* int nr_codes = 0; */
int *heap = NULL;
unsigned *codelength = NULL; /* was char[], probably to save space; but that's unnecessary and makes gcc complain */
int issued_codes[MAXCODELEN];
int next_code[MAXCODELEN];
long sum_bits;
Rprintf("COMPRESSING TOKEN STREAM of %s.%s\n", corpus_id, attr->any.name);
/* I need the following components:
* - CompCorpus
* - CompCorpusFreqs
* - CompLexicon
* - CompLexiconIdx
* and want to force the CL to use them rather than compressed data.
*/
{
Component *comp;
if ((comp = ensure_component(attr, CompCorpus, 0)) == NULL) {
Rprintf("Computation of huffman codes needs the CORPUS component\n");
return 1;
}
if ((comp = ensure_component(attr, CompLexicon, 0)) == NULL) {
Rprintf("Computation of huffman codes needs the LEXION component\n");
return 1;
}
if ((comp = ensure_component(attr, CompLexiconIdx, 0)) == NULL) {
Rprintf("Computation of huffman codes needs the LEXIDX component\n");
return 1;
}
if ((comp = ensure_component(attr, CompCorpusFreqs, 0)) == NULL) {
Rprintf("Computation of huffman codes needs the FREQS component.\n"
"Run 'makeall -r %s -c FREQS %s %s' in order to create it.\n",
corpus->registry_dir, corpus->registry_name, attr->any.name);
return 1;
}
}
/*
* strongly follows Witten/Moffat/Bell: ``Managing Gigabytes'',
* pp. 335ff.
*/
hc->size = cl_max_id(attr); /* the size of the attribute (nr of items) */
if ((hc->size <= 0) || (cderrno != CDA_OK)) {
cdperror("(aborting) cl_max_id() failed");
return 1;
}
hc->length = cl_max_cpos(attr); /* the length of the attribute (nr of tokens) */
if ((hc->length <= 0) || (cderrno != CDA_OK)) {
cdperror("(aborting) cl_max_cpos() failed");
return 1;
}
hc->symbols = NULL;
hc->min_codelen = 100;
hc->max_codelen = 0;
bzero((char *)hc->lcount, MAXCODELEN * sizeof(int));
bzero((char *)hc->min_code, MAXCODELEN * sizeof(int));
bzero((char *)hc->symindex, MAXCODELEN * sizeof(int));
bzero((char *)issued_codes, MAXCODELEN * sizeof(int));
codelength = (unsigned *)cl_calloc(hc->size, sizeof(unsigned));
/* =========================================== make & initialize the heap */
heap = (int *)cl_malloc(hc->size * 2 * sizeof(int));
for (i = 0; i < hc->size; i++) {
heap[i] = hc->size + i;
heap[hc->size+i] = get_id_frequency(attr, i);
}
/* ============================== PROTOCOL ============================== */
if (do_protocol > 0)
Rprintf("Allocated heap with %d cells for %d items\n\n",
hc->size * 2, hc->size);
if (do_protocol > 2)
print_heap(heap, hc->size, "After Initialization");
/* ============================== PROTOCOL ============================== */
/* ================================================== Phase 1 */
h = hc->size;
/*
* we address the heap in the following manner: when we start array
* indices at 1, the left child is at 2i, and the right child is at
* 2i+1. So we maintain this scheme and decrement just before
* adressing the array.
*/
/*
* construct the initial min-heap
*/
for (i = hc->size/2; i > 0; i--) {
/* do:
* bottom up, left to right,
* for each root of each subtree, sift if necessary
*/
sift(heap, h, i);
}
/* ============================== PROTOCOL ============================== */
if (do_protocol > 2) {
print_heap(heap, hc->size, "Initial Min-Heap");
Rprintf("\n");
}
/* ============================== PROTOCOL ============================== */
/* ================================================== Phase 2 */
/* smallest item at top of heap now, remove the two smallest items
* and sift, find second smallest by removing top and sifting, as
* long as we have more than one root */
while (h > 1) {
int pos[2];
for (i = 0; i < 2; i++) {
/* remove topmost (i.e. smallest) item */
pos[i] = heap[0];
/* remove and sift, to reobtain heap integrity: move ``last''
* item to top of heap and sift */
heap[0] = heap[--h];
sift(heap, h, 1);
}
/* ============================== PROTOCOL ============================== */
if (do_protocol > 3) {
Rprintf("Removed smallest item %d with freq %d\n",
pos[0], heap[pos[0]]);
Rprintf("Removed 2nd smallest item %d with freq %d\n",
pos[1], heap[pos[1]]);
}
/* ============================== PROTOCOL ============================== */
/*
* pos[0] and pos[1] contain pointers to the two smallest items
* now. since h was decremented twice, h and h+1 are now empty and
* become the accumulated freq of pos[i]. The individual
* frequencies are not needed any more, so pointers to h+1 (the
* acc freq) are stored there instead (tricky, since freq cell
* becomes pointer cell). So, what happens here, is to include a
* new element in the heap. */
heap[h] = h+1;
heap[h+1] = heap[pos[0]] + heap[pos[1]]; /* accumulated freq */
heap[pos[0]] = heap[pos[1]] = h+1; /* pointers! */
h++; /* we put a new element into heap */
/*
* now, swap it up until we reobtain heap integrity
*/
{
register int parent, current;
current = h;
parent = current >> 1;
while ((parent > 0) &&
(heap[heap[parent-1]] > heap[heap[current-1]])) {
int tmp;
tmp = heap[parent-1];
heap[parent-1] = heap[current-1];
heap[current-1] = tmp;
current = parent;
parent = current >> 1;
}
}
}
/* ============================== PROTOCOL ============================== */
if (do_protocol > 3)
Rprintf("\n");
/* ============================== PROTOCOL ============================== */
/* ================================================== Phase 3 */
/* compute the code lengths. We don't have any freqs in heap any
* more, only pointers to parents */
heap[0] = -1U;
/* root has a depth of 0 */
heap[1] = 0;
/* we trust in what they say on p. 345 */
for (i = 2; i < hc->size * 2; i++)
heap[i] = heap[heap[i]]+1;
/* collect the lengths */
sum_bits = 0L;
for (i = 0; i < hc->size; i++) {
int cl = heap[i+hc->size];
sum_bits += cl * get_id_frequency(attr, i);
codelength[i] = cl;
if (cl == 0)
continue;
if (cl > hc->max_codelen)
hc->max_codelen = cl;
if (cl < hc->min_codelen)
hc->min_codelen = cl;
hc->lcount[cl]++;
}
/* ============================== PROTOCOL ============================== */
if (do_protocol > 0) {
Rprintf("Minimal code length: %3d\n", hc->min_codelen);
Rprintf("Maximal code length: %3d\n", hc->max_codelen);
Rprintf("Compressed code len: %10ld bits, %10ld (+1) bytes\n\n\n",
sum_bits, sum_bits/8);
}
/* ============================== PROTOCOL ============================== */
if (hc->max_codelen >= MAXCODELEN) {
Rprintf("Error: Huffman codes too long (%d bits, current maximum is %d bits).\n", hc->max_codelen, MAXCODELEN-1);
Rprintf(" Please contact the CWB development team for assistance.\n");
return 1;
}
if ((hc->max_codelen == 0) && (hc->min_codelen == 100)) {
Rprintf("Problem: No output generated -- no items?\n");
/* nr_codes = 0; */
}
else {
hc->min_code[hc->max_codelen] = 0;
for (i = hc->max_codelen-1; i > 0; i--)
hc->min_code[i] = (hc->min_code[i+1] + hc->lcount[i+1]) >> 1;
hc->symindex[hc->min_codelen] = 0;
for (i = hc->min_codelen+1; i <= hc->max_codelen; i++)
hc->symindex[i] = hc->symindex[i-1] + hc->lcount[i-1];
/* ============================== PROTOCOL ============================== */
if (do_protocol > 0) {
int sum_codes = 0;
Rprintf(" CL #codes MinCode SymIdx\n");
Rprintf("----------------------------------------\n");
for (i = hc->min_codelen; i <= hc->max_codelen; i++) {
sum_codes += hc->lcount[i];
Rprintf("%3d %7d %7d %7d\n",
i, hc->lcount[i], hc->min_code[i], hc->symindex[i]);
}
Rprintf("----------------------------------------\n");
Rprintf(" %7d\n", sum_codes);
}
/* ============================== PROTOCOL ============================== */
for (i = 0; i < MAXCODELEN; i++)
next_code[i] = hc->min_code[i];
/* ============================== PROTOCOL ============================== */
if (do_protocol > 1) {
Rprintf("\n");
Rprintf(" Item f(item) CL Bits Code, String\n");
Rprintf("------------------------------------"
"------------------------------------\n");
}
/* ============================== PROTOCOL ============================== */
/* compute and issue codes */
hc->symbols = heap + hc->size;
for (i = 0; i < hc->size; i++) {
/* we store the code for item i in heap[i] */
heap[i] = next_code[codelength[i]];
next_code[codelength[i]]++;
/* ============================== PROTOCOL ============================== */
if (do_protocol > 1) {
Rprintf("%7d %7d %3d %10d ",
i,
get_id_frequency(attr, i),
codelength[i],
codelength[i] * get_id_frequency(attr, i));
/* bprintf(heap[i], codelength[i], protocol); */
Rprintf(" %7d %s\n",
heap[i], get_string_of_id(attr, i));
}
/* ============================== PROTOCOL ============================== */
/* and put the item itself in the second half of the table */
heap[hc->size+hc->symindex[codelength[i]]+issued_codes[codelength[i]]] = i;
issued_codes[codelength[i]]++;
}
/* ============================== PROTOCOL ============================== */
if (do_protocol > 1) {
Rprintf("------------------------------------"
"------------------------------------\n");
}
/* ============================== PROTOCOL ============================== */
/* The work itself -- encode the attribute data */
{
char *path;
char hcd_path[MAX_LINE_LENGTH];
char huf_path[MAX_LINE_LENGTH];
char sync_path[MAX_LINE_LENGTH];
Component *corp;
BFile bfd;
FILE *sync;
int cl, code, pos;
corp = ensure_component(attr, CompCorpus, 0);
assert(corp);
if (fname) {
path = fname;
sprintf(hcd_path, "%s.hcd", path);
sprintf(huf_path, "%s.huf", path);
sprintf(sync_path, "%s.huf.syn", path);
}
else {
path = component_full_name(attr, CompHuffSeq, NULL);
assert(path); /* additonal condition (cderrno == CDA_OK) removed, since component_full_name doesn't (re)set cderrno */
strcpy(huf_path, path);
path = component_full_name(attr, CompHuffCodes, NULL);
assert(path); /* additonal condition (cderrno == CDA_OK) removed, since component_full_name doesn't (re)set cderrno */
strcpy(hcd_path, path);
path = component_full_name(attr, CompHuffSync, NULL);
assert(path); /* additonal condition (cderrno == CDA_OK) removed, since component_full_name doesn't (re)set cderrno */
strcpy(sync_path, path);
}
Rprintf("- writing code descriptor block to %s\n", hcd_path);
if (!WriteHCD(hcd_path, hc)) {
Rprintf("ERROR: writing %s failed. Aborted.\n",
hcd_path);
return 1;
}
Rprintf("- writing compressed item sequence to %s\n", huf_path);
if (!BFopen(huf_path, "w", &bfd)) {
Rprintf("ERROR: can't create file %s\n", huf_path);
perror(huf_path);
return 1;
}
Rprintf("- writing sync (every %d tokens) to %s\n", SYNCHRONIZATION, sync_path);
if ((sync = fopen(sync_path, "w")) == NULL) {
Rprintf("ERROR: can't create file %s\n", sync_path);
perror(sync_path);
return 1;
}
for (i = 0; i < hc->length; i++) {
/* SYNCHRONIZE */
if ((i % SYNCHRONIZATION) == 0) {
if (i > 0)
BFflush(&bfd);
pos = BFposition(&bfd);
NwriteInt(pos, sync);
}
id = cl_cpos2id(attr, i);
if ((id < 0) || (cderrno != CDA_OK)) {
cdperror("(aborting) cl_cpos2id() failed");
return 1;
}
else {
assert((id >= 0) && (id < hc->size) && "Internal Error");
cl = codelength[id];
code = heap[id];
if (!BFwriteWord((unsigned int)code, cl, &bfd)) {
Rprintf("Error writing code for ID %d (%d, %d bits) at position %d. Aborted.\n",
id, code, cl, i);
return 1;
}
}
}
fclose(sync);
BFclose(&bfd);
}
}
free(codelength);
free(heap);
return 1;
}
/* ================================================== DECOMPRESSION & ERROR CHECKING */
/* this
*/
/**
* Checks a huffcoded attribute for errors by decompressing it.
*
* This function assumes that compute_code_lengths() has been called
* beforehand and made sure that the _uncompressed_ token sequence is
* used by CL access functions.
*
* @param attr The attribute to check.
* @param fname Base filename to use for the three compressed-attribute files.
* Can be NULL, in which case the filenames in the attribute are used.
*/
int
decode_check_huff(Attribute *attr, char *corpus_id, char *fname)
{
BFile bfd;
FILE *sync;
HCD hc;
int pos, size, sync_offset, offset;
int l, v;
int item, true_item;
unsigned char bit;
char hcd_path[MAX_LINE_LENGTH];
char huf_path[MAX_LINE_LENGTH];
char sync_path[MAX_LINE_LENGTH];
Rprintf("VALIDATING %s.%s\n", corpus_id, attr->any.name);
if (fname) {
sprintf(hcd_path, "%s.hcd", fname);
sprintf(huf_path, "%s.huf", fname);
sprintf(sync_path, "%s.huf.syn", fname);
}
else {
char *path;
path = component_full_name(attr, CompHuffSeq, NULL);
assert(path && (cderrno == CDA_OK));
strcpy(huf_path, path);
path = component_full_name(attr, CompHuffCodes, NULL);
assert(path && (cderrno == CDA_OK));
strcpy(hcd_path, path);
path = component_full_name(attr, CompHuffSync, NULL);
assert(path && (cderrno == CDA_OK));
strcpy(sync_path, path);
}
Rprintf("- reading code descriptor block from %s\n", hcd_path);
if (!ReadHCD(hcd_path, &hc)) {
Rprintf("ERROR: reading %s failed. Aborted.\n", hcd_path);
return 1;
}
Rprintf("- reading compressed item sequence from %s\n", huf_path);
if (!BFopen(huf_path, "r", &bfd)) {
Rprintf("ERROR: can't open file %s. Aborted.\n", huf_path);
perror(huf_path);
return 1;
}
Rprintf("- reading sync (mod %d) from %s\n", SYNCHRONIZATION, sync_path);
if ((sync = fopen(sync_path, "r")) == NULL) {
Rprintf("ERROR: can't open file %s. Aborted.\n", sync_path);
perror(sync_path);
return 1;
}
size = cl_max_cpos(attr);
if (size != hc.length) {
Rprintf("ERROR: wrong corpus size (%d tokens) in %s (correct size: %d)\n",
hc.length, hcd_path, size);
return 1;
}
for (pos = 0; pos < hc.length; pos++) {
if ((pos % SYNCHRONIZATION) == 0) {
offset = BFposition(&bfd); /* need to get offset before flushing (because flushing fills the bit buffer and advances offset to the following byte!) */
if (pos > 0)
BFflush(&bfd);
sync_offset = -1; /* make sure we get an error if read below fails */
NreadInt(&sync_offset, sync);
if (offset != sync_offset) {
Rprintf("ERROR: wrong sync offset %d (true offset %d) at cpos %d. Aborted.\n",
sync_offset, offset, pos);
return 1;
}
}
if (!BFread(&bit, 1, &bfd)) {
Rprintf("ERROR reading file %s. Aborted.\n", huf_path);
return 1;
}
v = (bit ? 1 : 0);
l = 1;
while (v < hc.min_code[l]) {
if (!BFread(&bit, 1, &bfd)) {
Rprintf("ERROR reading file %s. Aborted.\n", huf_path);
return 0;
}
v <<= 1;
if (bit)
v++;
l++;
}
item = hc.symbols[hc.symindex[l] + v - hc.min_code[l]];
true_item = cl_cpos2id(attr, pos);
if (item != true_item) {
Rprintf("ERROR: wrong token (id=%d) at cpos %d (correct id=%d). Aborted.\n",
item, pos, true_item);
}
}
fclose(sync);
BFclose(&bfd);
/* tell the user it's safe to delete the CORPUS component now */
Rprintf("!! You can delete the file <%s> now.\n",
component_full_name(attr, CompCorpus, NULL));
return 0; /* exits on error, so there's no return value */
}
|
myoKun345/RcppCWB
|
src/cwb/cl/bitio.c
|
<filename>src/cwb/cl/bitio.c
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
void Rprintf(const char *, ...);
#include <sys/types.h>
#include "globals.h"
#include "endian2.h"
#include "bitio.h"
/**
* Opens a file for bit input / output.
*
* Sets up a bit input/output file buffer (BF)
*
* @param filename Name of file to open
* @param type File-open mode string: "w" or "r" accepted
* @param bf Buffer in which to set up the opened BF
* @return 1 on success, 0 on failure (not like fopen/fclose)
*/
int
BFopen(char *filename, char *type, BFile *bf)
{
/* force binary-mode open */
char passmode[3] = { '\0', 'b', '\0' };
bf->mode = type[0];
assert((bf->mode == 'r') || (bf->mode == 'w'));
passmode[0] = bf->mode;
bf->fd = fopen(filename, passmode);
bf->buf = '\0';
bf->bits_in_buf = 0;
bf->position = 0;
return (bf->fd ? 1 : 0);
}
/**
* Creates a stream buffer for bit input / output.
*
* Sets up a bit input/output stream buffer (BS)
*
* @param base Pointer to the stream
* @param type Mode-string: "w" or "r" accepted
* @param bf Buffer in which to set up the opened BS
* @return boolean: 1 on success, 0 on failure (not like fopen/fclose)
*/
int
BSopen(unsigned char *base, char *type, BStream *bf)
{
bf->base = base;
bf->buf = '\0';
bf->bits_in_buf = 0;
bf->mode = type[0];
bf->position = 0;
assert((bf->mode == 'r') || (bf->mode == 'w'));
return (bf->base ? 1 : 0);
}
/**
* Closes a bit input / output file buffer.
*
* If this is an output buffer, it is flushed before closing.
*
* @param stream The file buffer to close.
* @return Returns true iff the file was closed successfully.
*/
int
BFclose(BFile *stream)
{
if (stream->mode == 'w')
BFflush(stream);
return (fclose(stream->fd) == 0 ? 1 : 0);
}
/**
* Closes a bit input / output stream buffer.
*
* If this is an output buffer, it is flushed before closing.
*
* @param stream The stream buffer to close.
* @return Always returns true.
*/
int
BSclose(BStream *stream)
{
if (stream->mode == 'w')
BSflush(stream);
stream->base = NULL;
return 1;
}
/**
* Flushes a bit input / output file buffer.
*
* In the case of an output file buffer, the buffer is flushed,
* even an incomplete byte (so the next one begins at a new byte).
* In the case of an input file buffer, the buffer skips to the
* next input byte.
*
* @param stream The file buffer to flush.
* @return Boolean: 1 for all OK, 0 for a problem.
*/
int
BFflush(BFile *stream)
{
int retval;
retval = 0;
if (stream->mode == 'w') {
if ((stream->bits_in_buf > 0) &&
(stream->bits_in_buf < 8)) {
stream->buf <<= (8 - stream->bits_in_buf);
fwrite(&stream->buf, sizeof(unsigned char), 1, stream->fd);
stream->position++;
if (fflush(stream->fd) == 0)
retval = 1;
stream->buf = '\0';
stream->bits_in_buf = 0;
}
else
assert(stream->bits_in_buf == 0);
}
else if (stream->mode == 'r') {
if (fread(&stream->buf, sizeof(unsigned char), 1, stream->fd) == 1)
retval = 1;
stream->bits_in_buf = 8;
stream->position++;
}
else
assert(0 && "Illegal BitFile mode");
return retval;
}
/**
* Flushes a bit input / output stream buffer.
*
* In the case of an output stream, the stream is flushed,
* even an incomplete byte (so the next one begins at a new byte).
* In the case of an input stream, the stream skips to the
* next input byte.
*
* @param stream The stream to flush.
* @return Boolean: 1 for all OK, 0 for a problem.
*/
int
BSflush(BStream *stream)
{
int retval;
retval = 0;
if (stream->mode == 'w') {
if ((stream->bits_in_buf > 0) &&
(stream->bits_in_buf < 8)) {
stream->buf <<= (8 - stream->bits_in_buf);
stream->base[stream->position] = stream->buf;
stream->position++;
retval = 1;
stream->buf = '\0';
stream->bits_in_buf = 0;
}
else
assert(stream->bits_in_buf == 0);
}
else if (stream->mode == 'r') {
stream->buf = stream->base[stream->position];
retval = 1;
stream->bits_in_buf = 8;
stream->position++;
}
else
assert(0 && "Illegal BitFile mode");
return retval;
}
/**
* Writes bit data to file via a BFile buffer.
*
* Bits accumulate in the buffer till there are 8 of them.
* Then a byte is written to file (as an unsigned char).
*
*
* @param data The data to write.
* @param nbits The number of bits to write from data.
* @param stream The buffer to write via.
* @return Boolean: 1 for all OK, 0 for a problem.
*/
int
BFwrite(unsigned char data, int nbits, BFile *stream)
{
unsigned char mask;
mask = 1 << (nbits - 1);
while (nbits > 0) {
assert(mask);
assert(stream->bits_in_buf < 8);
stream->bits_in_buf++;
stream->buf <<= 1;
if (data & mask)
stream->buf |= 1;
if (stream->bits_in_buf == 8) {
if (fwrite(&stream->buf, sizeof(unsigned char), 1, stream->fd) != 1)
return 0;
stream->position++;
stream->buf = 0;
stream->bits_in_buf = 0;
}
nbits--;
mask >>= 1;
}
return 1;
}
/**
* Writes bit data to a character stream via a BStream buffer.
*
* Bits accumulate in the buffer till there are 8 of them.
* Then a byte is written to the stream (as an unsigned char).
*
*
* @param data The data to write.
* @param nbits The number of bits to write from data.
* @param stream The buffer to write via.
* @return Boolean: 1 for all OK, 0 for a problem.
*/
int
BSwrite(unsigned char data, int nbits, BStream *stream)
{
unsigned char mask;
mask = 1 << (nbits - 1);
while (nbits > 0) {
assert(mask);
assert(stream->bits_in_buf < 8);
stream->bits_in_buf++;
stream->buf <<= 1;
if (data & mask)
stream->buf |= 1;
if (stream->bits_in_buf == 8) {
stream->base[stream->position] = stream->buf;
stream->position++;
stream->buf = 0;
stream->bits_in_buf = 0;
}
nbits--;
mask >>= 1;
}
return 1;
}
/**
* Read bit data from a file via a BFile buffer.
*
* NOTE: be sure that you read the data into an unsigned char!
*
* @param data Pointer to the location for the read bit data.
* @param nbits Number of bits to read.
* @param stream The BFile buffer to use.
* @return Boolean: 1 for all OK, 0 for a problem.
*/
int
BFread(unsigned char *data, int nbits, BFile *stream)
{
*data = '\0';
while (nbits > 0) {
if (stream->bits_in_buf == 0) {
if (fread(&stream->buf, sizeof(unsigned char), 1, stream->fd) != 1)
return 0;
stream->position++;
stream->bits_in_buf = 8;
}
*data <<= 1;
if (stream->buf & (1<<7))
*data |= 1;
stream->buf <<= 1;
stream->bits_in_buf--;
nbits--;
}
return 1;
}
/**
* Read bit data from a stream via a BStream buffer.
*
* NOTE: be sure that you read the data into an unsigned char!
*
* @param data Pointer to the location for the read bit data.
* @param nbits Number of bits to read.
* @param stream The BStream buffer to use.
* @return Boolean: 1 for all OK, 0 for a problem.
*/
int
BSread(unsigned char *data, int nbits, BStream *stream)
{
*data = '\0';
while (nbits > 0) {
if (stream->bits_in_buf == 0) {
stream->buf = stream->base[stream->position];
stream->position++;
stream->bits_in_buf = 8;
}
*data <<= 1;
if (stream->buf & (1<<7))
*data |= 1;
stream->buf <<= 1;
stream->bits_in_buf--;
nbits--;
}
return 1;
}
/* the next two read nbits into an unsigned int, padded to the right */
/**
* Writes bit data to a file from an unsigned int.
*
* This function writes nbits from an unsigned int, padded to the right.
*
* @param data The data to write.
* @param nbits Number of bits to write.
* @param stream The BFile buffer to use.
* @return Boolean: 1 for all OK, 0 for a problem.
*/
int
BFwriteWord(unsigned int data, int nbits, BFile *stream)
{
int bytes, rest, i;
unsigned char *cdata;
if ((nbits > 32) || (nbits < 0)) {
Rprintf("bitio.o/BFwriteWord: nbits (%d) not in legal bounds\n", nbits);
return 0;
}
cdata = (unsigned char *)&data;
/* We need to normalise this to Network format in order to create
the same bitstream on all machines!!
This code is extremely ugly. */
data = htonl(data);
bytes = nbits / 8;
rest = nbits % 8;
if (rest)
if (!BFwrite(cdata[3-bytes], rest, stream))
return 0;
for (i = 4 - bytes; i < 4; i++)
if (!BFwrite(cdata[i], 8, stream))
return 0;
return 1;
}
/**
* Reads bit data from a file into an unsigned int.
*
* This function reads nbits into an unsigned int, padded to the right.
*
* @param data Pointer to the location for the read bit data.
* @param nbits Number of bits to read.
* @param stream The BFile buffer to use.
* @return Boolean: 1 for all OK, 0 for a problem.
*/
int
BFreadWord(unsigned int *data, int nbits, BFile *stream)
{
int bytes, rest, i;
unsigned char *cdata;
if ((nbits > 32) || (nbits < 0)) {
Rprintf("bitio.o/BFreadWord: nbits (%d) not in legal bounds\n", nbits);
return 0;
}
cdata = (unsigned char *)data;
bytes = nbits / 8;
rest = nbits % 8;
if (rest)
if (!BFread(cdata + 3 - bytes, rest, stream))
return 0;
for (i = 4 - bytes; i < 4; i++)
if (!BFread(cdata + i, 8, stream))
return 0;
/* As in BFwriteWord, the above code assumes that integers are 4 bytes long
and stored in LSB first fashion. To avoid rewriting the whole code, we just
convert from this Network byte-order to the platform's native byte-order
in the end (which assumes that ints are 4 bytes ... but hey, we've got to
live with that in the CWB! */
*data = ntohl(*data);
return 1;
}
/* I'm just glad Oli didn't implement BSwriteWord() ... */
/**
* Gets the stream position of a BFile.
*/
int
BFposition(BFile *stream)
{
assert(stream);
return stream->position;
}
/**
* Gets the stream position of a BStream.
*/
int
BSposition(BStream *stream)
{
assert(stream);
return stream->position;
}
/**
* Moves the position marker of a BStream (clearing the bit buffer in the process)
*
* @param stream The stream whose position marker is changed.
* @param offset The desired new offset.
* @return Always true.
*/
int
BSseek(BStream *stream, off_t offset)
{
stream->buf = '\0';
stream->bits_in_buf = 0;
stream->position = offset;
return 1;
}
|
myoKun345/RcppCWB
|
src/cwb/cqp/ascii-print.c
|
<reponame>myoKun345/RcppCWB
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
#include <stdio.h>
#include <string.h>
#include "../cl/macros.h"
#include "../cl/corpus.h"
#include "../cl/attributes.h"
#include "../cl/cdaccess.h"
#include <sys/time.h>
#include <time.h>
#ifndef __MINGW__
#include <pwd.h>
#endif
#ifdef USE_TERMCAP
#include <curses.h>
#include <term.h>
#endif /* USE_TERMCAP */
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include "ascii-print.h"
#include "cqp.h"
#include "output.h"
#include "print_align.h"
#include "options.h"
#include "corpmanag.h"
#include "concordance.h"
#include "attlist.h"
#include "print-modes.h"
/* ---------------------------------------------------------------------- */
/** [TODO get rid?] doesn't currently appear to be used anywhere? */
#define USE_OLD_COMPOSE
/* ---------------------------------------------------------------------- */
/**
* Convert string function for ASCII mode.
*
* This is used for the "printToken" function in the relevant PDR.
*
* @param s The string to convert.
* @return s (ie no change).
*/
/* inline */
char *
ascii_convert_string(char *s)
{
return s;
}
char *ascii_print_field(FieldType field, int at_end);
/* ---------------------------------------------------------------------- */
/**
* Print description record for ASCII print mode.
*/
PrintDescriptionRecord ASCIIPrintDescriptionRecord = {
"%9d: ", /* CPOSPrintFormat */
NULL, /* BeforePrintStructures */
" ", /* PrintStructureSeparator */
": ", /* AfterPrintStructures */
"<", /* StructureBeginPrefix */
">", /* StructureBeginSuffix */
" ", /* StructureSeparator */
"</", /* StructureEndPrefix */
">", /* StructureEndSuffix */
NULL, /* BeforeToken */
" ", /* TokenSeparator */
"/", /* AttributeSeparator */
NULL, /* AfterToken */
NULL, /* BeforeField */
NULL, /* FieldSeparator */
NULL, /* AfterField */
NULL, /* BeforeLine */
"\n", /* AfterLine */
NULL, /* BeforeConcordance */
NULL, /* AfterConcordance */
ascii_convert_string,
NULL /* don't highlight anchor points */
};
/**
* Print description record for Highlighted-ASCII print mode.
*/
PrintDescriptionRecord ASCIIHighlightedPrintDescriptionRecord = {
"%9d: ", /* CPOSPrintFormat */
NULL, /* BeforePrintStructures */
" ", /* PrintStructureSeparator */
": ", /* AfterPrintStructures */
"<", /* StructureBeginPrefix */
">", /* StructureBeginSuffix */
" ", /* StructureSeparator */
"</", /* StructureEndPrefix */
">", /* StructureEndSuffix */
NULL, /* BeforeToken */
" ", /* TokenSeparator */
"/", /* AttributeSeparator */
NULL, /* AfterToken */
NULL, /* BeforeField */
NULL, /* FieldSeparator */
NULL, /* AfterField */
NULL, /* BeforeLine */
"\n", /* AfterLine */
NULL, /* BeforeConcordance */
NULL, /* AfterConcordance */
ascii_convert_string,
ascii_print_field /* printField -> highlighting of anchor points */
};
/* ---------------------------------------------------------------------- */
/**
* Boolean: have escapes been initialised?
*/
static int escapes_initialized = 0;
static char
*sc_s_in, /**< Enter standout (highlighted) mode */
*sc_s_out, /**< Exit standout mode */
*sc_u_in, /**< Enter underline mode */
*sc_u_out, /**< Exit underline mode */
*sc_b_in, /**< Enter bold mode */
*sc_b_out, /**< Exit bold mode (doesn't exist; this code turns off _all_ attributes) */
*sc_bl_in, /**< Enter blink mode */
*sc_bl_out, /**< Exit blink mode */
*sc_all_out; /**< Turn off all display attributes */
/* flags for current display attributes */
int sc_s_mode = 0; /**< Boolean: following tokens will be shown in standout mode */
int sc_u_mode = 0; /**< Boolean: following tokens will be shown in underline mode */
int sc_b_mode = 0; /**< Boolean: following tokens will be shown in bold mode */
#ifndef USE_TERMCAP
/**
* Dummy function
*/
char *
get_colour_escape(char colour, int foreground)
{
return "";
}
/**
* Dummy function
*/
char *
get_typeface_escape(char typeface)
{
return "";
}
/**
* Dummy function
*/
void get_screen_escapes(void)
{
sc_s_in = NULL;
sc_s_out = NULL;
sc_u_in = NULL;
sc_u_out = NULL;
sc_b_in = NULL;
sc_b_out = NULL;
sc_bl_in = NULL;
sc_bl_out = NULL;
sc_all_out = NULL;
escapes_initialized++;
}
#else /* USE_TERMCAP */
void
get_screen_escapes(void)
{
int status, l;
char *term;
sc_s_in = "";
sc_s_out = "";
sc_u_in = "";
sc_u_out = "";
sc_b_in = "";
sc_b_out = "";
sc_bl_in = "";
sc_bl_out = "";
if ((term = getenv("TERM")) == NULL)
return;
if ((setupterm(term, 1, &status) == ERR) || (status != 1)) {
return;
}
/* turn off all attributes */
sc_all_out = tigetstr("sgr0");
if (sc_all_out == NULL) sc_all_out = "";
/* Linux terminfo bug? fix: tigetstr("sgr0") returns an extra ^O (\x0f) character appended to the escape sequence
(this may be some code used internally by the ncurses library).
Since we printf() the escape sequences directly, we have to remove the extra character or 'less -R' will get confused. */
l = strlen(sc_all_out);
if ((l > 0) && (sc_all_out[l-1] == '\x0f')) {
sc_all_out = cl_strdup(sc_all_out);
sc_all_out[l-1] = 0; /* just chop of the offending character */
}
/* standout mode */
sc_s_in = tigetstr("smso");
if (sc_s_in == NULL) sc_s_in = "";
sc_s_out = tigetstr("rmso");
if (sc_s_out == NULL) sc_s_out = "";
/* underline */
sc_u_in = tigetstr("smul");
if (sc_u_in == NULL) sc_u_in = sc_s_in;
sc_u_out = tigetstr("rmul");
if (sc_u_out == NULL) sc_u_out = sc_s_out;
/* bold */
sc_b_in = tigetstr("bold");
if (sc_b_in == NULL) {
sc_b_in = sc_s_in;
sc_b_out = sc_s_out;
}
else {
sc_b_out = tigetstr("sgr0"); /* can't turn off bold explicitly */
if (sc_b_out == NULL) sc_b_out = "";
}
/* blink */
sc_bl_in = tigetstr("blink");
if (sc_bl_in == NULL) {
sc_bl_in = sc_s_in;
sc_bl_out = sc_s_out;
}
else {
sc_bl_out = sc_all_out; /* can't turn off blinking mode explicitly */
}
escapes_initialized++;
/* in highlighted mode, switch off display attributes at end of line (to be on the safe side) */
ASCIIHighlightedPrintDescriptionRecord.AfterLine = cl_malloc(strlen(sc_all_out) + 2);
sprintf(ASCIIHighlightedPrintDescriptionRecord.AfterLine,
"%s\n", sc_all_out);
/* print cpos in blue, "print structures" in pink if we're in coloured mode */
if (use_colour) {
char *blue = get_colour_escape('b', 1);
char *pink = get_colour_escape('p', 1);
char *normal = get_typeface_escape('n');
char *bold = get_typeface_escape('b');
ASCIIHighlightedPrintDescriptionRecord.CPOSPrintFormat = cl_malloc(strlen(blue) + strlen(normal) + 8);
sprintf(ASCIIHighlightedPrintDescriptionRecord.CPOSPrintFormat,
"%s%c9d:%s ", blue, '%', normal);
ASCIIHighlightedPrintDescriptionRecord.BeforePrintStructures = cl_malloc(strlen(pink) + strlen(bold) + 4);
sprintf(ASCIIHighlightedPrintDescriptionRecord.BeforePrintStructures,
"%s%s", pink, bold);
ASCIIHighlightedPrintDescriptionRecord.AfterPrintStructures = cl_malloc(strlen(normal) + 6);
sprintf(ASCIIHighlightedPrintDescriptionRecord.AfterPrintStructures,
":%s ", normal);
}
}
/* typeface = b=bold, u=underlined, s=standout, n=normal */
char *
get_typeface_escape(char typeface)
{
if (!escapes_initialized)
get_screen_escapes();
if (!escapes_initialized)
return ""; /* initialisation failed */
switch (typeface) {
case 'b': return sc_b_in;
case 'u': return sc_u_in;
case 's': return sc_s_in;
case 'n': return sc_all_out; /* also switches off colour */
default:
Rprintf("Internal error: unknown typeface '%c'.\n", typeface);
return "";
}
}
/* interface to the terminal formatting escape sequences (with dummy replacements if USE_TERMCAP is not set) */
/* colour: r=red g=green b=blue, p=pink, y=yellow, c=cyan */
char *
get_colour_escape(char colour, int foreground) {
if (use_colour) {
if (*(get_typeface_escape('n')) == 0)
return ""; /* don't try colour if terminal doesn't support typefaces */
if (foreground) {
switch(colour) {
case 'r': return "\x1B[0;31m";
case 'g': return "\x1B[0;32m";
case 'y': return "\x1B[0;33m";
case 'b': return "\x1B[0;34m";
case 'p': return "\x1B[0;35m";
case 'c': return "\x1B[0;36m";
default:
Rprintf("Internal error: unknown colour '%c'.\n", colour);
return "\x1B[0m";
}
}
else {
switch(colour) {
case 'r': return "\x1B[0;41m";
case 'g': return "\x1B[0;42m";
case 'y': return "\x1B[0;43m";
case 'b': return "\x1B[0;44m";
case 'p': return "\x1B[0;45m";
case 'c': return "\x1B[0;46m";
default:
Rprintf("Internal error: unknown colour '%c'.\n", colour);
return "\x1B[0m";
}
}
}
else {
return "";
}
}
#endif /* USE_TERMCAP */
/* ---------------------------------------------------------------------- */
/*
* ======================================================================
* Print Concordance Line
* ======================================================================
*/
/**< 'static' return value of ascii_print_field() */
char sc_before_token[256];
char *
ascii_print_field(FieldType field, int at_end)
{
sc_before_token[0] = '\0'; /* sets sc_before_token to "" */
/* if targets are shown, print target number at end of target/keyword fields */
if (show_targets && at_end && (field==TargetField || field==KeywordField)) {
char *red = get_colour_escape('r', 1);
/* if colours are activated & seem to work, print target number in red, otherwise print in parens */
if (*red != 0) {
/* must set colour first, then all other current attributes */
sprintf(sc_before_token + strlen(sc_before_token),
"%s%s%s%s%s%d",
sc_all_out,
red,
(sc_s_mode) ? sc_s_in : "",
(sc_u_mode) ? sc_u_in : "",
(sc_b_mode) ? sc_b_in : "",
field - TargetField); /* should yield 0 .. 9 */
}
else {
sprintf(sc_before_token + strlen(sc_before_token),
"(%d)", field - TargetField /* should yield 0 .. 9 */
);
}
}
/* set the display attribute flags */
switch (field) {
case MatchField:
if (at_end)
sc_s_mode = 0;
else
sc_s_mode = 1;
break;
case KeywordField:
if (at_end)
sc_u_mode = 0;
else
sc_u_mode = 1;
break;
case TargetField:
if (at_end)
sc_b_mode = 0;
else
sc_b_mode = 1;
break;
case NoField:
default:
break;
}
/* now compose escape sequence which has to be sent to the terminal (setting _all_ attributes to their current values) */
sprintf(sc_before_token + strlen(sc_before_token),
"%s%s%s%s",
sc_all_out, /* first switch off all attributes, then set the active ones in order standout, underline, bold */
(sc_s_mode) ? sc_s_in : "",
(sc_u_mode) ? sc_u_in : "",
(sc_b_mode) ? sc_b_in : "");
return sc_before_token;
}
/**
* Prints a line of text (which will have been previously exrtracted from a corfpus
* linked to the present corpus by an a-attribute) with a brief character-mode
* start-of-line flag ("-->$att_name: ").
*
* @param stream Destination for the output.
* @param highlighting Boolean: if true, use colour/bold highlighting for the leading indicator on the line.
* @param attribute_name The name of the aligned corpus: printed in the leading indicator
* @param line Character data of the line of aligned-corpus data to print. This is treated as opaque.
*/
void
ascii_print_aligned_line(FILE *stream,
int highlighting,
char *attribute_name,
char *line)
{
if (highlighting) {
char *red = get_colour_escape('r', 1);
char *bold = get_typeface_escape('b');
char *normal = get_typeface_escape('n');
Rprintf("%s%s-->%s:%s %s\n",
red, bold,
attribute_name,
normal,
line);
}
else
Rprintf("-->%s: %s\n", attribute_name, line);
}
/* print the concordance line for the target_word on the screen */
/**
* Prints a concordance line.
* (documentation not complete)_
*
*
*/
void
print_concordance_line(FILE *outfd,
CorpusList *cl,
int element,
int apply_highlighting,
AttributeList *strucs)
{
char *outstr;
int length, string_match_begin_pos, string_match_end_pos;
ConcLineField clf[NoField]; /* NoField is largest field code (not used by us) */
PrintDescriptionRecord *pdr;
if ((cl == NULL) || (outfd == NULL)) {
cqpmessage(Error, "Empty corpus or empty output file");
return;
}
if (element < 0 || element >= cl->size) {
cqpmessage(Error, "Illegal element in print_concordance_line");
return;
}
if (escapes_initialized == 0)
get_screen_escapes();
sc_s_mode = 0; /* reset display flags */
sc_u_mode = 0;
sc_b_mode = 0;
/* ---------------------------------------- concordance fields */
clf[MatchField].type = MatchField;
clf[MatchField].start_position = cl->range[element].start;
clf[MatchField].end_position = cl->range[element].end;
clf[MatchEndField].type = MatchEndField; /* unused, because we use MatchField for the entire match */
clf[MatchEndField].start_position = -1;
clf[MatchEndField].end_position = -1;
clf[KeywordField].type = KeywordField;
if (cl->keywords) {
clf[KeywordField].start_position = cl->keywords[element];
clf[KeywordField].end_position = cl->keywords[element];
}
else {
clf[KeywordField].start_position = -1;
clf[KeywordField].end_position = -1;
}
clf[TargetField].type = TargetField;
if (cl->targets) {
clf[TargetField].start_position = cl->targets[element];
clf[TargetField].end_position = cl->targets[element];
}
else {
clf[TargetField].start_position = -1;
clf[TargetField].end_position = -1;
}
if (apply_highlighting)
pdr = &ASCIIHighlightedPrintDescriptionRecord;
else
pdr = &ASCIIPrintDescriptionRecord;
outstr = compose_kwic_line(cl->corpus,
cl->range[element].start, cl->range[element].end,
&CD,
&length,
&string_match_begin_pos, &string_match_end_pos,
left_delimiter, right_delimiter,
NULL, 0, NULL,
clf, NoField, /* NoField = # of entries in clf[] */
ConcLineHorizontal,
pdr,
0, NULL);
fputs(outstr, outfd);
free(outstr);
if (pdr->AfterLine)
fputs(pdr->AfterLine, outfd);
if (CD.alignedCorpora != NULL)
printAlignedStrings(cl->corpus,
&CD,
cl->range[element].start, cl->range[element].end,
apply_highlighting,
outfd);
}
void
ascii_print_corpus_header(CorpusList *cl,
FILE *stream)
{
time_t now;
#ifndef __MINGW__
struct passwd *pwd = NULL;
#endif
int i;
time(&now);
/* pwd = getpwuid(geteuid()); */
/* disabled because of incompatibilities between different Linux versions */
fputc('#', stream);
for (i = 0; i < 75; i++)
fputc('-', stream);
fputc('\n', stream);
Rprintf(
"#\n"
"# User: %s (%s)\n"
"# Date: %s"
"# Corpus: %s (%s)\n"
"# Name: %s:%s\n"
"# Size: %d intervals/matches\n",
#ifndef __MINGW__
(pwd ? pwd->pw_name : "<unknown>"),
(pwd ? pwd->pw_gecos : "<unknown>"),
#else
"<unknown>",
"<unknown>",
#endif
ctime(&now),
(cl->corpus && cl->corpus->registry_name ? cl->corpus->registry_name : "<Unknown Corpus>"),
(cl->corpus && cl->corpus->name ? cl->corpus->name : "<Unknown Corpus>"),
cl->mother_name, cl->name,
cl->size);
Rprintf(
"# Context: %d %s left, %d %s right\n"
"#\n",
CD.left_width,
(CD.left_type == CHAR_CONTEXT) ? "characters" :
((CD.left_type == WORD_CONTEXT) ? "words" :
(CD.left_structure_name) ? CD.left_structure_name : "???"),
CD.right_width,
(CD.right_type == CHAR_CONTEXT) ? "characters" :
((CD.right_type == WORD_CONTEXT) ? "words" :
(CD.right_structure_name) ? CD.right_structure_name : "???"));
if (cl->query_corpus && cl->query_text) {
Rprintf("# Query: %s; %s\n", cl->query_corpus, cl->query_text);
}
fputc('#', stream);
for (i = 0; i < 75; i++)
fputc('-', stream);
fputc('\n', stream);
}
void
ascii_print_output(CorpusList *cl,
FILE *outfd,
int interactive,
ContextDescriptor *cd,
int first, int last)
{
int real_line, i;
int output_line = 1;
if (first < 0)
first = 0;
if ((last >= cl->size) || (last < 0))
last = cl->size - 1;
for (i = first; (i <= last) && !cl_broken_pipe; i++) {
if (cl->sortidx)
real_line = cl->sortidx[i];
else
real_line = i;
if (GlobalPrintOptions.number_lines) {
Rprintf("%6d.\t", output_line);
output_line++;
}
print_concordance_line(outfd, cl, real_line,
interactive && highlighting,
cd->printStructureTags);
}
}
void
ascii_print_group(Group *group, int expand, FILE *fd)
{
int source_id, target_id, count;
int has_source = (group->source_attribute != NULL);
char *source_s = "(null)";
char *target_s = "(null)";
int cell, last_source_id;
int nr_targets;
/* some pretty printing stuff left over from Oli */
last_source_id = -666;
nr_targets = 0;
for (cell = 0; (cell < group->nr_cells) && !cl_broken_pipe; cell++) {
source_id = group->count_cells[cell].s;
source_s = Group_id2str(group, source_id, 0);
target_id = group->count_cells[cell].t;
target_s = Group_id2str(group, target_id, 1);
count = group->count_cells[cell].freq;
if (pretty_print) {
if (source_id != last_source_id) {
last_source_id = source_id;
nr_targets = 0;
}
/* separator bar between groups */
if (cell == 0 || (group->is_grouped && nr_targets == 0))
Rprintf(SEPARATOR);
Rprintf("%-28s %-28s\t%6d\n",
(nr_targets == 0) ? source_s : " ", target_s, count);
}
else {
if (source_id < 0) source_s = ""; /* don't print "(none)" or "(all)" in plain mode (just empty string) */
if (target_id < 0) target_s = "";
if (has_source)
Rprintf("%s\t%s\t%d\n", source_s, target_s, count);
else
Rprintf("%s\t%d\n", target_s, count);
}
if (expand) {
/* Ausgabe der entsprechenden Konkordanzzeilen??? */
}
nr_targets++;
}
}
|
myoKun345/RcppCWB
|
src/cwb/editline/vc_editline_config.h
|
/************************************************************************/
/* */
/* Centre for Speech Technology Research */
/* University of Edinburgh, UK */
/* Copyright (c) 1996,1997 */
/* All Rights Reserved. */
/* */
/* Permission to use, copy, modify, distribute this software and its */
/* documentation for research, educational and individual use only, is */
/* hereby granted without fee, subject to the following conditions: */
/* 1. The code must retain the above copyright notice, this list of */
/* conditions and the following disclaimer. */
/* 2. Any modifications must be clearly marked as such. */
/* 3. Original authors' names are not deleted. */
/* This software may not be used for commercial purposes without */
/* specific prior written permission from the authors. */
/* */
/* THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK */
/* DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING */
/* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT */
/* SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE */
/* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES */
/* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN */
/* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, */
/* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF */
/* THIS SOFTWARE. */
/* */
/************************************************************************/
/* A Hand crafted config for Visual C */
/* ---------------------------------------------------------------------*/
/* Author: <NAME> */
/************************************************************************/
/* Define if the closedir function returns void instead of int. */
/* #undef CLOSEDIR_VOID */
/* Define if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Are we compiling under windows */
#define SYSTEM_IS_WIN32 1
/* How do we control the tty */
#define HAVE_TCGETATTR 1
/* Make Arrow keys work */
#define ANSI_ARROWS 1
/* Make local functions static */
#define HIDE 1
/* Define if you have the <dirent.h> header file. */
#define HAVE_DIRENT_H 1
/* Define if you have the <ndir.h> header file. */
/* #undef HAVE_NDIR_H */
/* Define if you have the <sys/dir.h> header file. */
/* #undef HAVE_SYS_DIR_H */
/* Define if you have the <sys/ndir.h> header file. */
/* #undef HAVE_SYS_NDIR_H */
/* Define if you have the <walloc.h> header file. */
/* #undef HAVE_WALLOC_H */
/* We don't have termcap of course, but we have some
* functions which pretend to be termcap
*/
#define HAVE_LIBTERMCAP 1
|
myoKun345/RcppCWB
|
src/cwb/cl/regopt.c
|
<filename>src/cwb/cl/regopt.c
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
/*
* Windows/Unicode-compatibility extensions to CWB in this file
* Copyright (C) 2010 by <NAME>, ENS de Lyon
*/
#include <glib.h>
#include "globals.h"
#include "regopt.h"
void Rprintf(const char *, ...);
/**
* @file
*
* The CL_Regex object, and the CL Regular Expression Optimiser.
*
* This is the CL front-end to POSIX regular expressions with CL semantics
* (most notably: CL regexes always match the entire string and NOT
* substrings.)
*
* Note that the optimiser is handled automatically by the CL_Regex object.
*
* All variables / functions containing "regopt" are internal to this
* module and are not exported in the CL API.
*
* Optimisation is done by means of "grains". The grain array in a CL_Regex
* object is a list of short strings. Any string which will match the
* regex must contain at least one of these. Thus, the grains
* provide a quick way of filtering out strings that definitely WON'T
* match, and avoiding a time-wasting call to the POSIX regex
* matching function.
*
* While a regex is being optimised, the grains are stored in non-exported
* global variables in this module. Subsequently they are transferred to
* members of the CL_regex object with which they are associated.
* The use of global variables and a fixed-size buffer for
* grains is partly due to historical reasons,
* but it does also serve to reduce memory allocation overhead.
*/
/* optimiser variables */
char *cl_regopt_grain[MAX_GRAINS]; /**< list of 'grains' (any matching string must contain one of these) */
int cl_regopt_grain_len; /**< length of shortest grain (in characters) */
int cl_regopt_grains; /**< number of grains */
int cl_regopt_anchor_start; /**< Boolean: whether grains are anchored at beginning of string */
int cl_regopt_anchor_end; /**< Boolean: whether grains are anchored at end of string */
/** whether the regular expression is in UTF-8 encoding (set before calling cl_regopt_analyse()) */
int cl_regopt_utf8;
/**
* Intermediate buffer for grains.
*
* When a regex is parsed, grains for each segment are written to this intermediate buffer;
* if the new set of grains is better than the current one, it is copied to the cl_regopt_ variables.
*/
char *grain_buffer[MAX_GRAINS]; /**< grains in the local buffer may have different lengths */
int grain_buffer_len[MAX_GRAINS]; /**< the length of each grain (in characters) */
/** The number of grains currently in the intermediate buffer. @see grain_buffer */
int grain_buffer_grains = 0;
/** A buffer for grain strings. @see local_grain_data */
char public_grain_data[CL_MAX_LINE_LENGTH]; /* input regexp shouldn't be longer than CL_MAX_LINE_LENGTH, so all grains must fit */
/* TODO - above assumes rx no longer than CL_MAX_LINE_LENGTH, but in cl_new_regex(), it is explicitly assumed that
* there may be regexs (with RE() ) that are of any gargantuan length... */
/** A buffer for grain strings. @see public_grain_data */
char local_grain_data[CL_MAX_LINE_LENGTH];
int cl_regopt_analyse(char *regex);
/**
* A counter of how many times the "grain" system has allwoed us to avoid
* calling the regex engine.
*
* @see cl_regopt_count_get
*/
int cl_regopt_successes = 0;
/*
* interface functions (ie "public methods" of CL_Regex)
*/
/**
* The error message from (PCRE) regex compilation are placed in this buffer
* if cl_new_regex() fails.
*
* This global variable is part of the CL_Regex object's API.
*/
char cl_regex_error[CL_MAX_LINE_LENGTH];
/**
* Create a new CL_regex object (ie a regular expression buffer).
*
* This function compiles the regular expression according to the specified flags
* (IGNORE_CASE and/or IGNORE_DIAC and/or REQUIRE_NFC) and for the specified
* character encoding. The regex is automatically anchored to the start and end of
* the string (i.e. wrapped in ^(?:...)$).
*
* The regular expression engine used is PCRE. However, the regex is optimized by
* scanning it for literal strings ("grains") that must be contained in any
* match; the grains can be used as a fast pre-filter (using Boyer-Moore search
* for the grains).
*
* The optimizer only understands a subset of PCRE syntax:
* - literal characters (alphanumeric, safe punctuation, escaped punctuation)
* - numeric character codes (\x and \o)
* - escape sequences for character classes and Unicode properties
* - all repetition operators
* - simple alternatives (...|...|...)
* - nested capturing (...) and non-capturing (?:...) groups
* Any regexp that contains other syntactic elements such as
* - character sets [...]
* - named groups, look-ahead and look-behind patterns, etc.
* - backreferences
* - modifiers such as (?i)
* cannot be parsed and optimized. Note that even if a regexp is parsed by
* the optimizer, it might not be able to extract all grains (because grain
* recognition uses an even more restrictive syntax).
*
* The optimizer is always disabled with IGNORE_DIAC if either PCRE JIT is
* available or the charset is UTF-8. Testing has showed that in these cases
* the overhead from case-folding each input string outweighs the benefits
* of the optimizer.
*
* @param regex String containing the regular expression
* @param flags IGNORE_CASE, or IGNORE_DIAC, or both, or 0.
* @param charset The character set of the regex.
* @return The new CL_Regex object, or NULL in case of error.
*/
CL_Regex
cl_new_regex(char *regex, int flags, CorpusCharset charset)
{
/* allocate buffers dynamically to support very long regexps (from RE() operator) */
char *delatexed_regex;
char *preprocessed_regex;
char *anchored_regex;
CL_Regex rx;
int optimised, l;
int options_for_pcre = 0;
const char *errstring_for_pcre = NULL;
int erroffset_for_pcre = 0;
int is_pcre_jit_available; /* in some cases, PCRE + JIT may be faster without the optimizer */
/* allocate temporary strings */
l = strlen(regex);
delatexed_regex = (char *) cl_malloc(l + 1);
/* allocate and initialise CL_Regex object */
rx = (CL_Regex) cl_malloc(sizeof(struct _CL_Regex));
rx->haystack_buf = NULL;
rx->haystack_casefold = NULL;
rx->charset = charset;
rx->icase = (flags & IGNORE_CASE); /* handled separately in CWB 3.4.10+ */
rx->idiac = (flags & IGNORE_DIAC);
rx->grains = 0; /* indicates no optimisation -> other optimizer-related fields are invalid */
/* pre-process regular expression (translate latex escapes, normalize, fold accents if required) */
cl_string_latex2iso(regex, delatexed_regex, l);
/* only fold accents at this stage */
preprocessed_regex = cl_string_canonical(delatexed_regex, charset, rx->idiac | REQUIRE_NFC, CL_STRING_CANONICAL_STRDUP);
cl_free(delatexed_regex);
/* add start and end anchors to improve performance of regex matcher for expressions such as ".*ung" */
anchored_regex = (char *) cl_malloc(strlen(preprocessed_regex) + 7);
sprintf(anchored_regex, "^(?:%s)$", preprocessed_regex);
/* compile regular expression with PCRE library function */
options_for_pcre = PCRE_UCP; /* use Unicode properties for \w, \d, etc. */
if (rx->icase)
options_for_pcre |= PCRE_CASELESS; /* case folding is left to the PCRE matcher */
if (charset == utf8) {
if (cl_debug)
Rprintf("CL: enabling PCRE's UTF8 mode for regex %s\n", anchored_regex);
/* note we assume all strings have been checked upon input (i.e. indexing or by the parser) */
options_for_pcre |= PCRE_UTF8|PCRE_NO_UTF8_CHECK;
}
rx->needle = pcre_compile(anchored_regex, options_for_pcre, &errstring_for_pcre, &erroffset_for_pcre, NULL);
if (rx->needle == NULL) {
strcpy(cl_regex_error, errstring_for_pcre);
Rprintf("CL: Regex Compile Error: %s\n", cl_regex_error);
cl_free(rx);
cl_free(preprocessed_regex);
cl_free(anchored_regex);
cl_errno = CDA_EBADREGEX;
return NULL;
}
else if (cl_debug)
Rprintf("CL: Regex compiled successfully using PCRE library\n");
/* a spot of code to handle use with a pre-JIT version of PCRE.
* Note that JIT compilation was added to PCRE v8.20. */
#ifdef PCRE_CONFIG_JIT
pcre_config(PCRE_CONFIG_JIT, &is_pcre_jit_available);
#else
is_pcre_jit_available = 0;
#define PCRE_STUDY_JIT_COMPILE 0
#endif
if (cl_debug)
Rprintf("CL: PCRE's JIT compiler is %s.\n", (is_pcre_jit_available ? "available" : "unavailable"));
/* always use pcre_study because nearly all our regexes are going to be used lots of times;
* with recent version of PCRE, this will also JIT-compile the expression for much faster matching */
rx->extra = pcre_study(rx->needle, PCRE_STUDY_JIT_COMPILE, &errstring_for_pcre);
if (errstring_for_pcre != NULL) {
rx->extra = NULL;
if (cl_debug)
Rprintf("CL: calling pcre_study failed with message...\n %s\n", errstring_for_pcre);
/* note that failure of pcre_study is not a critical error, we can just continue without the extra info */
}
if (cl_debug && rx->extra)
Rprintf("CL: calling pcre_study produced useful information...\n");
/* attempt to optimise regular expression */
cl_regopt_utf8 = (charset == utf8);
optimised = cl_regopt_analyse(preprocessed_regex);
/* decide whether it makes sense to use the optimizer:
* - testing showed that it is usually faster to rely directly on PCRE's caseless matching than
* casefold each input string for a Boyer-Moore search
* - this is always the case if PCRE has JIT capability
* - without JIT, it is still usually better to avoid expensive UTF-8 case-folding
* NB: accent-folding for %d cannot be avoided, so it makes no sense to disable the optimizer there
* NB: cannot debug the optimizer with %c any more (because regopt_data_copy_to_regex_object will not be called)
*/
if (rx->icase && (charset == utf8 || is_pcre_jit_available)) {
if (optimised && cl_debug) {
int i;
Rprintf("CL: Found grain set with %d items(s)", cl_regopt_grains);
for (i = 0; i < cl_regopt_grains; i++) {
Rprintf(" [%s]", cl_regopt_grain[i]);
}
Rprintf("\nCL: but optimization disabled for case-insensitive search\n");
}
optimised = 0;
}
if (optimised) {
/* copy optimiser data to CL_Regex object and construct jump table for Boyer-Moore search */
regopt_data_copy_to_regex_object(rx); /* will also casefold grains if rx->icase is set */
}
if (rx->idiac)
/* allocate string buffer for accent folding in cl_regex_match() */
rx->haystack_buf = (char *) cl_malloc(CL_MAX_LINE_LENGTH); /* this is for the string being matched, not the regex! */
if (rx->icase && optimised)
/* allocate second buffer for case-folded version (only needed for optimizer) */
rx->haystack_casefold = (char *) cl_malloc(2 * CL_MAX_LINE_LENGTH);
cl_free(preprocessed_regex);
cl_free(anchored_regex);
cl_errno = CDA_OK;
return rx;
}
/**
* Finds the level of optimisation of a CL_Regex.
*
* This function returns the approximate level of optimisation,
* computed from the ratio of grain length to number of grains
* (0 = no grains, ergo not optimised at all).
*
* @param rx The CL_Regex to check.
* @return 0 if rx is not optimised; otherwise an integer
* indicating optimisation level.
*/
int
cl_regex_optimised(CL_Regex rx)
{
if (rx->grains == 0)
return 0; /* not optimised */
else {
int level = (3 * rx->grain_len) / rx->grains;
return ((level >= 1) ? level + 1 : 1);
}
}
/**
* Matches a regular expression against a string.
*
* The pre-compiled regular expression contained in the CL_Regex is compared to the string.
* This regex automatically uses the case/accent folding flags and character encoding
* that were specified when the CL_Regex constructor was called.
*
* If the subject string is a UTF-8 string from an external sources, the caller can request
* enforcement of the subject to canonical NFC form by setting the third argument to true.
*
* @see cl_new_regex
* @param rx The regular expression to match.
* @param str The subject (the string to compare the regex to).
* @param normalize_utf8 Boolean: if a UTF-8 string from an external source is passed as subject,
* set to this parameter to true, and the function will make sure that
* the comparison is based on the canonical NFC form. For known-NFC
* strings, this parameter should be false. If the regex is not UTF-8,
* this parameter is ignored.
* @return Boolean: true if the regex matched, otherwise false.
*/
int
cl_regex_match(CL_Regex rx, char *str, int normalize_utf8)
{
char *haystack_pcre, *haystack; /* possibly case/accent folded versions of str for PCRE regexp and optimizer, respectively */
int optimised = (rx->grains > 0);
int i, di, k, max_i, len, jump;
int grain_match, result;
int ovector[30]; /* memory for pcre to use for back-references in pattern matches */
int do_nfc = (normalize_utf8 && (rx->charset == utf8)) ? REQUIRE_NFC : 0; /* whether we need to normalize the input to NFC */
if (rx->idiac || do_nfc) { /* perform accent folding on input string if necessary */
haystack_pcre = rx->haystack_buf;
strcpy(haystack_pcre, str);
cl_string_canonical(haystack_pcre, rx->charset, rx->idiac | do_nfc, CL_MAX_LINE_LENGTH);
}
else
haystack_pcre = str;
len = strlen(haystack_pcre);
/* Beta versions 3.4.10+ leading up to 3.5:
* - use regexp optimizer only if cl_optimize is set
* - allows comparative testing & benchmarking
* - question: is the optimizer still worth the effort for PCRE with JIT?
* - switch optimizer back to default before release **TODO**
*/
if (optimised && cl_optimize) {
if (rx->icase) {
haystack = rx->haystack_casefold;
strcpy(haystack, haystack_pcre);
cl_string_canonical(haystack, rx->charset, rx->icase, 2 * CL_MAX_LINE_LENGTH);
}
else
haystack = haystack_pcre;
/* this 'optimised' matcher may look fairly complicated, but it's still way ahead of POSIX regexen */
/* string offset where first character of each grain would be */
grain_match = 0;
max_i = len - rx->grain_len; /* stop trying to match when i > max_i */
if (rx->anchor_end)
i = (max_i >= 0) ? max_i : 0; /* if anchored at end, align grains with end of string */
else
i = 0;
while (i <= max_i) {
jump = rx->jumptable[(unsigned char) haystack[i + rx->grain_len - 1]];
if (jump > 0) {
i += jump; /* Boyer-Moore search */
}
else {
/* for each grain */
for (k = 0; k < rx->grains; k++) {
di = 0;
while ((di < rx->grain_len) && (rx->grain[k][di] == haystack[i + di]))
di++;
if (di >= rx->grain_len) {
grain_match = 1;
break; /* we have found a grain match and can quit the loop */
}
}
i++;
}
if (rx->anchor_start)
break; /* if anchored at start, only the first iteration can match */
}
} /* endif optimised */
else
/* if the regex is not optimised, always behave as if a grain was matched */
grain_match = 1;
/* if there was a grain-match, we call pcre_exec, which might match or might not find a match in the end;
* but if there wasn't a grain-match, we know that PCRE won't match; so we don't bother calling it. */
if (!grain_match) { /* enabled since version 2.2.b94 (14 Feb 2006) -- before: && cl_optimize */
cl_regopt_successes++;
result = PCRE_ERROR_NOMATCH; /* the return code from PCRE when there is, um, no match */
}
#if 1
/* set to 0 for debug purposes: always calls PCRE regardless of whether grains matched. */
/* this allows the code in the #if 1 below to check whether or not grains are behaving as they should. */
else {
#else
if (1) {
#endif
result = pcre_exec(rx->needle, rx->extra, haystack_pcre,
len, 0, PCRE_NO_UTF8_CHECK,
ovector, 30);
if (result < PCRE_ERROR_NOMATCH && cl_debug)
/* note, "no match" is a PCRE "error", but all actual errors are lower numbers */
Rprintf("CL: Regex Execute Error no. %d (see `man pcreapi` for error codes)\n", result);
}
#if 1
/* debugging code used before version 2.2.b94, modified to pcre return values & re-enabled in 3.2.b3 */
/* check for critical error: optimiser didn't accept candidate, but regex matched */
if ((result > 0) && !grain_match)
Rprintf("CL ERROR: regex optimiser did not accept '%s' although it should have!\n", str);
#endif
return (result > 0); /* return true if regular expression matched */
}
/**
* Deletes a CL_Regex object, and frees all resources associated with
* the pre-compiled regex.
*
* @param rx The CL_Regex to delete.
*/
void
cl_delete_regex(CL_Regex rx)
{
/* DON'T use cl_free() for PCRE opaque objects, just in case; use PCRE built-in
* pcre_free(). Note this will probably just be set to = free(). But it might not.
* We can let PCRE worry about that. That does mean, however, we should test the
* pointers for non-nullity before calling pcre_free. Normally we would also set the
* pointers to NULL after freeing the target. However, in this case, we know the
* structure they belong to will be freed by the end of the function, so no worries.
*/
int i;
/* sanity check for NULL pointer */
if (!rx)
return;
if (rx->needle)
pcre_free(rx->needle); /* free PCRE regex buffer */
if (rx->extra)
#ifdef PCRE_CONFIG_JIT
pcre_free_study(rx->extra); /* and "extra" buffer (iff JIT was a possibility)*/
#else
pcre_free(rx->extra); /* and "extra" buffer (iff we know for certain there was no JIT) */
#endif
cl_free(rx->haystack_buf); /* free string buffers if they were allocated */
cl_free(rx->haystack_casefold);
for (i = 0; i < rx->grains; i++)
cl_free(rx->grain[i]); /* free grain strings if regex was optimised */
cl_free(rx);
}
/*
* ================================
* helper functions (for optimiser)
* (non-exported in the public API)
* ================================
*/
/**
* Is the given character a 'safe' character which will only match itself in a regex?
*
* What counts as safe: A to Z, a to z, 0 to 9, minus, quote marks, percent,
* ampersand, slash, excl mark, colon, semi colon, character, underscore, tilde,
* any values above 0x7f (ISO 8859 extension or UTF-8 non-ASCII character).
*
* What counts as not safe therefore includes: brackets, braces, square brackets;
* questionmark, plus, and star; circumflex and dollar sign; dot; hash; backslash, etc.
* (But, in UTF8, Unicode PUNC area equivalents of these characters will be safe.)
*
* A safe character can never be the start of a meta element (even if it might appear
* as part of one), so it's safe to include in a literal grain.
*
* @param c The character (cast to unsigned for the comparison).
* @return True for non-special characters; false for special characters.
*/
int
is_safe_char(unsigned char c)
{
/* note: this function is UTF8-safe because byte values above 0x7f
* (forming UTF-8 multi-byte sequences) are always allowed */
if (
(c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') ||
(c >= 128) /* & (c <= 255); omitted to avoid compiler warnings */
) {
return 1;
}
else {
switch (c) {
case '!':
case '"':
case '#':
case '%':
case '&':
case '\'':
case ',':
case '-':
case '/':
case ':':
case ';':
case '<':
case '=':
case '>':
case '@':
case '_':
case '`':
case '~':
return 1;
default:
return 0;
}
}
}
/**
* Is the given character an ASCII alphanumeric?
*
* ASCII alphanumeric characters comprise A-Z, a-z and 0-9; they are the only
* characters that form special escape sequences in PCRE regular expressions.
*
* @param c The character (cast to unsigned for the comparison).
* @return True if ASCII alphanumeric; false otherwise.
*/
int
is_ascii_alnum(unsigned char c) {
if ((c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9')) {
return 1;
}
else {
return 0;
}
}
/**
* Is the given character ASCII punctuation?
*
* ASCII punctuation symbols are the only characters that may need to be protected
* by a \ in regular expressions. They cannot form special escape sequences.
*
* @param c The character (cast to unsigned for the comparison).
* @return True if ASCII alphanumeric; false otherwise.
*/
int
is_ascii_punct(unsigned char c) {
switch (c) {
case '!':
case '"':
case '#':
case '$':
case '%':
case '&':
case '(':
case '\'':
case ')':
case '*':
case '+':
case ',':
case '-':
case '.':
case '/':
case ':':
case ';':
case '<':
case '=':
case '>':
case '?':
case '@':
case '[':
case '\\':
case ']':
case '^':
case '_':
case '`':
case '{':
case '|':
case '}':
case '~':
return 1;
default:
return 0;
}
}
/**
* Is the given character a valid hexadecimal digit?
*
* @param c The character (cast to unsigned for the comparison).
* @return True if valid hexidecimal digit; false otherwise.
*/
int
is_hexadecimal(unsigned char c) {
if ((c >= 'A' && c <= 'F') ||
(c >= 'a' && c <= 'f') ||
(c >= '0' && c <= '9')) {
return 1;
}
else {
return 0;
}
}
/**
* Read in an escape sequence for a character or class - part of the CL Regex Optimiser.
*
* This function reads one of the following escape sequences:
* \x##, \x{###} ... hexadecimal character code
* \o{###} ... octal character code
* \w, \W, \d, \D, \s, \S ... generic character types
* \p#, \p{###} ... Unicode properties
* \P#, \P{###} ... negated Unicode properties
* \X ... Unicode extended grapheme cluster
*/
char *
read_escape_seq(char *mark)
{
char *point = mark;
if (*point != '\\')
return mark;
else
point++;
switch (*point) {
case 'x':
point++;
if (*point == '{') {
point++;
while (is_hexadecimal(*point))
point++;
if (*point == '}')
return point + 1;
}
else {
if (is_hexadecimal(point[0]) && is_hexadecimal(point[1]))
return point + 2;
}
return mark; /* not recognised */
case 'o':
point++;
if (*point == 'o') {
point++;
while (*point >= '0' && *point <= '7')
point++;
if (*point == '}')
return point + 1;
}
return mark; /* not recognised */
case 'w':
case 'W':
case 'd':
case 'D':
case 's':
case 'S':
case 'X':
return point + 1;
case 'p':
case 'P':
point++;
if (*point >= 'A' && *point <= 'Z')
return point + 1;
else if (*point == '{') {
point++;
while (is_ascii_alnum(*point) || *point == '_' || *point == '&')
point++;
if (*point == '}')
return point + 1;
}
return mark; /* not recognised */
default:
return mark; /* not recognised */
}
}
/**
* Reads in an element matching some character - part of the CL Regex Optimiser.
*
* This function reads in an element known to match some character.
* The following elements are currently recognized:
* - a matchall (.)
* - a safe literal character or escaped ASCII punctuation
* - an escape sequence for a simple character class (\w, \d, etc.)
* - an escape sequence for a Unicode property
* - a hexadecimal (\x) or octal (\o) character code
* - a simple character set such as [a-z], [A-Z] and [0-9]
* The precise syntax of character sets is rather messy, so we will not
* make an attempt to recognize more complex sets.
*
* @param mark Pointer to location in the regex string from
* which to read.
* @return Pointer to the first character after the character
* (class) it has read in (or the original "mark"
* pointer if nothing suitable was found).
*/
char *
read_matchall(char *mark)
{
char *point = mark;
char *p2;
if (*mark == '.') {
/* read the matchall dot */
return mark + 1;
}
else if (is_safe_char(*mark)) {
/* a literal character */
if (cl_regopt_utf8)
return g_utf8_next_char(mark);
else
return mark + 1;
}
else if (*mark == '\\') {
/* check for a supported escape sequence */
return read_escape_seq(mark);
}
else if (*mark == '[') {
/* a character set */
point = mark + 1;
if (*point == '^')
point++; /* negated character set */
while (1) {
if (is_safe_char(*point) || (*point == '-'))
point++;
else {
p2 = read_escape_seq(point);
if (p2 > point)
point = p2;
else
break;
}
}
if (*point == ']' && point > mark + 1)
return point + 1; /* note that we exclude [] because of ambiguity with []..] */
}
return mark; /* no element has been recognized */
}
/**
* Reads in a repetition operator - part of the CL Regex Optimiser.
*
* This function reads in any repetition operator allowed in PCRE syntax:
* - * (Kleene star), ?, +
* - {n}, {n,m}, {,m}, {n,}
* - optionally followed by a non-greedy (?) or possessive (+) modifier
* it returns a pointer to the first character after the repetition modifier
* it has found. If *one_or_more is not null, it is set to True if the
* quantifier operator mandates at least one repetition (i.e. it does not
* make the preceding element optional).
*
* @param mark Pointer to location in the regex string from
* which to read.
* @param one_or_more Optional pointer to integer, which will be set
* to True if repetition is not optional.
* @return Pointer to the first character after the star
* or other modifier it has read in (or the original
* "mark" pointer if a repetition modifier was not
* read).
*/
char *
read_kleene(char *mark, int *one_or_more)
{
int plus = 0; /* repetition is non-optional, i.e. 1 or more */
int ok = 1; /* whether a valid quantifier has been recognized */
char *point = mark;
if (*point == '?' || *point == '*') {
plus = 0;
point++;
}
else if (*point == '+') {
plus = 1;
point++;
}
else if (*point == '{') {
point++;
plus = (*point >= '1' && *point <= '9');
while ((*point >= '0' && *point <= '9') || (*point == ',')) {
point++;
}
if (*point != '}')
ok = 0;
else
point++;
}
else
ok = 0;
if (ok) {
if (*point == '?' || *point == '+')
point++; /* lazy or possessive quantifier */
if (one_or_more)
*one_or_more = plus;
return point;
}
else
return mark;
}
/**
* Reads in a wildcard - part of the CL Regex Optimiser.
*
* This function reads in a wildcard segment consisting of an
* element matching some character (read_matchall) or a capturing
* or non-capturing group, followed by an optional quantifier (read_kleene).
* It returns a pointer to the first character after the wildcard segment.
*
* Groups are parsed recursively and must consist of one or more
* alternatives containing only valid wildcard segments.
*
* @param mark Pointer to location in the regex string from which to read.
* @return Pointer to the first character after the
* wildcard segment (or the original "mark" pointer
* if a wildcard segment was not found).
*/
char *
read_wildcard(char *mark)
{
char *point, *p2;
point = read_matchall(mark);
if (point > mark) {
return read_kleene(point, NULL);
}
else if (*point == '(') {
point++;
if (*point == '?') {
if (point[1] == ':')
point += 2; /* non-capturing group */
else
return mark; /* other special elements are not supported */
}
while (1) {
/* body of group must consist only of wildcard segments and disjunction operators */
p2 = read_wildcard(point);
if (p2 > point)
point = p2;
else if (*point == '|')
point++;
else
break;
}
if (*point == ')')
return read_kleene(point + 1, NULL);
}
return mark; /* no wildcard segment found */
}
/**
* Reads in a literal grain from a regex - part of the CL Regex Optimiser.
*
* A grain is a string of safe symbols: alphanumeric, safe punctuation and
* escaped punctuation; numeric character codes (\x, \u) are not supported.
* The last symbol might be followed by a repetition operator. It is only
* included in the grain if the repetition count is at least one.
*
* This function finds the longest grain it can starting at the point
* in the regex indicated by mark. If *grain is not NULL, the grain data
* are unescaped and copied to the specified buffer. Note that the buffer
* will be mangled even if no grain is matched; it is guaranteed to contain
* a NUL-terminated string, though. If *len is not null, the length of the
* grain (in characters) is stored there.
*
* @param mark Pointer to location in the regex string from
* which to read.
* @param grain Optional pointer to a buffer into which the grain data
* will be copied. Guaranteed to contain a NUL-terminated
* string even if no grain is found.
* @param len Pointer to integer in which length of grain in characters
* will be stored.
* @return Pointer to the first character after the grain
* it has read in (or the original "mark" pointer
* if no grain is found).
*/
char *
read_grain(char *mark, char *grain, int *len)
{
char *point = mark;
char *grain_point = grain;
char *grain_last_char = grain; /* pointer to start of last symbol in grain buffer */
char *end, *q;
int glen = 0; /* length of grain in characters */
int one_or_more;
/* read sequence of safe literal characters */
while (
is_safe_char(*point) ||
(*point == '\\' && is_ascii_punct(point[1]))
) {
if (*point == '\\') {
/* copy escaped character to grain */
if (grain) {
grain_last_char = grain_point;
*grain_point++ = point[1];
}
glen++;
point += 2;
}
else {
/* copy complete character to grain */
end = (cl_regopt_utf8) ? g_utf8_next_char(point) : point + 1;
if (grain) {
grain_last_char = grain_point;
for (q = point; q < end; q++) {
*grain_point++ = *q;
}
}
glen++;
point = end;
}
}
if (glen > 0) {
/* check for quantifier on last symbol of grain */
end = read_kleene(point, &one_or_more);
if (end > point) {
/* remove last symbol from grain if made optional by quantifier */
if (!one_or_more) {
glen--;
if (grain)
grain_point = grain_last_char;
}
}
point = end;
}
if (grain)
*grain_point = '\0'; /* NUL-terminated extracted grain */
if (len)
*len = glen;
if (glen > 0)
return point;
else
return mark;
}
/**
* Finds grains in a simple disjunction group - part of the CL Regex Optimiser.
*
* This function parses a simple parenthesized disjunction within a regular expression
* and attempts to extract one grain from each alternative. Grains are written to the
* local grain buffer. If a complete grain set has been found, the functions returns
* a pointer to the first character after the disjunction. Otherwise it returns mark
* and the caller can try to accept the group with read_matchall.
*
* For simplicity, only the first grain in each alternative is considered. This makes
* it easier to check start/end alignment of the grains. Note that the local grain
* buffer is always mangled, even if the function is unsuccessful.
*
* The first argument, mark, must point to the '(' at the beginning of the
* disjunction group (unless no_paren is set).
*
* The booleans align_start and align_end are set to true if the grains from
* *all* alternatives are anchored at the start or end of the disjunction
* group, respectively.
*
* This is a non-exported function.
*
* @param mark Pointer to the disjunction group (see also function
* description).
* @param align_start See function description.
* @param align_end See function description.
* @param no_paren Attempt to read a top-level disjunction without parentheses,
* which must extend to the end of the string.
* @return A pointer to first character after the disjunction group
* iff the parse succeeded, the original pointer in
* the mark argument otherwise.
*
*/
char *
read_disjunction(char *mark, int *align_start, int *align_end, int no_paren)
{
char *point, *p2, *buf;
int grain;
point = mark;
if (no_paren) {
if (*point == '(')
return mark; /* bare disjunction must not be parenthesized */
}
else {
if (*point == '(') {
point++;
if (*point == '?') {
point++;
/* don't accept special (?...) elements, except for simple non-capturing (?:...) */
if (*point == ':')
point++;
else
return mark; /* failed to parse disjunction */
}
}
else
return mark; /* disjunction group must be parenthesized */
}
buf = local_grain_data;
grain_buffer_grains = 0;
grain = 0;
/* Note: if we can extend the disjunction parser further to allow parentheses around the
* initial segment of an alternative, then regexen created by the matches operator will
* also be optimised. */
*align_start = *align_end = 1;
while (1) { /* loop over alternatives in disjunction, using first grain found in each */
p2 = read_grain(point, buf, &(grain_buffer_len[grain])); /* attempt to read a grain */
while (p2 == point) {
p2 = read_wildcard(point); /* try skipping a wildcard element */
if (p2 > point) {
point = p2; /* advance point and look for grain again */
*align_start = 0; /* grain in this alternative can't be aligned at start */
}
else
return mark; /* no grain found in this alternative -> unsuccessful */
p2 = read_grain(point, buf, &(grain_buffer_len[grain]));
}
grain_buffer[grain] = buf; /* store grain in local grain buffer */
buf += strlen(buf) + 1;
grain++;
if (grain >= MAX_GRAINS)
return mark; /* too many alternatives, can't extract full grain set */
point = p2;
while (*point != '|' && *point != ')') {
p2 = read_wildcard(point); /* try skipping data up to next | or ) */
if (p2 > point) {
point = p2;
*align_end = 0; /* grain in this alternative can't be aligned at end */
}
else
break;
}
if (*point == '|')
point++; /* continue with next alternative */
else
break; /* abort scanning */
} /* end of while (1) loop over alternatives in disjunction */
if ((!no_paren && *point == ')') ||
(no_paren && *point == '\0')) {
/* we've successfully read the entire disjunction */
grain_buffer_grains = grain;
if (grain >= 1)
return point + 1; /* success */
}
return mark; /* unsuccessful */
}
/**
* Updates the public grain buffer -- part of the CL Regex Optimiser.
*
* This function copies the local grains to the public buffer, if they
* are better than the set of grains currently there. The decision is
* made with a heuristic based on the character length of the shortest
* grain and the number of different grains.
*
* A non-exported function.
*
* @param at_start Boolean: if True, all grains are anchored on the left
* @param at_end Boolean: if True, all grains are anchored on the right
*
*/
void
update_grain_buffer(int at_start, int at_end)
{
char *buf = public_grain_data;
int i, len, N;
N = grain_buffer_grains;
if (N > 0) {
len = grain_buffer_len[0];
for (i = 1; i < N; i++) {
if (grain_buffer_len[i] < len)
len = grain_buffer_len[i];
}
if (len >= 2) { /* minimum grain length is 2 */
/* we make a heuristic decision whether the new set of grains is better than the current one;
based on grain length and the number of grains */
if (
(len > (cl_regopt_grain_len + 1))
|| ((len == (cl_regopt_grain_len + 1)) && (N <= (3 * cl_regopt_grains) ))
|| ((len == cl_regopt_grain_len) && (N < cl_regopt_grains))
|| ((len == (cl_regopt_grain_len - 1)) && ((3 * N) < cl_regopt_grains))
) {
/* the new set of grains is better, copy them to the output buffer */
for (i = 0; i < N; i++) {
strcpy(buf, grain_buffer[i]);
cl_regopt_grain[i] = buf;
buf += strlen(buf) + 1;
}
cl_regopt_grains = N;
cl_regopt_grain_len = len;
cl_regopt_anchor_start = at_start;
cl_regopt_anchor_end = at_end;
}
}
}
}
/**
* Computes a jump table for Boyer-Moore searches -- part of the CL Regex Optimiser.
*
* Unlike the textbook version, this jumptable includes the last character of each grain
* (so we don't have to start the string comparison loops every time).
*
* A non-exported function.
*/
void
make_jump_table(CL_Regex rx)
{
int j, k, jump;
unsigned int ch;
unsigned char *grain; /* want unsigned char to compare with unsigned int ch */
/* clear the jump table */
for (ch = 0; ch < 256; ch++)
rx->jumptable[ch] = 0;
if (rx->grains > 0) {
/* compute smallest jump distance for each byte (0 -> matches last byte of one or more grains) */
for (ch = 0; ch < 256; ch++) {
jump = rx->grain_len; /* if character isn't contained in any of the grains, jump by grain length */
for (k = 0; k < rx->grains; k++) { /* for each grain... */
grain = (unsigned char *) rx->grain[k] + rx->grain_len - 1; /* pointer to last byte in grain */
for (j = 0; j < rx->grain_len; j++, grain--) {
if (*grain == ch) {
if (j < jump)
jump = j;
break; /* can't find shorter jump distance for this grain */
}
}
}
rx->jumptable[ch] = jump;
}
if (cl_debug) { /* in debug mode, print out the entire jumptable */
Rprintf("CL: cl_regopt_jumptable for Boyer-Moore search is\n");
for (k = 0; k < 256; k += 16) {
Rprintf("CL: ");
for (j = 0; j < 15; j++) {
ch = k + j;
if ((ch >= 32) & (ch < 127))
Rprintf("|%2d %c ", rx->jumptable[ch], ch);
else
Rprintf("|%2d %02X ", rx->jumptable[ch], ch);
}
Rprintf("\n");
}
}
}
/* if no grains have been found, don't do anything (just clear the jump table) */
}
/**
* Copy grain set from internal global variables to CL_Regex object -- part of the CL Regex Optimiser.
*
* This function carries out four important tasks:
* - It copies the grain set found by cl_regopt_analyse from the internal global buffer
* to member variables of the specified CL_Regex object.
* - It casefolds the grains if required (i.e. if rx->icase is True).
* - It cuts grains to equal byte length, preserving start/end anchoring if possible.
* Note that our implementation of Boyer-Moore search requires equally sized grains.
* - It calls make_jump_table to generate a lookup table for the Boyer-Moore search.
*
* This is a non-exported function.
*
* @param rx a pointer to an initialized CL_Regex object
*/
void
regopt_data_copy_to_regex_object(CL_Regex rx)
{
char *grain;
int i, l, len, cut_prefix;
rx->grains = cl_regopt_grains;
if (rx->icase) {
/* casefold strings if required (in case this reduces byte length) */
grain = local_grain_data; /* we can use this static buffer for the casefolded grains */
for (i = 0; i < rx->grains; i++) {
strcpy(grain, cl_regopt_grain[i]);
cl_string_canonical(grain, rx->charset, IGNORE_CASE, CL_MAX_LINE_LENGTH);
cl_regopt_grain[i] = grain; /* pointers into static buffer, so we can just move them */
grain += strlen(grain) + 1;
}
}
/* determine common byte length of grains */
len = CL_MAX_LINE_LENGTH;
for (i = 0; i < rx->grains; i++) {
l = strlen(cl_regopt_grain[i]);
if (l < len)
len = l;
}
/* determine whether to remove prefix or suffix of grains to reduce to common length */
cut_prefix = (cl_regopt_anchor_end && !cl_regopt_anchor_start);
/* now allocate copy of each grain (reduced to specified number of bytes) */
for (i = 0; i < rx->grains; i++) {
grain = cl_regopt_grain[i];
l = strlen(grain);
if (l > len) {
/* need to shorten */
if (cut_prefix) {
rx->grain[i] = cl_strdup(grain + l - len);
cl_regopt_anchor_start = 0; /* no longer anchored left */
}
else {
rx->grain[i] = cl_strdup(grain);
rx->grain[i][len] = '\0';
cl_regopt_anchor_end = 0; /* no longer anchored right */
}
}
else {
/* grain already has the desired length */
rx->grain[i] = cl_strdup(grain);
}
}
rx->grain_len = len;
rx->anchor_start = cl_regopt_anchor_start;
rx->anchor_end = cl_regopt_anchor_end;
if (cl_debug) {
Rprintf("CL: Regex optimised, %d grain(s) of length %d\n",
rx->grains, rx->grain_len);
Rprintf("CL: grain set is");
for (i = 0; i < rx->grains; i++) {
Rprintf(" [%s]", rx->grain[i]);
}
if (rx->anchor_start)
Rprintf(" (anchored at beginning of string)");
if (rx->anchor_end)
Rprintf(" (anchored at end of string)");
Rprintf("\n");
}
/* compute jump table for Boyer-Moore search */
if (rx->grains > 0)
make_jump_table(rx);
if (cl_debug)
Rprintf("CL: using %d grain(s) for optimised regex matching\n", rx->grains);
}
/**
* Analyses a regular expression and tries to find the best set of grains.
*
* Part of the regex optimiser. For a given regular expression, this function will
* try to extract a set of grains from regular expression {regex_string}. These
* grains are then used by the CL regex matcher and cl_regex2id() as a pre-filter
* for faster regular expression search.
*
* The function only recognizes relatively simple regular expressions without
* recursive nesting, which roughly correspond to wildcard searches similar to
* SQL's LIKE operator. Searching for a fixed prefix, suffix or infix (or a
* small set of alternatives) will see the most noticeable performance improvement.
* Any more complex expression is passed directly to the standard PCRE evaluation.
* See cl_new_regex() for an overview of the supported subsets of PCRE syntax.
*
* If successful, this function returns True and stores the grains
* in the optiomiser's global variables above, from which they then must be
* copied to a CL_Regex object with regopt_data_copy_to_regex_object(). This step
* will also casefold grains if necessary and prepare the Boyer-Moore jump tables.
*
* Usage: optimised = cl_regopt_analyse(regex_string);
*
* This is a non-exported function.
*
* @param regex String containing the regex to optimise.
* @return Boolean: true = ok, false = couldn't optimise regex.
*/
int
cl_regopt_analyse(char *regex)
{
char *point, *mark;
int ok, at_start, at_end, one_or_more, align_start, align_end;
mark = regex;
if (cl_debug) {
Rprintf("CL: cl_regopt_analyse('%s')\n", regex);
}
cl_regopt_grains = 0;
cl_regopt_grain_len = 0;
cl_regopt_anchor_start = cl_regopt_anchor_end = 0;
/**
* The code below parses a regular expression using the supported PCRE subset
* and attempts to extract a literal string ("grain") that must occur in every
* match of the regular expression. In a disjunction group, each alternative
* must contain a grain in order to be used for optimized matching; we refer to
* this as a complete grain set.
*
* The algorithm scans the regular expression from left to right,
* looking for the following supported elements in the specified order:
*
* 1. a literal grain (read_grain)
* 2. a parenthesized disjunction containing grains (read_disjunction)
* 3. a segment matching some, possibly empty substring (read_wildcard),
* including recursively nested capturing or non-capturing groups
*
* See the respective functions for further information on these elements.
* Grains are collected by read_grain and read_disjunction in a local buffer.
* If a complete grain set has been found, it replaces the previous global
* grain set if it is considered to be more effective based on the length
* and number of grains.
*
* As a special case, the optimizer first attempts to match the entire
* regexp as a simple disjunction (read_disjunction) without parentheses.
*/
/* check for a bare disjunction at top level (not parenthesized) */
point = read_disjunction(mark, &align_start, &align_end, 1);
if (point > mark) {
update_grain_buffer(align_start, align_end);
return (cl_regopt_grains > 0) ? 1 : 0;
}
ok = 1;
while (ok) {
/* accept if we're at end of string */
if (*mark == '\0') {
ok = (cl_regopt_grains > 0) ? 1 : 0;
return ok;
}
at_start = (mark == regex);
/* check for a grain */
point = read_grain(mark, local_grain_data, &(grain_buffer_len[0]));
if (point > mark) {
grain_buffer[0] = local_grain_data;
grain_buffer_grains = 1;
mark = point;
/* update public grain set */
at_end = (*mark == '\0');
update_grain_buffer(at_start, at_end);
}
else {
/* check for a simple parenthesized disjunction */
point = read_disjunction(mark, &align_start, &align_end, 0);
if (point > mark) {
mark = point;
at_end = (*mark == '\0'); /* can only be anchored if there's no quantifier */
/* can't accept grain set if there's a quantifier that makes the group optional */
point = read_kleene(mark, &one_or_more);
if (point == mark)
one_or_more = 1; /* no quantifier found, so not optional */
else
mark = point;
if (one_or_more) {
/* update public grain set */
at_start = (at_start && align_start); /* check that grains within disjunction are aligned, too */
at_end = (at_end && align_end);
update_grain_buffer(at_start, at_end);
}
}
else {
point = read_wildcard(mark);
if (point > mark) { /* found segment matching some (possibly empty) substring -> skip */
mark = point;
}
else {
ok = 0; /* no recognised segment starting at mark */
}
}
}
} /* end of while (ok) */
/* couldn't analyse regexp -> no optimisation */
return 0;
}
/* two monitoring functions */
/**
* Reset the "success counter" for optimised regexes.
*/
void
cl_regopt_count_reset(void)
{
cl_regopt_successes = 0;
}
/**
* Get a reading from the "success counter" for optimised regexes.
*
* The counter is incremented by 1 every time the "grain" system
* is used successfully to avoid calling PCRE. That is, it is
* incremented every time a string is scrutinised and found to
* contain none of the grains.
*
* Usage:
*
* cl_regopt_count_reset();
*
* for (i = 0, hits = 0; i < n; i++)
* if (cl_regex_match(rx, haystacks[i]))
* hits++;
*
* Rprintf(
* "Found %d matches; avoided regex matching %d times out of %d trials",
* hits, cl_regopt_count_get(), n );
*
* @see cl_regopt_count_reset
* @return an integer indicating the number of times a regular expression
* has been matched using the regopt system of "grains", rather
* than by calling an external regex library.
*/
int
cl_regopt_count_get(void)
{
return cl_regopt_successes;
}
|
myoKun345/RcppCWB
|
src/cwb/cqp/eval.h
|
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
#ifndef _cqp_eval_h_
#define _cqp_eval_h_
#include "../cl/cdaccess.h"
#include "regex2dfa.h"
#include "corpmanag.h"
#include "symtab.h"
#include "options.h"
#define repeat_inf -1 /**< constant which indicates 'infinite repetition' (actually, repetition up to hard_boundary) @see hard_boundary */
#define repeat_none -2 /**< constant which indicates 'no repetition' */
/** Number of AVStructures to put in each Patternlist */
#define MAXPATTERNS 5000
/** maximum number of EvalEnvironments iin the global array */
#define MAXENVIRONMENT 10
/*
* definition of the evaluation tree of boolean expressions
*/
/**
* Labels a boolean operation.
*/
enum b_ops { b_and, /**< boolean and operator */
b_or, /**< boolean or operator */
b_implies, /**< boolean implication (->) operator */
b_not, /**< boolean negation */
cmp_gt, /**< compare: greater than */
cmp_lt, /**< compare: less than */
cmp_get, /**< compare: greater or equal than */
cmp_let, /**< compare: less or equal than */
cmp_eq, /**< compare: equal */
cmp_neq, /**< compare: not equal */
cmp_ex /**< is value present? bool exprs */
};
/**
* Labels the type of a {what??}.
*/
enum wf_type { NORMAL, REGEXP, CID };
/**
* Labels the type of a boolean node.
*/
enum bnodetype { bnode, /**< boolean evaluation node */
cnode, /**< constant node */
func, /**< function call */
sbound, /**< structure boundary (open or close) */
pa_ref, /**< reference to positional attribute */
sa_ref, /**< reference to structural attribute */
string_leaf, /**< string constant */
int_leaf, /**< integer constant */
float_leaf, /**< float constant */
id_list, /**< list of IDs */
var_ref /**< variable reference */
};
/**
* Union of structures underlying the Constraint / Constrainttree objects.
*
* Each Constraint is a node in the Constrainttree, i.e. a single element of a compiled CQP query.
*/
typedef union c_tree {
/** The type of this particular node.
* Allows the type member of the other structures within the union to be accessed. */
enum bnodetype type;
/** "standard" operand node in the evaluation tree; type is "bnode" */
struct {
enum bnodetype type; /**< must be bnode */
enum b_ops op_id; /**< identifier of the bool operator */
union c_tree *left, /**< points to the first operand */
*right; /**< points to the second operand,
if present */
} node;
/** "constant" node in the evaluation tree */
struct {
enum bnodetype type; /**< must be cnode */
int val; /**< Value of the constant: 1 or 0 for true or false */
} constnode;
/** function call (dynamic attribute), type is "func" */
struct {
enum bnodetype type; /**< must be func */
int predef;
Attribute *dynattr;
struct _ActualParamList *args; /**< arguments of the function */
int nr_args; /**< nr of arguments for this call */
} func;
/** structure boundary */
struct {
enum bnodetype type; /**< must be sbound */
Attribute *strucattr; /**< the attribute which corresponds to the structure */
Boolean is_closing; /**< True if closing tag, False for opening tag */
} sbound;
/** reference to positional attribute */
struct {
enum bnodetype type; /**< must be pa_ref */
LabelEntry label; /**< may be empty (NULL) */
Attribute *attr; /**< the P-attribute we are referring to */
int delete; /**< delete label after using it ? */
} pa_ref;
/**
* reference to structural attribute.
*
* If label is empty, this checks if the current position is at start
* or end of structural_attribute and returns INT value (this is kept for
* backward compatibility regarding lbound() and rbound() builtins; the new
* syntax is to use {s} and {/s}, which are represented as 'Tag' nodes.
*
* If label is non-empty, the referenced S-attribute must have values, and
* the value of the enclosing region is returned as a string; in short,
* values of attributes can be accessed through label references .
*/
struct {
enum bnodetype type; /**< must be sa_ref */
LabelEntry label; /**< may be empty (NULL) */
Attribute *attr; /**< the s-attribute we are referring to */
int delete; /**< delete label after using it ? */
} sa_ref;
struct {
enum bnodetype type; /**< must be var_ref */
char *varName;
} varref;
struct {
enum bnodetype type; /**< must be id_list */
Attribute *attr;
LabelEntry label; /**< may be empty (NULL) */
int negated;
int nr_items;
int *items; /**< an array of item IDs of size nr_items */
int delete; /**< delete label after using it ? */
} idlist;
/** constant (string, int, float, ...) */
struct {
enum bnodetype type; /**< string_leaf, int_leaf, or float_leaf */
int canon; /**< canonicalization mode (i.e. flags) */
enum wf_type pat_type; /**< pattern type: normal wordform or reg. exp. */
CL_Regex rx; /**< compiled regular expression (using CL frontend) */
/** Union containing the constant type. */
union {
char *sconst; /**< operand is a string constant. */
int iconst; /**< operand is a integer constant. */
int cidconst; /**< operand is {?? corpus position?? corpus lexicon id??} constant */
double fconst; /**< operand is a float (well, double) constant */
} ctype;
} leaf;
} Constraint;
/**
* The Constrainttree object.
*/
typedef Constraint *Constrainttree;
/**
* The ActualParamList object: used to build a linked list of parameters,
* each one of which is a Constrainttree.
*/
typedef struct _ActualParamList {
Constrainttree param;
struct _ActualParamList *next;
} ActualParamList;
/** Enumeration specifying different types of tree node */
enum tnodetype { node, leaf, meet_union, tabular };
enum re_ops { re_od_concat, /* order dependent concat. */
re_oi_concat, /* order independent concat. */
re_disj, /* disjunction */
re_repeat /* repetition ({n} and {n,k})*/
};
enum cooc_op { cooc_meet,
cooc_union
};
/**
* Evaltree object
*
* (TODO specify here what on earth one of these is)
*/
typedef union e_tree *Evaltree;
/* cross-check treemacros.h after changes of this data structure!!!
* also check the print commands in tree.c */
/**
* Underlying union for the Evaltree object.
*
* Consists of a number of anonymous-type structures
* (node, leaf, cooc, tab_el) that can be found in a tree.
*
* The type member is always accessible.
*
* @see tnodetype
*/
union e_tree {
/** What type of node does this union represent? */
enum tnodetype type;
/** node type: node */
struct {
enum tnodetype type;
enum re_ops op_id; /**< id_number of the RE operator */
Evaltree left, /**< points to the first argument */
right; /**< points to the second argument -- if it exists. */
int min, /**< minimum number of repetitions. */
max; /**< maximum number of repetitions. */
} node;
/** node type: leaf */
struct {
enum tnodetype type;
int patindex; /**< index to the patternlist */
} leaf;
/** node type: meet_union */
struct {
enum tnodetype type;
enum cooc_op op_id;
int lw, rw;
Attribute *struc;
Evaltree left, right;
} cooc;
/** node type: tabular */
struct {
enum tnodetype type;
int patindex; /**< index into pattern list */
int min_dist; /**< minimal distance to next pattern */
int max_dist; /**< maximal distance to next pattern */
Evaltree next; /**< next pattern */
} tab_el;
};
/* definition of the patternlist, which builds the 'character set' for the
* regular expressions of wordform patterns
*/
typedef enum _avstype {
Pattern, Tag, MatchAll, Anchor
} AVSType;
/**
* The AVStructure object.
*
* A union of structures with the type member always accessible.
*/
typedef union _avs {
/** What type of AV structure does this union represent? */
AVSType type;
/** a matchall item */
struct {
AVSType type; /* set to MatchAll */
LabelEntry label;
Boolean is_target;
Boolean lookahead; /**< whether pattern is just a lookahead constraint */
} matchall;
/** a constraint tree */
struct {
AVSType type; /* set to Pattern */
LabelEntry label;
Constrainttree constraint;
Boolean is_target;
Boolean lookahead; /**< whether pattern is just a lookahead constraint */
} con;
/** a structure describing tag */
struct {
AVSType type; /* set to Tag */
int is_closing;
Attribute *attr;
char *constraint; /**< constraint for annotated value of region (string or regexp); NULL = no constraint */
int flags; /**< flags passed to regexp or string constraint (information purposes only) */
CL_Regex rx; /**< if constraint is a regexp, this holds the compiled regexp; otherwise NULL */
int negated; /**< whether constraint is negated (!=, not matches, not contains) */
LabelEntry right_boundary; /**< label in RDAT namespace: contains right boundary of constraining region (in StrictRegions mode) */
} tag;
/* an anchor point tag (used in subqueries) */
struct {
AVSType type; /* set to Anchor */
int is_closing;
FieldType field;
} anchor;
} AVStructure;
/** AVS is a pointer type for AVStructure */
typedef AVStructure *AVS;
/** Patternlist is an array of AVStructures */
typedef AVStructure Patternlist[MAXPATTERNS];
/* ====================================================================== */
enum ctxtdir { leftright, left, right };
enum spacet { word, structure };
/**
* The Context object.
*
* This stores information about contexts.
*
* "Context" here means the context for evaluation of a query result within
* a corpus. (???)
*/
typedef struct ctxtsp {
enum ctxtdir direction; /**< direction of context expansion (if valid).
Might be left, right, or leftright*/
enum spacet type; /**< kind of space (word or structure) */
Attribute *attrib; /**< attribute representing the structure. */
int size; /**< size of space in number of structures. */
int size2; /**< only for meet-context */
} Context;
/* ====================================================================== */
/**
* Global eval environment pointer (actually an array index, not a pointer).
*
* eep contains the index of the highest currently-occupied slot within Environment.
* @see Environment
*/
int eep;
/**
* The EvalEnvironment object: environment variables for the evaluation of
* a corpus query.
*/
typedef struct evalenv {
CorpusList *query_corpus; /**< the search corpus for this query part */
int rp; /**< index of current range (in subqueries) */
SymbolTable labels; /**< symbol table for labels */
int MaxPatIndex; /**< the current number of patterns */
Patternlist patternlist; /**< global variable which holds the pattern list */
Constrainttree gconstraint; /**< the "global constraint" */
Evaltree evaltree; /**< the evaluation tree (with regular exprs) */
DFA dfa; /**< the regex DFA for the current query */
int has_target_indicator; /**< is there a target mark ('@') in the query? */
LabelEntry target_label; /**< targets are implemented as a special label "target" now */
LabelEntry match_label; /**< special "match" and "matchend"-Labels for access
to start & end of match within query */
LabelEntry matchend_label;
Context search_context; /**< the search context (within...) */
Attribute *aligned; /**< the attribute holding the alignment info */
int negated; /**< 1 iff we should negate alignment constr */
enum _matching_strategy matching_strategy; /**< copied from global option unless overwritten by (?...) directive */
} EvalEnvironment;
/**
* EEPs are Eval Environment pointers.
*/
typedef EvalEnvironment *EEP;
/** A global array of EvalEnvironment structures */
EvalEnvironment Environment[MAXENVIRONMENT];
EEP CurEnv, evalenv;
/* ---------------------------------------------------------------------- */
Boolean eval_bool(Constrainttree ctptr, RefTab rt, int corppos);
/* ==================== the three query types */
void cqp_run_query(int cut, int keep_old_ranges);
void cqp_run_mu_query(int keep_old_ranges, int cut_value);
void cqp_run_tab_query();
/* ======================================== */
int next_environment();
int free_environment(int thisenv);
void show_environment(int thisenv);
void free_environments();
#endif
|
myoKun345/RcppCWB
|
src/cwb/cqp/parse_actions.c
|
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
#include "parse_actions.h"
#include <stdlib.h>
#include <sys/time.h>
#ifndef __MINGW__
#include <sys/resource.h>
#else
#include <windows.h>
#endif
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdarg.h>
#include <unistd.h>
#include "../cl/globals.h"
#include "../cl/special-chars.h"
#include "../cl/attributes.h"
#include "../cl/macros.h"
#include "cqp.h"
#include "options.h"
#include "ranges.h"
#include "symtab.h"
#include "treemacros.h"
#include "tree.h"
#include "eval.h"
#include "corpmanag.h"
#include "regex2dfa.h"
#include "builtins.h"
#include "groups.h"
#include "targets.h"
#include "attlist.h"
#include "concordance.h"
#include "output.h"
#include "print-modes.h"
#include "variables.h"
/* ======================================== GLOBAL PARSER VARIABLES */
/**
* TODO would be very useful to have a desc for this
*
* A boolean; seems to be some kind of error-indicator (set to true
* if a query worked, false if it didn't, things like that).
*
* When it is false, many actions simply have no effect, because they are
* set to only actually do anything "if (generate_code)".
*
* Some functions will set it to 0 when an action works to block later actions.
*
* In some cases, setting this to 0 is linked with "YYABORT" in comments.
*/
int generate_code;
int within_gc; /**< TODO would be very useful to have a desc for this ;
seems to be about whether or not we are within a global constraint */
CYCtype last_cyc; /**< type of last corpus yielding command */
/** The corpus (or subcorpus) which is "active" in the sense that the query will be executed within it. */
CorpusList *query_corpus = NULL;
/** Used for preserving former values of query_corpus (@see query_corpus), so it can be reset to a former value). */
CorpusList *old_query_corpus = NULL;
int catch_unknown_ids = 0;
/**
* This is used by the parser in response to CQP's "expand" operator,
* which incorporates context around the query hit into the match itself.
* Functions involved in carrying this out utilise info stored here by the parser.
*/
Context expansion;
/**
* Buffer for storing regex strings. As it says on the tin.
*
* TODO Doesn't seem currently to be in use anywhere, except in one func which itself is not used.
*/
char regex_string[CL_MAX_LINE_LENGTH];
/** index into the regex string buffer, storing a current position. @ see regex_string_pos */
int regex_string_pos;
/** length of search string: is written to by evaltree2searchstr() but then seems never to be read. TODO . */
int sslen;
/* ======================================== predeclared functions */
char *mval_string_conversion(char *s);
/* ======================================== PARSER ACTIONS */
/* ======================================== Syntax rule: line -> command */
/**
* Add a line of CQP input to the history file.
*
* Supports parser rule: line -> command
*
* The line that is added comes from QueryBuffer; the file it is
* written to is that named in cqp_history_file.
*
* @see QueryBuffer
* @see cqp_history_file
*/
void
addHistoryLine(void)
{
if (cqp_history_file != NULL &&
cqp_history_file[0] != '\0' &&
write_history_file &&
!silent &&
!reading_cqprc) {
if (QueryBuffer[0] != '\0') {
FILE *fd;
if (!(fd = open_file(cqp_history_file, "a"))) {
cqpmessage(Error, "Can't open history file %s\n", cqp_history_file);
}
else {
fputs(QueryBuffer, fd);
fputc('\n', fd);
fclose(fd);
}
}
}
}
/**
* Empties the query buffer and sets to 0 the pointer.
*
* Supports parser rule: line -> command
*
* @see QueryBuffer
* @see QueryBufferP
*/
void
resetQueryBuffer(void)
{
/* Rprintf("+ Resetting Query Buffer\n"); */
QueryBufferP = 0;
QueryBuffer[0] = '\0';
QueryBufferOverflow = 0;
}
void
RaiseError(void)
{
generate_code = 0;
resetQueryBuffer();
}
void
prepare_parse(void)
{
if (old_query_corpus != NULL) {
query_corpus = old_query_corpus;
old_query_corpus = NULL;
cqpmessage(Warning, "Query corpus reset");
}
generate_code = 1;
}
/* ======================================== Syntax rule: command -> CorpusCommand ';' */
CorpusList *
in_CorpusCommand(char *id, CorpusList *cl)
{
if (cl == NULL)
return NULL;
else if (is_qualified(id)) {
cqpmessage(Warning,
"You can't use a qualified corpus name on the\n"
"left hand side of an assignment (result in \"Last\")");
return NULL;
}
else if (cl->type == SYSTEM) {
cqpmessage(Warning, "System corpora can't be duplicated.");
return NULL;
}
else {
duplicate_corpus(cl, id, True);
last_cyc = Assignment;
return current_corpus;
}
}
/**
* Set the current corpus and
* do the output if it was a query
*/
void
after_CorpusCommand(CorpusList *cl)
{
#if defined(DEBUG_QB)
if (QueryBufferOverflow)
Rprintf("+ Query Buffer overflow.\n");
else if (QueryBuffer[0] == '\0')
Rprintf("+ Query Buffer is empty.\n");
else
Rprintf("Query buffer: >>%s<<\n", QueryBuffer);
#endif
switch (last_cyc) {
case Query:
if (cl) {
if (subquery)
set_current_corpus(cl, 0);
if (autoshow && (cl->size > 0)) {
catalog_corpus(cl, NULL, 0, -1, GlobalPrintMode);
}
else if (!silent)
Rprintf("%d matches.%s\n",
cl->size,
(cl->size > 0 ? " Use 'cat' to show." : ""));
}
query_corpus = NULL;
break;
case Activation:
if (cl)
set_current_corpus(cl, 0);
break;
case SetOperation:
if (cl) {
if (subquery)
set_current_corpus(cl, 0);
if (autoshow && (cl->size > 0))
catalog_corpus(cl, NULL, 0, -1, GlobalPrintMode);
else if (!silent)
Rprintf("%d matches.%s\n",
cl->size,
(cl->size > 0 ? " Use 'cat' to show."
: ""));
}
break;
default:
break;
}
if (auto_save && cl && (cl->type == SUB) && (cl->saved == False))
save_subcorpus(cl, NULL);
LastExpression = last_cyc;
last_cyc = NoExpression;
}
/* ======================================== UnnamedCorpusCommand -> CYCommand ReStructure */
/**
* This function is called after an UnnamedCorpusCommand rule is parsed.
*
* Seems to be a tidying-up function.
*
* @param cl The result of the corpus-yielding command (first component of this syntax rule).
* @return Modified valuse of cl. May be NULL.
*/
CorpusList *
in_UnnamedCorpusCommand(CorpusList *cl)
{
CorpusList *res = NULL;
cqpmessage(Message, "Command: UnnamedCorpusCommand");
if (cl != NULL) {
switch (last_cyc) {
case Query:
/* the last command was a query */
assert(cl->type == TEMP); /* should be true since the last command was a query! */
if (generate_code) {
expand_dataspace(cl);
do_timing("Query result computed"); /* timer must be started by each query execution command */
/* set the "corpus" created by the query to be the default "Last" subcorpus. */
res = assign_temp_to_sub(cl, "Last");
}
else
res = NULL;
drop_temp_corpora();
break;
case Activation:
/* Last command was not a query, that is, it was a corpus activation.
* We only have to copy if we want to expand the beast.
*/
if (expansion.size > 0) {
if (cl->type == SYSTEM) {
cqpmessage(Warning, "System corpora can't be expanded");
res = cl;
}
else {
res = make_temp_corpus(cl, "RHS");
expand_dataspace(res);
res = assign_temp_to_sub(res, "Last");
}
}
else {
/* a simple activation without restructuring */
res = cl;
}
break;
case SetOperation:
assert(cl->type == TEMP);
expand_dataspace(cl);
res = assign_temp_to_sub(cl, "Last");
drop_temp_corpora();
break;
default:
cqpmessage(Warning, "Unknown CYC type: %d\n", last_cyc);
res = NULL;
break;
}
}
free_environments();
return res;
}
/* ======================================== Corpus Yielding Commands */
CorpusList *
ActivateCorpus(CorpusList *cl)
{
cqpmessage(Message, "CorpusActivate: %s", cl);
if (inhibit_activation) {
Rprintf("Activation prohibited\n");
exit(1); /* hard way! */
}
else {
query_corpus = cl;
if (query_corpus) {
if (!next_environment()) {
cqpmessage(Error, "Can't allocate another evaluation environment");
generate_code = 0;
query_corpus = NULL;
}
else
CurEnv->query_corpus = query_corpus;
}
last_cyc = Activation;
}
return cl;
}
CorpusList *
after_CorpusSetExpr(CorpusList *cl)
{
last_cyc = SetOperation;
if (!next_environment()) {
cqpmessage(Error,
"Can't allocate another evaluation environment");
generate_code = 0;
CurEnv->query_corpus = NULL;
}
else
CurEnv->query_corpus = cl;
return cl;
}
/**
* This function sets things up to run a query.
*
* It is called as an "action" before any detected Query in the parser.
*
* [AH 2010/8/2: I have added the code checking input character encoding.
* Anything that is not part of a query should be plain ASCII - if not,
* then the lexer/parser should pick it up as bad. Filenames, etc. are
* obvious exceptions - but we can't check the encoding of those, because
* there's no guarantee it will be the same as that of the corpus, which
* is the only thing whose encoding we know. So it's up to the user to
* type filenames in an encoding their OS will accept!
* Canonicalisation is done within the CL_Regex, not here.]
*/
void
prepare_Query()
{
generate_code = 1;
/* check whether we've got a corpus loaded */
if (current_corpus == NULL) {
cqpmessage(Error, "No corpus activated");
generate_code = 0;
}
else if (!access_corpus(current_corpus)) {
cqpmessage(Error, "Current corpus can't be accessed");
generate_code = 0;
}
if (generate_code) {
assert(current_corpus->corpus != NULL);
assert(searchstr == NULL);
assert(eep == -1);
/* validate character encoding according to that corpus, now we know it's loaded */
if (!cl_string_validate_encoding(QueryBuffer, current_corpus->corpus->charset, 0)) {
cqpmessage(Error, "Query includes a character or character sequence that is invalid\n"
"in the encoding specified for this corpus");
generate_code = 0;
}
if (!next_environment()) {
cqpmessage(Error, "Can't allocate another evaluation environment");
generate_code = 0;
query_corpus = NULL;
}
else {
int before, after;
assert(eep == 0);
assert(CurEnv == &(Environment[0]));
query_corpus = make_temp_corpus(current_corpus, "RHS");
CurEnv->query_corpus = query_corpus;
/* subqueries don't work properly if the mother corpus has overlapping regions -> delete and warn */
before = query_corpus->size;
RangeSetop(query_corpus, RNonOverlapping, NULL, NULL);
after = query_corpus->size;
if (after < before) {
cqpmessage(Warning, "Overlapping matches in %s:%s deleted for subquery execution.",
query_corpus->mother_name, query_corpus->name);
}
}
}
within_gc = 0;
}
CorpusList *
after_Query(CorpusList *cl)
{
last_cyc = Query;
within_gc = 0;
if (generate_code) {
if (cl) {
cl_free(cl->query_text);
cl_free(cl->query_corpus);
if (query_corpus)
cl->query_corpus = cl_strdup(query_corpus->name);
/* this is probably where we want to auto-execute the reduce to maximal stuff */
if (QueryBuffer[0] != '\0' &&
QueryBufferP > 0 &&
!QueryBufferOverflow) {
cl->query_text = cl_strdup(QueryBuffer);
}
}
return cl;
}
else
return NULL;
}
/* ======================================== ``interactive'' commands */
void
do_cat(CorpusList *cl, struct Redir *r, int first, int last)
{
if (cl) {
cqpmessage(Message, "cat command: (%s)", cl->name);
catalog_corpus(cl, r, first, last, GlobalPrintMode);
}
}
void
do_echo(char *s, struct Redir *rd) {
char *r, *w;
if (!open_stream(rd, unknown_charset)) {
cqpmessage(Error, "Can't redirect output to file or pipe\n");
return;
}
/* make copy of s to interpret \t, \r and \n escapes */
s = cl_strdup(s);
r = w = s;
while (*r) {
if (*r == '\\' && *(r + 1)) {
if (*(r + 1) == 't') {
*w++ = '\t';
r += 2;
}
else if (*(r + 1) == 'r') {
*w++ = '\r';
r += 2;
}
else if (*(r + 1) == 'n') {
*w++ = '\n';
r += 2;
}
else {
*w++ = *r++; /* pass through all other escaped symbols */
*w++ = *r++;
}
}
else {
*w++ = *r++;
}
}
*w = '\0'; /* terminate modified string */
Rprintf("%s", s);
cl_free(s);
close_stream(rd);
}
void
do_save(CorpusList *cl, struct Redir *r)
{
if (cl) {
if (!LOCAL_CORP_PATH)
cqpmessage(Warning,
"Can't save subcorpus ``%s'' (env. var. %s isn't set)", /* TODO: isn't this a bit misleading? Would be better to say "you must set DataDirectory".... */
cl->name,
DEFAULT_LOCAL_PATH_ENV_VAR);
else {
cqpmessage(Message, "save command: %s to %s", cl->name, r->name);
save_subcorpus(cl, r->name);
}
}
}
/* ======================================== show attribute */
void
do_attribute_show(char *name, int status)
{
AttributeInfo *ai;
if ((strcasecmp(name, "cpos") == 0) &&
current_corpus &&
current_corpus->corpus &&
find_attribute(current_corpus->corpus, name, ATT_STRUC, NULL) == NULL) {
CD.print_cpos = status;
}
else if ((strcasecmp(name, "targets") == 0) &&
current_corpus &&
current_corpus->corpus &&
find_attribute(current_corpus->corpus, name, ATT_STRUC, NULL) == NULL) {
show_targets = status;
}
else if (CD.attributes || CD.alignedCorpora) {
if (name) {
if ((ai = FindInAL(CD.attributes, name)))
ai->status = status;
else if ((ai = FindInAL(CD.alignedCorpora, name)))
ai->status = status;
else if ((ai = FindInAL(CD.strucAttributes, name)))
ai->status = status;
else {
cqpmessage(Error, "No such attribute: %s", name);
generate_code = 0;
}
}
else {
for (ai = CD.attributes->list; ai; ai = ai->next)
ai->status = status;
if (!status)
if ((ai = FindInAL(CD.attributes, DEFAULT_ATT_NAME)) != NULL)
ai->status = 1;
}
}
}
CorpusList *
do_translate(CorpusList *source, char *target_name) {
CorpusList *res, *target;
Attribute *alignment;
int i, n, bead;
int s1, s2, t1, t2;
if (generate_code) {
assert(source != NULL);
target = findcorpus(target_name, SYSTEM, 0);
if (target == NULL) {
cqpmessage(Warning, "System corpus ``%s'' doesn't exist", target_name);
generate_code = 0;
return NULL;
}
alignment = find_attribute(source->corpus, target->corpus->registry_name,
ATT_ALIGN, NULL);
if (alignment == NULL) {
cqpmessage(Error, "Corpus ``%s'' is not aligned to corpus ``%s''",
source->mother_name, target->mother_name);
generate_code = 0;
return NULL;
}
/* allocate temporary NQR for the translated ranges */
res = make_temp_corpus(target, "RHS");
res->size = n = source->size;
cl_free(res->range); /* allocate ranges for mapped regions */
res->range = (Range *)cl_calloc(n, sizeof(Range));
cl_free(res->targets); /* make sure there are no spurious target / keywords vectors */
cl_free(res->keywords);
/* translate each matching range into target bead */
for (i = 0; i < n; i++) {
bead = cl_cpos2alg(alignment, source->range[i].start);
if (bead < 0 ||
!cl_alg2cpos(alignment, bead, &s1, &s2, &t1, &t2) ||
cderrno != CDA_OK) {
res->range[i].start = -1;
}
else {
res->range[i].start = t1;
res->range[i].end = t2;
}
}
/* remove unaligned items (but not duplicates) */
RangeSetop(res, RReduce, NULL, NULL);
/* make sure target ranges are sorted (preserving original order with sortidx) */
RangeSort(res, 1);
return res;
}
else
return NULL;
}
CorpusList *
do_setop(RangeSetOp op, CorpusList *c1, CorpusList *c2)
{
CorpusList *res;
res = NULL;
cqpmessage(Message, "Set Expr");
if (c1 && c2) {
if (c1->corpus != c2->corpus)
cqpmessage(Warning,
"Original corpora of %s (%s) and %s (%s) differ.\n",
c1->name, c1->mother_name, c2->name, c2->mother_name);
else {
res = make_temp_corpus(c1, "RHS");
RangeSetop(res, op, c2, NULL);
}
}
return res;
}
void
prepare_do_subset(CorpusList *cl, FieldType field)
{
int field_exists = 0;
if (cl == NULL || cl->type != SUB) {
cqpmessage(Error, "The subset operator can only be applied to subcorpora.");
generate_code = 0;
return;
}
else if (cl->size == 0) {
cqpmessage(Warning, "The subcorpus is empty, subset operation therefore "
"without any effect.");
return;
}
switch (field) {
case MatchField:
case MatchEndField:
field_exists = cl->size > 0;
break;
case KeywordField:
field_exists = cl->size > 0 && cl->keywords != NULL;
break;
case TargetField:
field_exists = cl->size > 0 && cl->targets != NULL;
break;
default:
field_exists = 0;
break;
}
if (!field_exists) {
cqpmessage(Error, "The <%s> anchor is not defined for this subcorpus.",
field_type_to_name(field));
generate_code = 0;
return;
}
if (progress_bar) {
progress_bar_clear_line();
progress_bar_message(1, 1, " preparing");
}
/* jetzt k�nnen wir endlich loslegen */
query_corpus = make_temp_corpus(cl, "RHS");
generate_code = 1;
}
CorpusList *
do_subset(FieldType field, Constrainttree boolt)
{
if (generate_code) {
(void) evaluate_subset(query_corpus, field, boolt);
}
if (boolt)
free_booltree(boolt);
if (progress_bar) {
progress_bar_clear_line();
}
if (generate_code)
return query_corpus;
else
return NULL;
}
void
do_set_target(CorpusList *cl, FieldType goal, FieldType source)
{
if (cl != NULL && goal != NoField)
set_target(cl, goal, source);
}
void
do_set_complex_target(CorpusList *cl,
FieldType field_to_set,
SearchStrategy strategy,
Constrainttree boolt,
enum ctxtdir direction,
int number,
char *id,
FieldType field,
int inclusive)
{
if (generate_code && cl != NULL) {
/* query_corpus has been saved in old_query_corpus and set to cl by parser */
evaluate_target(cl,
field_to_set,
field,
inclusive,
strategy,
boolt, direction, number, id);
query_corpus = old_query_corpus; /* reset query_corpus to previous value */
old_query_corpus = NULL;
}
/* aufr�umen */
if (boolt)
free_booltree(boolt);
}
/**
* Puts the program to sleep.
*
* A wrapper round the standard sleep() function (or Sleep() in Windows).
*
* @param duration How many seconds to sleep for.
*/
void
do_sleep(int duration)
{
if (duration > 0) {
#ifndef __MINGW__
sleep(duration); /* sleep in number of seconds (normal POSIX function) */
#else
Sleep(duration*1000); /* sleep in number of milliseconds (Windows "equivalent") */
#endif
}
}
/**
* Execute the commands contained within a specified text file.
*/
void
do_exec(char *fname)
{
FILE *f;
cqpmessage(Message, "exec cmd: %s\n", fname);
if (1) {
cqpmessage(Error, "The source statement is not yet supported");
generate_code = 0;
}
else {
if ((f = open_file(fname, "r")) != NULL) {
if (!cqp_parse_file(f, 1)) {
cqpmessage(Error, "Errors in exec'ed file %s\n", fname);
generate_code = 0;
}
}
else {
cqpmessage(Error, "Exec file %s not accessible\n", fname);
generate_code = 0;
}
}
}
void
do_delete_lines_num(CorpusList *cl, int start, int end)
{
if (cl == NULL || cl->type != SUB) {
cqpmessage(Error, "The delete operator can only be applied to subcorpora.");
generate_code = 0;
return;
}
else if (start <= end) {
Bitfield lines = create_bitfield(cl->size);
assert(lines);
for ( ; start <= end && start < cl->size; start++) {
(void) set_bit(lines, start);
}
if (nr_bits_set(lines) > 0) {
(void) delete_intervals(cl, lines, SELECTED_LINES);
}
(void) destroy_bitfield(&lines);
}
}
void
do_delete_lines(CorpusList *cl, FieldType f, int mode)
{
if (cl == NULL || cl->type != SUB) {
cqpmessage(Error, "The delete operator can only be applied to subcorpora.");
generate_code = 0;
return;
}
else if (f != NoField) {
int *positions = NULL;
switch (f) {
case MatchField:
case MatchEndField:
cqpmessage(Warning, "\"delete ... with[out] match/matchend\" does not make sense.");
break;
case KeywordField:
if ((positions = cl->keywords) == NULL) {
cqpmessage(Warning, "No keywords set for this subcorpus");
}
break;
case TargetField:
if ((positions = cl->targets) == NULL) {
cqpmessage(Warning, "No collocates set for this subcorpus");
}
break;
default:
assert(0 && "Can't (well, shouldn't) be..");
break;
}
if (positions) {
int i;
Bitfield lines = create_bitfield(cl->size);
assert(lines);
for (i = 0; i < cl->size; i++) {
if (positions[i] >= 0) {
(void) set_bit(lines, i);
}
}
(void) delete_intervals(cl, lines, mode);
(void) destroy_bitfield(&lines);
}
}
}
void
do_reduce(CorpusList *cl, int number, int percent) {
if (cl == NULL || cl->type != SUB) {
cqpmessage(Error, "The reduce operator can only be applied to named query results.");
generate_code = 0;
return;
}
else if (cl->size == 0) {
cqpmessage(Warning, "Zero matches - no reduction applicable\n");
return;
}
if (percent) {
if (number <= 0 || number >= 100) {
cqpmessage(Error, "The \"reduce to n percent\" operation\n"
"requires a number between 0 and 100 (exclusive)");
generate_code = 0;
return;
}
number = (cl->size * number) / 100;
}
else {
if (number <= 0 || number >= cl->size) {
/* nothing to be done -- don't squeal (a general "reduce Last to 50" without checking size is quite useful) */
/* cqpmessage(Warning, "The \"reduce to n lines\" operation\n" */
/* "requires a number between 0 and the subcorpus' size (exclusive)"); */
return;
}
}
{
unsigned int to_select, size;
Bitfield lines = create_bitfield(cl->size);
assert(lines);
/* the algorithm below uses a continuously updated selection probability
in order to select a random sample of size <number> without replacement */
size = cl->size; /* how many matches remain to be processed */
to_select = number; /* how many of these should be selected */
while (size > 0) {
double prob = ((double) to_select) / ((double) size); /* select current line with this probability */
if (cl_runif() <= prob) {
set_bit(lines, size-1); /* current line number is size-1 */
to_select--;
}
size--;
}
(void) delete_intervals(cl, lines, UNSELECTED_LINES);
(void) destroy_bitfield(&lines);
}
}
void
do_cut(CorpusList *cl, int first, int last) {
int n_matches, i;
if (cl == NULL || cl->type != SUB) {
cqpmessage(Error, "The cut operator can only be applied to named query results.");
generate_code = 0;
return;
}
n_matches = cl->size;
if (n_matches == 0) {
cqpmessage(Warning, "Named query result is empty - can't cut\n");
return;
}
assert(first >= 0); /* first < 0 is now disallowed by the parser */
if (last >= n_matches)
last = n_matches - 1; /* must be >= 0 because n_matches > 1 has been checked */
if (first >= n_matches)
first = n_matches; /* so the loop below cannot overflow */
if (last < first) {
cqpmessage(Warning, "Cut operator applied with empty range %d .. %d, so result is empty.", first, last);
first = last = n_matches; /* delete all matches, ensuring that index does not run out of bounds */
}
for (i = 0; i < first; i++) {
cl->range[i].start = -1; /* delete all matches before <first> */
cl->range[i].end = -1;
}
for (i = last + 1; i < n_matches; i++) {
cl->range[i].start = -1; /* delete all matches after <last> */
cl->range[i].end = -1;
}
RangeSetop(cl, RReduce, NULL, NULL); /* remove matches marked for deletion */
touch_corpus(cl);
}
void
do_info(CorpusList *cl)
{
if (cl)
corpus_info(cl);
}
void
do_group(CorpusList *cl,
FieldType target, int target_offset, char *t_att,
FieldType source, int source_offset, char *s_att,
int cut, int expand, int is_grouped, struct Redir *redir)
{
Group *group;
do_start_timer();
group = compute_grouping(cl, source, source_offset, s_att, target, target_offset, t_att, cut, is_grouped);
do_timing("Grouping computed");
if (group) {
print_group(group, expand, redir);
free_group(&group);
}
}
/** Like do_group, but with no source */
void
do_group2(CorpusList *cl,
FieldType target, int target_offset, char *t_att,
int cut, int expand, struct Redir *r)
{
Group *group;
do_start_timer();
group = compute_grouping(cl, NoField, 0, NULL, target, target_offset, t_att, cut, 0);
do_timing("Grouping computed");
if (group) {
print_group(group, expand, r);
free_group(&group);
}
}
CorpusList *
do_StandardQuery(int cut_value, int keep_flag, char *modifier)
{
CorpusList *res;
res = NULL;
cqpmessage(Message, "Query");
/* embedded modifier (?<modifier>) at start of query */
if (modifier != NULL) {
/* currently, modifiers can only be used to set the matching strategy */
int code = find_matching_strategy(modifier);
if (code < 0) {
cqpmessage(Error, "embedded modifier (?%s) not recognized;\n"
"\tuse (?longest), (?shortest), (?standard) or (?traditional) to set matching strategy temporarily",
modifier);
generate_code = 0;
}
else
Environment[0].matching_strategy = code;
cl_free(modifier); /* allocated by lexer */
}
if (parseonly || (generate_code == 0))
res = NULL;
else if (Environment[0].evaltree != NULL) {
debug_output();
do_start_timer();
if (keep_flag == 1 && current_corpus->type != SUB) {
cqpmessage(Warning, "``Keep Ranges'' only allowed when \n"
"querying subcorpora (ignored)");
keep_flag = 0;
}
cqp_run_query(cut_value, keep_flag);
res = Environment[0].query_corpus;
/* the new matching strategies require post-processing of the query result */
switch (Environment[0].matching_strategy) {
case shortest_match:
RangeSetop(res, RMinimalMatches, NULL, NULL); /* select shortest from several nested matches */
break;
case standard_match:
RangeSetop(res, RLeftMaximalMatches, NULL, NULL); /* reduce multiple matches created by optional query prefix */
break;
case longest_match:
RangeSetop(res, RMaximalMatches, NULL, NULL); /* select longest from several nested matches */
break;
case traditional:
default:
break; /* nothing to do here */
}
/* if there's a cut_value, we may need to reduce the result to <cut_value> matches */
if (cut_value > 0) {
/* if there is more than 1 initial pattern in the query, it may have returned more than <cut_value> matches */
if (res->size > cut_value) {
Bitfield lines = create_bitfield(res->size);
int i;
for (i = 0; i < cut_value; i++)
set_bit(lines, i);
if (!delete_intervals(res, lines, UNSELECTED_LINES)) {
cqpmessage(Error, "Couldn't reduce query result to first %d matches.\n", cut_value);
}
destroy_bitfield(&lines);
}
}
}
cl_free(searchstr);
return res;
}
CorpusList *
do_MUQuery(Evaltree evalt, int keep_flag, int cut_value)
{
CorpusList *res;
cqpmessage(Message, "Meet/Union Query");
if (parseonly || (generate_code == 0))
res = NULL;
else if (evalt != NULL) {
assert(CurEnv == &Environment[0]);
CurEnv->evaltree = evalt;
assert((evalt->type == meet_union) ||
(evalt->type == leaf));
debug_output();
do_start_timer();
if (keep_flag == 1 && current_corpus->type != SUB) {
cqpmessage(Warning, "``Keep Ranges'' only allowed when \n"
"querying subcorpora");
keep_flag = 0;
}
cqp_run_mu_query(keep_flag, cut_value);
res = Environment[0].query_corpus;
}
else
res = NULL;
return res;
}
void
do_SearchPattern(Evaltree expr, /* $1 */
Constrainttree constraint) /* $3 */
{
cqpmessage(Message, "SearchPattern");
if (generate_code) {
CurEnv->evaltree = expr;
CurEnv->gconstraint = constraint;
if (!check_labels(CurEnv->labels)) {
cqpmessage(Error, "Illegal use of labels, not evaluated.");
generate_code = 0;
}
else {
searchstr = (char *)evaltree2searchstr(CurEnv->evaltree,
&sslen);
if (search_debug) {
Rprintf("Evaltree: \n");
print_evaltree(eep, CurEnv->evaltree, 0);
Rprintf("Search String: ``%s''\n", searchstr);
}
if (searchstr && (strspn(searchstr, " ") < strlen(searchstr))) { /* i.e. searchstr does not match /^\s*$/ */
regex2dfa(searchstr, &(CurEnv->dfa));
}
else {
cqpmessage(Error, "Query is vacuous, not evaluated.");
generate_code = 0;
}
cl_free(searchstr);
}
} /* endif generate_code */
}
/* ======================================== Regular Expressions */
Evaltree
reg_disj(Evaltree left, Evaltree right)
{
Evaltree ev;
if (generate_code) {
NEW_EVALNODE(ev, re_disj, left, right, repeat_none, repeat_none);
return ev;
}
else
return NULL;
}
Evaltree
reg_seq(Evaltree left, Evaltree right)
{
Evaltree ev;
if (generate_code) {
NEW_EVALNODE(ev, re_od_concat,
left, right,
repeat_none, repeat_none);
return ev;
}
else
return NULL;
}
int
do_AnchorPoint(FieldType field, int is_closing)
{
int res = -1;
cqpmessage(Message, "Anchor: <%s%s>", ((is_closing) ? "/" : ""), field_type_to_name(field));
if (generate_code) {
if (CurEnv->MaxPatIndex == MAXPATTERNS) {
cqpmessage(Error,
"Too many patterns (max is %d)", MAXPATTERNS);
generate_code = 0; /* YYABORT; */
}
}
if (generate_code) {
/* check that <target> or <keyword> anchor is defined in query_corpus */
switch (field) {
case MatchField:
case MatchEndField:
break; /* ok (if query_corpus->size == 0, subquery will simply return no matches) */
case TargetField:
if (query_corpus->targets == NULL) {
cqpmessage(Error, "<target> anchor not defined in %s", query_corpus->name);
generate_code = 0;
}
break;
case KeywordField:
if (query_corpus->keywords == NULL) {
cqpmessage(Error, "<keyword> anchor not defined in %s", query_corpus->name);
generate_code = 0;
}
break;
default:
/* should not be reachable */
assert("Internal error in do_AnchorPoint()" && 0);
}
}
if (generate_code) {
CurEnv->MaxPatIndex++;
CurEnv->patternlist[CurEnv->MaxPatIndex].type = Anchor;
CurEnv->patternlist[CurEnv->MaxPatIndex].anchor.is_closing = is_closing;
CurEnv->patternlist[CurEnv->MaxPatIndex].anchor.field = field;
res = CurEnv->MaxPatIndex;
}
if (!generate_code)
res = -1;
return res;
}
int
do_XMLTag(char *s_name, int is_closing, int op, char *regex, int flags)
{
Attribute *attr = NULL;
int op_type = op & OP_NOT_MASK;
int negated = op & OP_NOT;
int res = -1;
cqpmessage(Message, "StructureDescr: <%s%s>", (is_closing ? "/" : ""), s_name);
if (generate_code) {
if (CurEnv->MaxPatIndex == MAXPATTERNS) {
cqpmessage(Error,
"Too many patterns (max is %d)", MAXPATTERNS);
generate_code = 0; /* YYABORT; */
}
}
if (generate_code) {
attr = cl_new_attribute(query_corpus->corpus, s_name, ATT_STRUC);
if (attr == NULL) {
cqpmessage(Error, "Structural attribute %s.%s does not exist.",
query_corpus->name, s_name);
generate_code = 0; /* YYABORT; */
}
else {
if (regex && !cl_struc_values(attr)) {
cqpmessage(Error, "Structural attribute %s.%s does not have annotated values.",
query_corpus->name, s_name);
generate_code = 0;
}
}
}
if (generate_code && ((op_type == OP_MATCHES) || (op_type == OP_CONTAINS)) && (flags == IGNORE_REGEX)) {
cqpmessage(Error, "Can't use literal strings with 'contains' and 'matches' operators.");
generate_code = 0;
}
if (generate_code) {
CurEnv->MaxPatIndex++;
CurEnv->patternlist[CurEnv->MaxPatIndex].type = Tag;
CurEnv->patternlist[CurEnv->MaxPatIndex].tag.attr = attr;
CurEnv->patternlist[CurEnv->MaxPatIndex].tag.is_closing = is_closing;
CurEnv->patternlist[CurEnv->MaxPatIndex].tag.constraint = NULL;
CurEnv->patternlist[CurEnv->MaxPatIndex].tag.flags = 0;
CurEnv->patternlist[CurEnv->MaxPatIndex].tag.rx = NULL;
CurEnv->patternlist[CurEnv->MaxPatIndex].tag.negated = 0;
CurEnv->patternlist[CurEnv->MaxPatIndex].tag.right_boundary = (LabelEntry) NULL;
/* start tag may have regex constraint on annotated values */
if ((!is_closing) && regex) {
cl_string_latex2iso(regex, regex, strlen(regex)); /* interpret latex escapes */
if (flags == IGNORE_REGEX ||
((strcspn(regex, "[](){}.*+|?\\") == strlen(regex)) && (flags == 0) && (op_type == OP_EQUAL))) {
/* match as literal string -> don't compile regex */
}
else {
int safe_regex = !(strchr(regex, '|') || strchr(regex, '\\')); /* see below */
char *conv_regex; /* OP_CONTAINS and OP_MATCHES */
char *pattern;
CL_Regex rx;
if ((op_type == OP_CONTAINS) || (op_type == OP_MATCHES)) {
conv_regex = mval_string_conversion(regex);
pattern = cl_malloc(strlen(conv_regex) + 42); /* leave some room for the regexp wrapper */
if (op_type == OP_CONTAINS)
sprintf(pattern, ".*\\|(%s)\\|.*", conv_regex);
else { /* op_type == OP_MATCHES */
if (safe_regex) /* inner regexp is 'safe' so we can omit the parentheses and thus enable optimisation */
sprintf(pattern, "\\|(%s\\|)+", conv_regex);
else
sprintf(pattern, "\\|((%s)\\|)+", conv_regex);
}
cl_free(conv_regex);
}
else if (op_type == OP_EQUAL) {
pattern = cl_strdup(regex);
}
else { /* undefined operator */
assert(0 && "do_mval_string(): illegal opcode (internal error)");
}
rx = cl_new_regex(pattern, flags, query_corpus->corpus->charset);
if (rx == NULL) {
cqpmessage(Error, "Illegal regular expression: %s", regex);
generate_code = 0;
}
else
CurEnv->patternlist[CurEnv->MaxPatIndex].tag.rx = rx;
cl_free(pattern);
}
CurEnv->patternlist[CurEnv->MaxPatIndex].tag.constraint = regex;
CurEnv->patternlist[CurEnv->MaxPatIndex].tag.flags = flags;
CurEnv->patternlist[CurEnv->MaxPatIndex].tag.negated = negated;
}
}
if (generate_code && strict_regions) {
/* label is 'defined' by first open tag and 'used' by following close tag -> in this case, it is activated */
LabelEntry label;
if (!is_closing) { /* open tag -> 'define' label */
label = labellookup(CurEnv->labels, s_name, LAB_DEFINED|LAB_RDAT, 1);
CurEnv->patternlist[CurEnv->MaxPatIndex].tag.right_boundary = label;
}
else { /* close tag -> if label is already defined, it is 'used', i.e. activated */
label = findlabel(CurEnv->labels, s_name, LAB_RDAT);
if ((label != NULL) && (label->flags & LAB_DEFINED)) {
label->flags |= LAB_USED; /* activate this label for strict regions */
CurEnv->patternlist[CurEnv->MaxPatIndex].tag.right_boundary = label;
}
else {
/* end tag doesn't check or reset the label if it isn't preceded by a corresponding open tag */
/* label = labellookup(CurEnv->labels, s_name+offset, LAB_RDAT, 1); */
}
}
}
if (generate_code)
res = CurEnv->MaxPatIndex;
else {
res = -1;
if (regex)
free(regex);
}
return res;
}
int
do_NamedWfPattern(int is_target, char *label, int pat_idx) {
int res;
LabelEntry lab;
res = -1;
cqpmessage(Message, "NamedWfPattern");
if (generate_code) {
if (label != NULL) {
/* lookup or create label */
lab = labellookup(CurEnv->labels, label, LAB_DEFINED, 1);
/* user isn't allowed to set special label */
if (lab->flags & LAB_SPECIAL) {
cqpmessage(Error, "Can't set special label %s", label);
generate_code = 0;
return 0;
}
}
else
lab = NULL;
switch (CurEnv->patternlist[pat_idx].type) {
case Pattern:
CurEnv->patternlist[pat_idx].con.label = lab;
CurEnv->patternlist[pat_idx].con.is_target =
(is_target == 1 ? True : False);
break;
case MatchAll:
CurEnv->patternlist[pat_idx].matchall.label = lab;
CurEnv->patternlist[pat_idx].matchall.is_target =
(is_target == 1 ? True : False);
break;
default:
assert("Can't be" && 0);
break;
}
if (is_target == 1) {
CurEnv->has_target_indicator = 1;
CurEnv->target_label = labellookup(CurEnv->labels, "target", LAB_DEFINED|LAB_USED, 1);
/* the special "target" label is never formally ``used'' in the construction of the
NFA, so we declared it as both DEFINED and USED (which it will be in <eval.h>) */
}
res = pat_idx;
}
else
res = 0;
return res;
}
int
do_WordformPattern(Constrainttree boolt, int lookahead) {
int res;
if (generate_code) {
if (CurEnv->MaxPatIndex == MAXPATTERNS) {
cqpmessage(Error,
"Too many patterns (max is %d)", MAXPATTERNS);
generate_code = 0;
}
}
if (generate_code) {
CurEnv->MaxPatIndex++;
if ((boolt->type == cnode) && (boolt->constnode.val == 1)) {
/* matchall */
free(boolt);
CurEnv->patternlist[CurEnv->MaxPatIndex].type = MatchAll;
CurEnv->patternlist[CurEnv->MaxPatIndex].matchall.label = NULL;
CurEnv->patternlist[CurEnv->MaxPatIndex].matchall.is_target = False;
CurEnv->patternlist[CurEnv->MaxPatIndex].matchall.lookahead = lookahead;
}
else {
CurEnv->patternlist[CurEnv->MaxPatIndex].type = Pattern;
/* the assertion below is utter bollocks; that pattern may have had a different type
in the previous query, so the assertion will only be true if the particular bit of memory
storing the pointer has been initialised to zeroes */
/* assert(CurEnv->patternlist[CurEnv->MaxPatIndex].con.constraint == NULL); */
CurEnv->patternlist[CurEnv->MaxPatIndex].con.constraint = boolt;
CurEnv->patternlist[CurEnv->MaxPatIndex].con.label = NULL;
CurEnv->patternlist[CurEnv->MaxPatIndex].con.lookahead = lookahead;
}
res = CurEnv->MaxPatIndex;
}
else
res = -1;
return res;
}
Constrainttree
OptimizeStringConstraint(Constrainttree left,
enum b_ops op,
Constrainttree right)
{
Constrainttree c = NULL;
if (right->type == cnode) {
cl_free(left);
c = right;
right = NULL;
if (op == cmp_neq)
c->constnode.val = !c->constnode.val;
}
else {
NEW_BNODE(c);
if (right->leaf.pat_type == REGEXP) {
int range;
range = get_id_range(left->pa_ref.attr);
/* optimise regular expressions to idlists for categorical attributes (at most MAKE_IDLIST_BOUND lexicon entries) */
if ((range > 0) && (range < MAKE_IDLIST_BOUND)) {
int *items;
int nr_items;
items = collect_matching_ids(left->pa_ref.attr,
right->leaf.ctype.sconst,
right->leaf.canon,
&nr_items);
if (cderrno != CDA_OK) {
cqpmessage(Error, "Error while collecting matching IDs of %s\n(%s)\n",
right->leaf.ctype.sconst,
cdperror_string(cderrno));
generate_code = 0;
c->type = cnode;
c->constnode.val = 0;
}
else if (nr_items == 0) {
cl_free(items);
c->type = cnode;
c->constnode.val = (op == cmp_eq ? 0 : 1);
}
else if (nr_items == range) {
cl_free(items);
c->type = cnode;
c->constnode.val = (op == cmp_eq ? 1 : 0);
}
else {
c->type = id_list;
c->idlist.attr = left->pa_ref.attr;
c->idlist.label = left->pa_ref.label;
c->idlist.delete = left->pa_ref.delete;
c->idlist.nr_items = nr_items;
c->idlist.items = items;
c->idlist.negated = (op == cmp_eq ? 0 : 1);
/* if more than half of all IDs match, the ID list can be processed more
efficiently when it is inverted (exchanging == for != in the comparison
where it is used, and vice versa); however, for sparse attributes (where
the most frequent type is "no value") the inverted list might match almost
all tokens in the corpus, which can be catastrophic when the ID list is
used for index lookup (in query-initial position); therefore, the decision
for or against negation should be based on whether the ID list matches
more than half of all tokens; for "normal" attributes, the two criteria
will lead to very similar decisions anyway */
/* previous condition removed: */
/* if (nr_items > range/2) { */
if (cl_idlist2freq(left->pa_ref.attr, items, nr_items) > cl_max_cpos(left->pa_ref.attr) / 2) {
int i, k, pos, last_id;
int *ids;
ids = (int *)cl_malloc((range - nr_items) * sizeof(int));
pos = 0;
last_id = -1;
for (i = 0; i < nr_items; i++) {
if (last_id < 0) {
for (k = 0; k < items[i]; k++)
ids[pos++] = k;
}
else {
for (k = last_id + 1; k < items[i]; k++)
ids[pos++] = k;
}
last_id = items[i];
}
for (k = last_id + 1; k < range; k++)
ids[pos++] = k;
assert(pos == range - nr_items);
c->idlist.nr_items = range - nr_items;
c->idlist.items = ids;
c->idlist.negated = !c->idlist.negated;
free(items);
}
}
cl_free(left);
cl_free(right);
}
else {
c->type = bnode;
c->node.op_id = op;
c->node.left = left;
c->node.right = right;
}
}
else {
int id;
assert(right->leaf.pat_type == NORMAL);
id = cl_str2id(left->pa_ref.attr, right->leaf.ctype.sconst);
if (id < 0) {
if (catch_unknown_ids) {
/* nb effectively if (0) since catch_unknown_ids is initialised to 0 and no code changes it -- AH*/
cqpmessage(Error, "The string ``%s'' is not in the value space of ``%s''\n",
right->leaf.ctype.sconst, left->pa_ref.attr->any.name);
generate_code = 0;
}
cl_free(right);
cl_free(left);
c->type = cnode;
c->constnode.val = (op == cmp_eq ? 0 : 1);
}
else {
c->type = bnode;
c->node.op_id = op;
c->node.left = left;
c->node.right = right;
cl_free(right->leaf.ctype.sconst);
right->leaf.pat_type = CID;
right->leaf.ctype.cidconst = id;
}
}
}
return c;
}
Constrainttree
do_StringConstraint(char *s, int flags)
{
Constrainttree c, left, right;
Attribute *attr = NULL;
c = NULL; left = NULL; right = NULL;
if (generate_code) {
if ((attr = find_attribute(query_corpus->corpus,
def_unbr_attr,
ATT_POS,
NULL)) == NULL) {
cqpmessage(Error,
"``%s'' attribute not defined for corpus ``%s'',"
"\nusing ``%s''",
def_unbr_attr, query_corpus->name,
DEFAULT_ATT_NAME);
set_string_option_value("DefaultNonbrackAttr", DEFAULT_ATT_NAME);
if ((attr = find_attribute(query_corpus->corpus,
DEFAULT_ATT_NAME,
ATT_POS,
NULL)) == NULL) {
cqpmessage(Error,
"``%s'' attribute not defined for corpus ``%s''",
DEFAULT_ATT_NAME, query_corpus->name);
generate_code = 0;
}
}
}
if (generate_code) {
if (!(right = do_flagged_string(s, flags)))
generate_code = 0;
else if (right->type == cnode) {
c = right;
right = NULL;
}
else {
/* make a new leaf node which holds the attribute */
NEW_BNODE(left);
left->type = pa_ref;
left->pa_ref.attr = attr;
left->pa_ref.label = NULL;
left->pa_ref.delete = 0;
c = OptimizeStringConstraint(left, cmp_eq, right);
}
}
if (generate_code)
return c;
else
return NULL;
}
Constrainttree
Varref2IDList(Attribute *attr, enum b_ops op, char *varName)
{
Constrainttree node;
node = NULL;
if (generate_code) {
Variable v;
if ((v = FindVariable(varName)) != NULL) {
NEW_BNODE(node);
node->type = id_list;
node->idlist.attr = attr;
node->idlist.label = NULL;
node->idlist.delete = 0;
node->idlist.negated = (op == cmp_eq ? 0 : 1);
node->idlist.items = GetVariableItems(v,
query_corpus->corpus,
attr,
&(node->idlist.nr_items));
if (node->idlist.nr_items == 0) { /* optimise: empty ID list -> constant */
node->type = cnode;
node->constnode.val = (op == cmp_eq ? 0 : 1); /* always FALSE for '=', always TRUE for '!=' */
/* NB: no need to free idlist.items, because the list is empty (NULL pointer) */
}
}
else {
cqpmessage(Error, "%s: no such variable.");
generate_code = 0;
}
}
return node;
}
Constrainttree
do_SimpleVariableReference(char *varName)
{
Attribute *attr = NULL;
if (generate_code) {
if ((attr = find_attribute(query_corpus->corpus,
def_unbr_attr,
ATT_POS,
NULL)) == NULL) {
cqpmessage(Error,
"``%s'' attribute not defined for corpus ``%s'',"
"\nusing ``%s''",
def_unbr_attr, query_corpus->name,
DEFAULT_ATT_NAME);
set_string_option_value("DefaultNonbrackAttr", DEFAULT_ATT_NAME);
if ((attr = find_attribute(query_corpus->corpus,
DEFAULT_ATT_NAME,
ATT_POS,
NULL)) == NULL) {
cqpmessage(Error,
"``%s'' attribute not defined for corpus ``%s''",
DEFAULT_ATT_NAME, query_corpus->name);
generate_code = 0;
}
}
}
if (generate_code)
return Varref2IDList(attr, cmp_eq, varName);
else
return NULL;
}
void
prepare_AlignmentConstraints(char *id)
{
Attribute *algattr;
CorpusList *cl;
if ((cl = findcorpus(id, SYSTEM, 0)) == NULL) {
cqpmessage(Warning, "System corpus ``%s'' is undefined", id);
generate_code = 0;
}
else if (!access_corpus(cl)) {
cqpmessage(Warning, "Corpus ``%s'' can't be accessed", id);
generate_code = 0;
}
else if ((algattr = find_attribute(Environment[0].query_corpus->corpus,
cl->corpus->registry_name,
ATT_ALIGN, NULL)) == NULL) {
cqpmessage(Error,
"Corpus ``%s'' is not aligned to corpus ``%s''",
Environment[0].query_corpus->mother_name, id);
generate_code = 0;
}
else if (!next_environment()) {
cqpmessage(Error, "Can't allocate another evaluation environment (too many alignments)");
generate_code = 0;
query_corpus = NULL;
}
else {
CurEnv->aligned = algattr;
CurEnv->query_corpus = cl;
query_corpus = cl;
}
}
/* ======================================== BOOLEAN OPS */
Constrainttree
bool_or(Constrainttree left, Constrainttree right)
{
Constrainttree res;
res = NULL;
if (generate_code) {
if (left->node.type == cnode) {
if (left->constnode.val == 0) {
res = right;
free_booltree(left);
}
else {
res = left;
free_booltree(right);
}
}
else if (right->node.type == cnode) {
if (right->constnode.val == 0) {
res = left;
free_booltree(right);
}
else {
res = right;
free_booltree(left);
}
}
else {
NEW_BNODE(res);
res->node.type = bnode;
res->node.op_id = b_or;
res->node.left = left;
res->node.right = right;
res = try_optimization(res);
}
}
else
res = NULL;
return res;
}
Constrainttree
bool_implies(Constrainttree left, Constrainttree right)
{
Constrainttree res = NULL;
if (generate_code) {
if (left->node.type == cnode) {
if (left->constnode.val == 0) { /* LHS is FALSE -> implication always TRUE */
res = left;
res->constnode.val = 1;
free_booltree(right);
}
else { /* LHS is TRUE -> implication == RHS */
res = right;
free_booltree(left);
}
}
else if (right->node.type == cnode) {
if (right->constnode.val == 0) { /* RHS is FALSE -> implication == !(LHS) */
res = bool_not(left);
free_booltree(right);
}
else { /* RHS is TRUE -> implication always TRUE */
res = right;
free_booltree(left);
}
}
else {
NEW_BNODE(res);
res->node.type = bnode;
res->node.op_id = b_implies;
res->node.left = left;
res->node.right = right;
res = try_optimization(res);
}
}
else
res = NULL;
return res;
}
Constrainttree
bool_and(Constrainttree left, Constrainttree right)
{
Constrainttree res;
res = NULL;
if (generate_code) {
if (left->node.type == cnode) {
if (left->constnode.val == 0) {
res = left;
free_booltree(right);
}
else {
res = right;
free_booltree(left);
}
}
else if (right->node.type == cnode) {
if (right->constnode.val == 0) {
res = right;
free_booltree(left);
}
else {
res = left;
free_booltree(right);
}
}
else {
NEW_BNODE(res);
res->node.type = bnode;
res->node.op_id = b_and;
res->node.left = left;
res->node.right = right;
}
}
else
res = NULL;
return res;
}
Constrainttree
bool_not(Constrainttree left)
{
Constrainttree res;
res = NULL;
if (generate_code) {
if (left->node.type == cnode) {
left->constnode.val = !(left->constnode.val);
res = left;
}
else if (left->type == id_list) {
left->idlist.negated = !left->idlist.negated;
res = left;
}
else if (left->type == bnode &&
left->node.op_id == b_not &&
left->node.right == NULL) {
res = left->node.left;
left->node.left = NULL;
free_booltree(left);
}
else {
NEW_BNODE(res);
res->node.type = bnode;
res->node.op_id = b_not;
res->node.left = left;
res->node.right = NULL;
}
}
else
res = NULL;
return res;
}
Constrainttree
do_RelExpr(Constrainttree left,
enum b_ops op,
Constrainttree right)
{
Constrainttree res;
res = NULL;
if (generate_code) {
if (right->type == var_ref) {
if (left->type == pa_ref) {
res = Varref2IDList(left->pa_ref.attr, op, right->varref.varName);
/* be careful: res might be of type cnode, when an empty id_list has been optimised away */
if (res && res->type == id_list && generate_code) {
res->idlist.label = left->pa_ref.label;
res->idlist.delete = left->pa_ref.delete;
}
}
else {
cqpmessage(Error,
"LHS of variable reference must be the name of "
"a positional attribute");
generate_code = 0;
}
free_booltree(left);
free_booltree(right);
}
else if ((left->type == pa_ref) && (right->type == string_leaf))
res = OptimizeStringConstraint(left, op, right);
else {
NEW_BNODE(res);
res->type = bnode;
res->node.op_id = op;
res->node.left = left;
res->node.right = right;
res = try_optimization(res);
}
}
else
res = NULL;
return res;
}
Constrainttree
do_RelExExpr(Constrainttree left)
{
Constrainttree res;
res = NULL;
if (generate_code) {
NEW_BNODE(res);
res->type = bnode;
res->node.op_id = cmp_ex;
res->node.left = left;
res->node.right = NULL;
res = try_optimization(res);
}
else
res = NULL;
return res;
}
Constrainttree
do_LabelReference(char *label_name, int auto_delete)
{
Constrainttree res;
Attribute *attr;
LabelEntry lab;
char *hack;
res = NULL; hack = NULL; lab = NULL; attr = NULL;
if (CurEnv == NULL) {
cqpmessage(Error, "No label references allowed");
generate_code = 0;
}
else {
/* find the dot in the qualified name */
hack = strchr(label_name, '.');
if (hack == NULL) {
cqpmessage(Error, "``%s'' is not a valid label reference.", label_name);
generate_code = 0;
}
}
if (generate_code) {
*hack = '\0';
hack++;
/* now, label_name keeps the label, hack points to the attribute */
lab = labellookup(CurEnv->labels, label_name, LAB_USED, 0);
/* if (!(lab->flags & LAB_SPECIAL) && !(lab->flags & LAB_DEFINED)) { */
if (lab == NULL) { /* this is more like what we want: label hasn't been defined yet ('this' label is implicitly defined) */
cqpmessage(Error, "Label ``%s'' used before it was defined", label_name);
generate_code = 0;
}
else if (lab->flags & LAB_SPECIAL) {
if (auto_delete) {
cqpmessage(Warning, "Cannot auto-delete special label '%s' [ignored].", label_name);
auto_delete = 0;
}
}
}
if (generate_code) {
if ((attr = find_attribute(query_corpus->corpus,
hack,
ATT_POS,
NULL)) != NULL) {
/* reference to positional attribute at label */
NEW_BNODE(res);
res->type = pa_ref;
res->pa_ref.attr = attr;
res->pa_ref.label = lab;
res->pa_ref.delete = auto_delete;
}
else if ((attr = find_attribute(query_corpus->corpus,
hack,
ATT_STRUC,
NULL)) == NULL) {
cqpmessage(Error,
"Attribute ``%s'' is not defined for corpus",
hack);
generate_code = 0;
}
else {
/* reference to (value of) structural attribute at label */
if (!cl_struc_values(attr)) {
cqpmessage(Error,
"Need attribute with values (``%s'' has no values)",
hack);
generate_code = 0;
}
else {
NEW_BNODE(res);
res->type = sa_ref;
res->sa_ref.attr = attr;
res->sa_ref.label = lab;
res->sa_ref.delete = auto_delete;
}
}
}
cl_free(label_name);
if (!generate_code)
res = NULL;
return res;
}
Constrainttree
do_IDReference(char *id_name, int auto_delete) /* auto_delete may only be set if this ID is a bare label */
{
Constrainttree res;
Attribute *attr;
LabelEntry lab;
res = NULL; lab = NULL; attr = NULL;
if (generate_code) {
if (!within_gc &&
((attr = find_attribute(query_corpus->corpus,
id_name,
ATT_POS,
NULL)) != NULL)) {
NEW_BNODE(res);
res->type = pa_ref;
res->pa_ref.attr = attr;
res->pa_ref.label = NULL;
res->pa_ref.delete = 0;
}
else if ((lab = labellookup(CurEnv->labels, id_name, LAB_USED, 0)) != NULL) {
NEW_BNODE(res);
res->type = pa_ref;
res->pa_ref.attr = NULL;
res->pa_ref.label = lab;
if ((lab->flags & LAB_SPECIAL) && auto_delete) {
cqpmessage(Warning, "Cannot auto-delete special label '%s' [ignored].", id_name);
auto_delete = 0;
}
res->pa_ref.delete = auto_delete;
auto_delete = 0; /* we'll check that below */
}
else if ((attr = find_attribute(query_corpus->corpus,
id_name,
ATT_STRUC,
NULL)) != NULL) {
/* Well I was wondering myself ... this is needed for references
to structural attributes in function calls. The semantics of say
's' is to return an INT value of
1 ... if current position is the start of a region
2 ... if it's the end of a region
0 ... otherwise
If the current position is not within an 's' region, the whole
boolean expression where the reference occurred evals to False */
NEW_BNODE(res);
res->type = sa_ref;
res->sa_ref.attr = attr;
/* Need to set label to NULL now that we put sa_ref's to better use.
A label's sa_ref now returns the value of the enclosing region */
res->sa_ref.label = NULL;
res->sa_ref.delete = 0;
}
else {
if (within_gc) {
cqpmessage(Error,
"``%s'' is not a (qualified) label reference",
id_name);
}
else {
cqpmessage(Error,
"``%s'' is neither a positional/structural attribute"
" nor a label reference",
id_name);
}
generate_code = 0;
auto_delete = 0; /* so we won't raise another error */
res = NULL;
}
}
/* if auto_delete is still set, it was set on an attribute -> error */
if (auto_delete) {
cqpmessage(Error, "Auto-delete expression '~%s' not allowed ('%s' is not a label)", id_name, id_name);
generate_code = 0;
res = NULL;
}
cl_free(id_name);
return res;
}
/**
* Implements expansion of a variable within the RE() operator.
*/
Constrainttree
do_flagged_re_variable(char *varname, int flags)
{
Constrainttree tree;
Variable var;
char *s, *mark, **items;
int length, i, l, N_strings;
tree = NULL;
if (flags == IGNORE_REGEX) {
cqpmessage(Warning, "%c%c flag doesn't make sense with RE($%s) (ignored)", '%', 'l', varname);
flags = 0;
}
var = FindVariable(varname);
if (var != NULL) {
items = GetVariableStrings(var, &N_strings);
if (items == NULL || N_strings == 0) {
cqpmessage(Error, "Variable $%s is empty.", varname);
generate_code = 0;
}
else {
/* compute length of interpolated regular expression */
length = 1;
for (i = 0; i < N_strings; i++)
length += strlen(items[i]) + 1;
s = cl_malloc(length);
l = sprintf(s, "%s", items[0]);
mark = s + l; /* <mark> points to the trailing null byte */
for (i = 1; i < N_strings; i++) {
l = sprintf(mark, "|%s", items[i]);
mark += l;
}
cl_free(items);
/* now <s> contains the disjunction over all REs stored in <var> */
/* since the var strings were loaded without charset checking,
* we need to now check the regex for the present corpus's encoding. */
if (! cl_string_validate_encoding(s, query_corpus->corpus->charset, 0)){
cqpmessage(Error, "Variable $%s used with RE() includes one or more strings with characters that are invalid\n"
"in the encoding specified for corpus [%s]", varname, query_corpus->corpus->name);
generate_code = 0;
cl_free(s);
}
else
tree = do_flagged_string(s, flags);
/* note that <s> is inserted into the constraint tree and mustn't be freed here */
}
}
else {
cqpmessage(Error, "Variable $%s is not defined.", varname);
generate_code = 0;
}
cl_free(varname);
return tree;
}
Constrainttree
do_flagged_string(char *s, int flags)
{
Constrainttree res = NULL;
if (generate_code) {
NEW_BNODE(res);
/* This gets in the way with some other functions were we'd like to
keep it as a regexp ... it isn't very useful anyway, so ... */
/* if ((strcmp(s, ".*") == 0 ||
strcmp(s, ".+") == 0) &&
flags != IGNORE_REGEX) {
res->type = cnode;
res->constnode.val = 1;
}
else { */
res->type = string_leaf;
res->leaf.canon = flags;
cl_string_latex2iso(s, s, strlen(s));
if (flags == IGNORE_REGEX || (strcspn(s, "[](){}.*+|?\\") == strlen(s) && flags == 0)) {
res->leaf.ctype.sconst = s;
res->leaf.pat_type = NORMAL;
}
else {
/* Sonderzeichen oder flags != 0/IGNORE_REGEX */
res->leaf.pat_type = REGEXP;
res->leaf.ctype.sconst = s;
res->leaf.rx = cl_new_regex(s, flags, query_corpus->corpus->charset);
if (res->leaf.rx == NULL) {
cqpmessage(Error, "Illegal regular expression: %s", s);
res->leaf.pat_type = NORMAL;
generate_code = 0;
}
}
/* } */
}
if (!generate_code)
res = NULL;
return res;
}
/* in an mval_string regexp, matchall dots ('.') need to be converted to '[^|]'
in order to give intuitive results (otherwise, '.*' might gobble up all the following
separator bars ('|')) */
char *
mval_string_conversion(char *s)
{
char *result, *p;
int cnt = 0;
for (p = s; *p; p++) /* count dots in <s> */
if (*p == '.') cnt++;
result = cl_malloc(strlen(s) + 3*cnt + 1); /* every '.'->'[^|]' replacement adds three characters */
p = result;
while (*s) {
if (*s == '\\') { /* copy escaped character verbatim */
*p++ = *s++;
if (!(*s)) {
cqpmessage(Error, "mval_string_conversion(): RegExp '%s' ends with escape", s);
generate_code = 0;
free(result);
return NULL;
}
*p++ = *s++;
}
else if (*s == '.') {
s++;
*p++ = '['; *p++ = '^'; *p++ = '|'; *p++ = ']';
}
else {
*p++ = *s++;
}
}
*p = 0; /* end of string */
return result;
}
/* do_mval_string() replaces do_flagged_string() for 'contains' and 'matches' operators
that operate on multi-valued attributes */
Constrainttree
do_mval_string(char *s, int op, int flags)
{
Constrainttree res = NULL;
char *pattern; /* regexp that simulates the multi-value operator */
char *converted_s;
int safe_regexp;
if (generate_code) {
if (flags == IGNORE_REGEX) {
cqpmessage(Error, "Can't use literal strings with 'contains' and 'matches' operators.");
generate_code = 0;
return NULL;
}
safe_regexp = !(strchr(s, '|') || strchr(s, '\\')); /* see below */
converted_s = mval_string_conversion(s);
if (!converted_s) return NULL; /* generate_code already set to 0 in subroutine */
pattern = cl_malloc(strlen(converted_s) + 42); /* leave some room for the regexp wrapper */
switch (op & OP_NOT_MASK) {
case OP_CONTAINS:
sprintf(pattern, ".*\\|(%s)\\|.*", converted_s);
break;
case OP_MATCHES:
if (safe_regexp) /* inner regexp is 'safe' so we can omit the parentheses and thus enable optimisation */
sprintf(pattern, "\\|(%s\\|)+", converted_s);
else
sprintf(pattern, "\\|((%s)\\|)+", converted_s);
break;
default:
/* undefined operator */
assert(0 && "do_mval_string(): illegal opcode (internal error)");
}
res = do_flagged_string(pattern, flags);
free(converted_s);
if (!res)
free(pattern); /* the pattern is inserted into the RegExp node, do don't free it unless do_flagged_string() failed */
}
return res;
}
Constrainttree
FunctionCall(char *f_name, ActualParamList *apl)
{
Constrainttree res;
int len, predef;
ActualParamList *p;
Attribute *attr;
res = NULL;
cqpmessage(Message, "FunctionCall: %s(...)", f_name);
if (generate_code) {
/* I'd like to check here whether the function
* gets the correct parameters. TODO
*/
len = 0;
for (p = apl; p; p = p->next)
len++;
predef = find_predefined(f_name);
if (predef >= 0) {
if (len != builtin_function[predef].nr_args) {
generate_code = 0;
cqpmessage(Error,
"Illegal number of arguments "
"for %s (needs %d, got %d)",
f_name, builtin_function[predef].nr_args, len);
}
else {
NEW_BNODE(res);
res->type = func;
res->func.predef = predef;
res->func.dynattr = NULL;
res->func.args = apl;
res->func.nr_args = len;
}
}
else if ((attr = find_attribute(query_corpus->corpus,
f_name,
ATT_DYN, NULL)) != NULL) {
NEW_BNODE(res);
res->type = func;
res->func.predef = -1;
res->func.dynattr = attr;
res->func.args = apl;
res->func.nr_args = len;
}
else {
cqpmessage(Error,
"Function or dynamic attribute "
"``%s'' is not defined", f_name);
generate_code = 0;
}
}
if (!generate_code)
res = NULL;
return res;
}
void
do_Description(Context *context, int nr, char *name)
{
context->type = word;
context->attrib = NULL;
context->size = 0;
if (generate_code) {
if (nr < 0) {
cqpmessage(Error,
"Can't expand to negative size: %d", nr);
generate_code = 0;
}
else if (Environment[0].query_corpus) {
context->size = nr;
if ((name == NULL) ||
(strcmp(name, "word") == 0) ||
(strcmp(name, "words") == 0)) {
context->type = word;
context->attrib = NULL;
}
else {
if ((context->attrib = find_attribute(Environment[0].query_corpus->corpus,
name,
ATT_STRUC, NULL)) == NULL) {
cqpmessage(Error,
"Structure ``%s'' is not defined for corpus ``%s''",
name, Environment[0].query_corpus->name);
generate_code = 0;
}
else
context->type = structure;
}
}
else {
cqpmessage(Error,
"No query corpus yielded and/or accessible");
generate_code = 0;
}
}
}
Evaltree do_MeetStatement(Evaltree left, Evaltree right, Context *context)
{
Evaltree ev;
ev = NULL;
if (generate_code) {
ev = (Evaltree)cl_malloc(sizeof(union e_tree));
ev->type = meet_union;
ev->cooc.op_id = cooc_meet;
ev->cooc.left = left;
ev->cooc.right = right;
ev->cooc.lw = context->size;
ev->cooc.rw = context->size2;
ev->cooc.struc = context->attrib;
}
return ev;
}
Evaltree
do_UnionStatement(Evaltree left, Evaltree right)
{
Evaltree ev;
ev = NULL;
if (generate_code) {
ev = (Evaltree)cl_malloc(sizeof(union e_tree));
ev->type = meet_union;
ev->cooc.op_id = cooc_union;
ev->cooc.left = left;
ev->cooc.right = right;
ev->cooc.lw = 0;
ev->cooc.rw = 0;
}
return ev;
}
void
do_StructuralContext(Context *context, char *name)
{
context->type = word;
context->attrib = NULL;
context->size = 1;
context->size2 = 1;
if (query_corpus) {
context->size = 1;
context->size2 = 1;
if ((context->attrib = find_attribute(query_corpus->corpus,
name,
ATT_STRUC, NULL)) == NULL) {
cqpmessage(Error,
"Structure ``%s'' is not defined for corpus ``%s''",
name, query_corpus->corpus->id);
generate_code = 0;
}
else
context->type = structure;
}
else {
context->size = 0;
generate_code = 0;
}
}
CorpusList *
do_TABQuery(Evaltree patterns)
{
CorpusList *cl;
cl = NULL;
if (parseonly || (generate_code == 0))
cl = NULL;
else if (patterns != NULL) {
assert(CurEnv == &Environment[0]);
CurEnv->evaltree = patterns;
assert(patterns->type == tabular);
debug_output();
do_start_timer();
cqp_run_tab_query();
cl = Environment[0].query_corpus;
}
return cl;
}
Evaltree
make_first_tabular_pattern(int pattern_index, Evaltree next)
{
union e_tree *node;
node = NULL;
if (generate_code) {
node = (union e_tree *)cl_malloc(sizeof(union e_tree));
node->type = tabular;
node->tab_el.patindex = pattern_index;
node->tab_el.min_dist = 0;
node->tab_el.max_dist = 0;
node->tab_el.next = next;
}
return node;
}
Evaltree
add_tabular_pattern(Evaltree patterns, Context *context, int pattern_index)
{
union e_tree *node, *k;
node = NULL;
if (generate_code) {
node = (union e_tree *)cl_malloc(sizeof(union e_tree));
node->type = tabular;
node->tab_el.patindex = pattern_index;
node->tab_el.min_dist = context->size;
node->tab_el.max_dist = context->size2;
node->tab_el.next = NULL;
if (patterns) {
for (k = patterns; k->tab_el.next; k = k->tab_el.next)
;
k->tab_el.next = node;
node = patterns;
}
}
return node;
}
void
do_OptDistance(Context *context, int l_bound, int u_bound)
{
if (l_bound < 0) {
cqpmessage(Warning, "Left/Min. distance must be >= 0 (reset to 0)");
l_bound = 0;
}
if (u_bound < 0 && u_bound != repeat_inf) {
cqpmessage(Warning, "Right/Max. distance must be >= 0 (reset to 0)");
u_bound = 0;
}
if (u_bound < l_bound && u_bound != repeat_inf) {
cqpmessage(Warning, "Right/Max. distance must be >= Left/Max. distance");
u_bound = l_bound;
}
context->type = word;
context->size = l_bound;
context->size2 = u_bound;
context->attrib = NULL;
}
/* ======================================== Variable Settings */
/**
* Prints the setting of a single Variable as an indented list.
*/
void
printSingleVariableValue(Variable v, int max_items)
{
int i;
if (v) {
Rprintf("$%s = \n", v->my_name);
if (max_items <= 0)
max_items = v->nr_items;
start_indented_list(0, 0, 0);
for (i = 0; i < v->nr_items; i++) {
if (i >= max_items) {
print_indented_list_item("...");
break;
}
if (!v->items[i].free) {
print_indented_list_item(v->items[i].sval);
}
}
end_indented_list();
}
}
void
do_PrintAllVariables()
{
Variable v;
variables_iterator_new();
while ((v = variables_iterator_next()) != NULL) {
printSingleVariableValue(v, 44); /* show at most 44 words from each variable in overview */
}
}
void
do_PrintVariableValue(char *varName)
{
Variable v;
if ((v = FindVariable(varName)) != NULL) {
printSingleVariableValue(v, 0);
}
else {
cqpmessage(Error, "%s: no such variable", varName);
}
}
void
do_printVariableSize(char *varName)
{
Variable v = FindVariable(varName);
if (v) {
int i, size = 0;
for (i = 0; i < v->nr_items; i++) {
if (!v->items[i].free)
size++;
}
Rprintf("$%s has %d entries\n", v->my_name, size);
}
else
cqpmessage(Error, "%s: no such variable", varName);
}
void
do_SetVariableValue(char *varName, char operator, char *varValues)
{
Variable v;
if ((v = FindVariable(varName)) == NULL)
v = NewVariable(varName);
if (v != NULL) {
if (operator != '<') {
cl_string_latex2iso(varValues, varValues, strlen(varValues));
}
if (!SetVariableValue(varName, operator, varValues))
cqpmessage(Error, "Error in variable value definition.");
}
else
cqpmessage(Warning, "Can't create variable, probably fatal (bad variable name?)");
}
void
do_AddSubVariables(char *var1Name, int add, char *var2Name)
{
Variable v1, v2;
char **items;
int i, N;
if ((v1 = FindVariable(var1Name)) == NULL) {
cqpmessage(Error, "Variable $%s not defined.", var1Name);
}
else if ((v2 = FindVariable(var2Name)) == NULL) {
cqpmessage(Error, "Variable $%s not defined.", var2Name);
}
else {
items = GetVariableStrings(v2, &N);
if (items != NULL) {
for (i = 0; i < N; i++) {
if (add)
VariableAddItem(v1, items[i]);
else
VariableSubtractItem(v1, items[i]);
}
cl_free(items); /* the actual strings point into the variable's internal representation, so don't free them */
}
else {
/* v2 is empty, so do nothing */
}
}
}
/* ======================================== PARSER UTILS */
/**
* Get ready to parse a command.
*
* This function is called before the processing of each parsed line that is
* recognised as a command.
*
* Mostly it involves setting the global variables to their starting-state
* values.
*/
void
prepare_input(void)
{
regex_string_pos = 0;
free_environments();
generate_code = 1;
searchstr = NULL;
last_cyc = NoExpression;
LastExpression = NoExpression;
}
/**
* Expand the dataspace of a subcorpus.
*
* This is done, e.g., by the CQP-syntax "expand" command, to include context
* into the matches found by a query.
*
* Each corpus interval stored in the CorpusList is extended by an amount, and in a direction,
* dependant on the information in the global variable "expansion", a Context object
* (information which has been put there by the parser).
*
* @see expansion
* @param cl The subcorpus to expand.
*/
void
expand_dataspace(CorpusList *cl)
{
int i, res;
if (cl == NULL)
cqpmessage(Warning, "The selected corpus is empty.");
else if (cl->type == SYSTEM)
cqpmessage(Warning, "You can only expand subcorpora, no system corpora (unchanged)");
else if (expansion.size > 0) {
for (i = 0; i < cl->size; i++) {
if (expansion.direction == left || expansion.direction == leftright) {
res = calculate_leftboundary(cl,
cl->range[i].start,
expansion);
if (res >= 0)
cl->range[i].start = res;
else
cqpmessage(Warning, "'expand' statement failed (while expanding corpus interval leftwards).\n");
}
if (expansion.direction == right || expansion.direction == leftright) {
res = calculate_rightboundary(cl,
cl->range[i].end,
expansion);
if (res >= 0)
cl->range[i].end = res;
else
cqpmessage(Warning, "'expand' statement failed (while expanding corpus interval rightwards).\n");
}
}
RangeSetop(cl, RUniq, NULL, NULL);
cl->needs_update = True;
cl->saved = False;
}
}
/**
* Add a character (in the sense of a byte) to the regex_string buffer.
*
* Doesn't seem to currently be in use.
*
* @see regex_string
*/
void
push_regchr(char c)
{
if (regex_string_pos < CL_MAX_LINE_LENGTH) {
regex_string[regex_string_pos] = c;
regex_string_pos++;
regex_string[regex_string_pos] = '\0';
}
else {
cqpmessage(Warning, "Regex string overflow");
regex_string[0] = '\0';
}
}
/**
* Prints out all the existing EvalEnvironments in the global array.
*
* @see Environment
*/
void
debug_output(void)
{
int i;
for (i = 0; i <= eep; i++)
show_environment(i);
}
/** Global variable for timing functions; not exported. @see do_start_timer @see do_timing */
struct timeval timer_start_time;
/**
* Starts the timer running.
*/
void
do_start_timer(void)
{
if (timing)
gettimeofday(&timer_start_time, NULL);
}
/**
* Shows the period since the timer started running.
*
* @param msg A message to print along with the reading from the timer.
*/
void
do_timing(char *msg)
{
struct timeval t;
long delta_s;
long delta_ms;
if (timing) {
gettimeofday(&t, NULL);
delta_s = t.tv_sec - timer_start_time.tv_sec;
delta_ms = (t.tv_usec - timer_start_time.tv_usec) / 1000;
if (delta_ms < 0) {
delta_s--;
delta_ms = delta_ms + 1000;
}
cqpmessage(Info, "%s in %ld.%.3ld seconds\n", msg, delta_s, delta_ms);
}
}
/* ====================================== CQP Child mode: Size & Dump */
void
do_size(CorpusList *cl, FieldType field)
{
if (cl) {
if (field != NoField) {
if (field == TargetField) {
int count = 0, i;
if (cl->targets) {
for (i = 0; i < cl->size; i++) {
if (cl->targets[i] != -1)
count++;
}
}
Rprintf("%d\n", count);
}
else if (field == KeywordField) {
int count = 0, i;
if (cl->keywords) {
for (i = 0; i < cl->size; i++) {
if (cl->keywords[i] != -1)
count++;
}
}
Rprintf("%d\n", count);
}
else { /* must be Match or MatchEnd then */
Rprintf("%d\n", cl->size);
}
}
else {
Rprintf("%d\n", cl->size);
}
}
else {
Rprintf("0\n"); /* undefined corpus */
}
}
/**
* Dump query result (or part of it) as TAB-delimited table of corpus positions.
*
* @param cl The result (as a subcorpus, naturally)
* @param first Where in the result to begin dumping (index of cl->range)
* @param last Where in the result to end dumping (index of cl->range)
* @param rd Pointer to a Redir structure which contains information about
* where to dump to.
*/
void
do_dump(CorpusList *cl, int first, int last, struct Redir *rd)
{
int i, j, f, l, target, keyword;
Range *rg;
if (cl) {
if (! open_stream(rd, cl->corpus->charset)) {
cqpmessage(Error, "Can't redirect output to file or pipe\n");
return;
}
f = (first >= 0) ? first : 0;
l = (last < cl->size) ? last : cl->size - 1;
for (i = f; (i <= l) && !cl_broken_pipe; i++) {
j = (cl->sortidx) ? cl->sortidx[i] : i;
target = (cl->targets) ? cl->targets[j] : -1;
keyword = (cl->keywords) ? cl->keywords[j] : -1;
rg = cl->range + j;
Rprintf("%d\t%d\t%d\t%d\n", rg->start, rg->end, target, keyword);
}
close_stream(rd);
}
}
/** read TAB-delimited table of corpus positions and create named query result from it.
*
* acceptable values for extension_fields and corresponding row formats:
* 0 = match \t matchend
* 1 = match \t matchend \t target
* 2 = match \t matchend \t target \t keyword
*/
int
do_undump(char *corpname, int extension_fields, int sort_ranges, struct InputRedir *rd)
{
int i, ok, size, match, matchend, target, keyword;
int max_cpos, mark, abort; /* for validity checks */
char line[CL_MAX_LINE_LENGTH], junk[CL_MAX_LINE_LENGTH], mother[CL_MAX_LINE_LENGTH];
CorpusList *cl = current_corpus, *new = NULL;
assert(corpname != NULL);
assert((extension_fields >= 0) && (extension_fields <= 2));
if (! valid_subcorpus_name(corpname)) {
cqpmessage(Error, "Argument %s is not a valid query name.", corpname);
return 0;
}
if (is_qualified(corpname)) { /* if <corpname> is qualified, use specified mother corpus */
corpname = split_subcorpus_name(corpname, mother); /* reset <corpname> to point to local name, copy qualifier to <mother> */
cl = findcorpus(mother, SYSTEM, 0);
if (cl == NULL) {
cqpmessage(Error, "Can't find system corpus %s. Undump aborted.\n", mother);
return 0;
}
}
else { /* otherwise, check for activated corpus for which named query result will be created */
if (cl == NULL) {
cqpmessage(Error, "No corpus activated. Can't perform undump.");
return 0;
}
if (cl->type != SYSTEM) { /* if a subcorpus is activated, find the corresponding system corpus */
CorpusList *tmp;
assert(cl->mother_name != NULL);
tmp = findcorpus(cl->mother_name, SYSTEM, 0);
if (tmp == NULL) {
cqpmessage(Error, "Can't find implicitly activated corpus %s. Undump aborted.\n", cl->mother_name);
return 0;
}
cl = tmp;
} /* cl now points to the currently active system corpus */
}
new = make_temp_corpus(cl, "UNDUMP_TMP"); /* create temporary subcorpus that will hold the undump data */
assert((new != NULL) && "failed to create temporary query result for undump");
if (! open_input_stream(rd)) { /* open input file, input pipe, or read from stdin */
/* error message should printed by open_input_stream() */
drop_temp_corpora();
return 0;
}
ok = 0; /* read undump table header = number of rows */
if (fgets(line, CL_MAX_LINE_LENGTH, rd->stream)) {
if (1 == sscanf(line, "%d %s", &size, junk)) {
ok = 1;
}
else if (2 == sscanf(line, "%d %d", &match, &matchend)) {
/* looks like undump file without line count => determine number of lines */
if (rd->stream == stdin) {
cqpmessage(Warning, "You must always provide an explicit line count if undump data is entered manually (i.e. read from STDIN)");
}
else {
/* undump file without header: count lines, then reopen stream */
size = 1; /* first line is already in buffer */
while (fgets(line, CL_MAX_LINE_LENGTH, rd->stream))
size++; /* dump files should not contain any long lines, so this count is correct */
close_input_stream(rd);
if (! open_input_stream(rd))
cqpmessage(Warning, "Can't rewind undump file after counting lines: line count must be given explicitly");
else
ok = 1;
}
}
}
if (!ok) {
cqpmessage(Error, "Format error in undump file: expecting number of rows on first line");
close_input_stream(rd);
drop_temp_corpora();
return 0;
}
cl_free(new->range); /* free previous match data (should only be one range for system corpus) */
cl_free(new->sortidx);
cl_free(new->targets);
cl_free(new->keywords);
new->size = size; /* allocate space for required number of (match, matchend) pairs, targets, keywords */
new->range = (Range *) cl_malloc(sizeof(Range) * size);
if (extension_fields >= 1) new->targets = (int *) cl_malloc(sizeof(int) * size);
if (extension_fields >= 2) new->keywords = (int *) cl_malloc(sizeof(int) * size);
max_cpos = cl->mother_size - 1; /* check validity, ordering, and non-overlapping of match ranges */
mark = -1;
abort = 0;
for (i = 0; (i < size) && !abort; i++) { /* now read one data row at a time from the undump table */
if (feof(rd->stream)
|| (!fgets(line, CL_MAX_LINE_LENGTH, rd->stream)) /* parse input line format */
|| (sscanf(line, "%d %d %d %d %s", &match, &matchend, &target, &keyword, junk)
!= (2 + extension_fields))
) {
cqpmessage(Error, "Format error in undump file (row #%d)", i+1);
abort = 1;
break;
}
if (matchend < match) { /* check validity of match .. matchend range */
cqpmessage(Error, "match (%d) must be <= matchend (%d) on row #%d", match, matchend, i+1);
abort = 1;
}
else if (match < 0 || matchend > max_cpos) {
cqpmessage(Error, "match (%d .. %d) out of range (0 .. %d) on row #%d", match, matchend, max_cpos, i+1);
abort = 1;
}
else if ((! sort_ranges) && (match <= mark)) { /* current range must start _after_ end of previous range (unless sort_ranges==1) */
cqpmessage(Error, "matches must be sorted and non-overlapping\n\t"
"match (%d) on row #%d overlaps with previous matchend (%d)", match, i+1, mark);
abort = 1;
}
else {
new->range[i].start = match;
new->range[i].end = matchend;
mark = matchend;
}
if (extension_fields >= 1) { /* check validity of target position if specified */
if (target < -1 || target > max_cpos) {
cqpmessage(Error, "target (%d) out of range (0 .. %d) on row #%d", target, max_cpos, i+1);
abort = 1;
}
else
new->targets[i] = target;
}
if (extension_fields >= 2) { /* check validity of keyword position if specified */
if (keyword < -1 || keyword > max_cpos) {
cqpmessage(Error, "keyword (%d) out of range (0 .. %d) on row #%d", keyword, max_cpos, i+1);
abort = 1;
}
else
new->keywords[i] = keyword;
}
}
if (abort) { /* when an error was detected, don't create the named query result */
close_input_stream(rd);
drop_temp_corpora();
return 0;
}
if (! close_input_stream(rd)) { /* ignore trailing junk etc. */
cqpmessage(Warning, "There may be errors in the undump data. Please check the named query result %s.\n", corpname);
}
if (sort_ranges) { /* if ranges aren't sorted in natural order, they must be re-ordered so that CQP can work with them */
RangeSort(new, 1); /* however, a sortidx is automatically constructed to reproduce the ordering of the input file */
}
new = assign_temp_to_sub(new, corpname); /* copy the temporary subcorpus to the requested query name */
drop_temp_corpora();
if (new == NULL) {
cqpmessage(Error, "Couldn't assign undumped data to named query %s.\n");
return 0;
}
return 1;
}
|
myoKun345/RcppCWB
|
src/cwb/cqp/variables.c
|
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "../cl/corpus.h"
#include "../cl/attributes.h"
#include "../cl/cdaccess.h"
#include "../cl/macros.h"
#include "variables.h"
#include "output.h"
#include "options.h"
/* TODO: shrink malloced buffers as necessary - for VarSpace as well
as for items in single vars */
/* ---------------------------------------------------------------------- */
/** How many pointers to allocate space for at one time to a Variable's ->items array*/
#define ITEM_REALLOC 8
/** How many pointers to allocate space for at one time to the global array VariableSpace */
#define VARIABLE_REALLOC 16
/** Number of variables in VariableArray (exported)*/
int nr_variables = 0;
/** Global array of Variables (exported) */
Variable *VariableSpace = NULL;
/* ---------------------------------------------------------------------- */
/**
* Finds the Variable object of the given name, if it
* exists in VariableSpace.
*
* @param varname The name of the variable required.
* @return The Variable requested, or NULL if no Variable by that
* name could be found.
*/
Variable
FindVariable(char *varname)
{
int i;
for (i = 0; i < nr_variables; i++)
if (VariableSpace[i] && strcmp(VariableSpace[i]->my_name, varname) == 0)
return VariableSpace[i];
return NULL;
}
/**
* Tests whether a given string exists within the variable.
*
* @return Boolean: true if the variable contains the string.
*/
int
VariableItemMember(Variable v, char *item)
{
int i;
for (i = 0; i < v->nr_items; i++)
if (!v->items[i].free && strcmp(v->items[i].sval, item) == 0)
return 1;
return 0;
}
/**
* Adds a string to the variable.
*
* @return Always 1.
*/
int
VariableAddItem(Variable v, char *item)
{
int i;
if (!VariableItemMember(v, item)) {
/* Since the contents of the variable changes here, it will no longer be valid against
* any corpus / attrribute it has previously been checked against. */
v->valid = 0;
for (i = 0; i < v->nr_items; i++)
if (v->items[i].free) {
v->items[i].free = 0;
v->items[i].sval = cl_strdup(item);
v->items[i].ival = -1;
break;
}
if (i >= v->nr_items) {
/* no space in list. malloc. */
v->nr_items += ITEM_REALLOC;
if (v->items == NULL)
v->items = (VariableItem *)cl_malloc(sizeof(VariableItem) * v->nr_items);
else
v->items = (VariableItem *)cl_realloc(v->items, sizeof(VariableItem) * v->nr_items);
if (v->items == NULL) {
Rprintf("Fatal Error #6: no memory left.");
perror("Memory fault");
assert(0 && "Big Problem here!");
}
/* insert the new item into the FIRST newly allocated item; then set the REST as empty. */
v->items[i].sval = cl_strdup(item);
v->items[i].free = 0;
v->items[i].ival = -1;
i++;
for ( ; i < v->nr_items; i++) {
v->items[i].sval = NULL;
v->items[i].free = 1;
v->items[i].ival = -1;
}
}
}
return 1;
}
/**
* Remove a string from a defined Variable.
*
* Identification of the string to remove is by bytewise identity.
*
* @param v The variable.
* @param item The string to take out of the variable.
* @return Always 1
*/
int
VariableSubtractItem(Variable v, const char *item)
{
int i;
/* by altering the list, it is automatically no longer valid:
* it will need to be rechecked if it has already been checked. */
v->valid = 0;
for (i = 0; i < v->nr_items; i++) {
/* if this item is the string we want to remove, free the string, set the integer value to -1, and flag as free.
* IE everything in the item gets scrubbed. */
if (!v->items[i].free && v->items[i].sval != NULL && strcmp(v->items[i].sval, item) == 0) {
cl_free(v->items[i].sval);
v->items[i].ival = -1;
v->items[i].free++;
}
}
return 1;
}
/**
* Deletes and frees up all memory associated with the strings contained by this variable.
*
* The variable continues to exist, but is now empty.
*/
int
VariableDeleteItems(Variable v)
{
int i;
/* first, free the strings. */
for (i = 0; i < v->nr_items; i++)
cl_free(v->items[i].sval);
v->valid = 0;
v->nr_items = 0;
v->nr_valid_items = 0;
v->nr_invalid_items = 0;
cl_free(v->items);
return 1;
}
/**
* Deletes all the memory associated with a given variable.
* If the Variable is in VariableSpace, that slot in VariableSpace is emptied out.
*
* @param vp Note that this function takes a POINTER
* to a Variable object, not a Variable itself (even though
* Variable IS a pointer type)... allowing the object to be set
* to NULL once emptied out.
* @return Always 1.
*/
int
DropVariable(Variable *vp)
{
int i;
Variable v = *vp;
VariableDeleteItems(v);
cl_free(v->my_name);
cl_free(v->my_corpus);
cl_free(v->my_attribute);
for (i = 0; i < nr_variables; i++)
if (VariableSpace[i] == v) {
VariableSpace[i] = NULL;
break;
}
/* triggered if the variable object supplied is NOT in VariableSpace, which all Variables should be. */
if (i >= nr_variables)
Rprintf("Error #5 in variable logic. Please contact developer.\n");
*vp = NULL;
vp = NULL;
return 1;
}
/**
* Creates a new Variable (set of strings) with the specified name within the global VariableSpace.
*
* Returns NULL only if the variable string name was NULL.
*/
Variable
NewVariable(char *varname)
{
Variable v;
int i;
/* the caller may or may not have checked this. */
if (varname == NULL)
return NULL;
v = (Variable)cl_malloc(sizeof(VariableBuffer));
v->valid = 0;
v->my_name = cl_strdup(varname);
v->my_corpus = NULL;
v->my_attribute = NULL;
v->nr_items = 0;
v->items = NULL;
for (i = 0; i < nr_variables; i++) {
if (VariableSpace[i] == NULL) {
VariableSpace[i] = v;
break;
}
}
if (i >= nr_variables) {
/* not inserted, malloc */
nr_variables += VARIABLE_REALLOC;
if (VariableSpace == NULL)
VariableSpace = (Variable *)cl_malloc(nr_variables * sizeof(Variable));
else
VariableSpace = (Variable *)cl_realloc(VariableSpace,
nr_variables * sizeof(Variable));
/* no longer necessary: cl_malloc/_realloc checks for this.
if (VariableSpace == NULL) {
RprintF("Fatal Error: Variable space out of memory.\n");
assert(0 && "Sorry, big problem here!");
} */
VariableSpace[i++] = v;
for ( ; i < nr_variables; i++)
VariableSpace[i] = NULL;
}
return v;
}
/**
* Sets the value of a variable; returns true for success, false for failure.
*/
int
SetVariableValue(char *varName,
char operator,
char *varValues)
{
Variable v;
char *item;
FILE *fd;
if ((v = FindVariable(varName)) == NULL) {
v = NewVariable(varName);
if (v == NULL) {
cqpmessage(Error, "Bad variable name supplied!");
return 0;
}
}
switch (operator) {
case '+': /* += operator: extend */
item = strtok(varValues, " \t\n");
while (item) {
VariableAddItem(v, item);
item = strtok(NULL, " \t\n");
}
break;
case '-': /* -= operator: substract */
item = strtok(varValues, " \t\n");
while (item) {
VariableSubtractItem(v, item);
item = strtok(NULL, " \t\n");
}
break;
case '=': /* = operator: absolute setting */
VariableDeleteItems(v);
item = strtok(varValues, " \t\n");
while (item) {
VariableAddItem(v, item);
item = strtok(NULL, " \t\n");
}
break;
case '<': /* < operator: read from file */
VariableDeleteItems(v);
fd = cl_open_stream(varValues, CL_STREAM_READ, (insecure) ? CL_STREAM_MAGIC_NOPIPE : CL_STREAM_MAGIC);
if (fd) {
int l;
char s[CL_MAX_LINE_LENGTH];
while (fgets(s, CL_MAX_LINE_LENGTH, fd) != NULL) {
/* remove trailing line break (LF or CR-LF) */
cl_string_chomp(s);
l = strlen(s);
if (l > 0)
VariableAddItem(v, s);
}
cl_close_stream(fd);
}
else {
cl_error(varValues);
cqpmessage(Warning, "Can't open %s: no such file or directory", varValues);
return 0;
}
break;
default:
return 0;
break;
}
return 1;
}
/*
* variables iterator: one non-exported integer and two functions.
*/
int variables_iterator_idx;
/**
* Resets the global variables iterator to the beginning of the global VariableSpace array.
*/
void
variables_iterator_new(void)
{
variables_iterator_idx = 0;
}
/**
* Gets the next Variable object from the variables iterator.
*
* Returns NULL if the iterator has reached the end of the global VariableSpace array.
*
* @see VariableSpace
* @return The next Variable object from the iterator.
*/
Variable
variables_iterator_next(void)
{
if (variables_iterator_idx < nr_variables)
return VariableSpace[variables_iterator_idx++];
else
return NULL;
}
/**
* Verify a variable for use with a given p-attribute of a given corpus.
*
* This associates the variable with the supplied corpus/attribute,
* plus checks the variable's strings against the relevant attribute lexicon.
*
* @return Boolean: true for all OK, false if something went wrong (problem with
* the arguments, or if none of the variable's strings match the
* lexicon). Same as the value of the Variable's "valid" flag after this
* function has run.
*/
int
VerifyVariable(Variable v, Corpus *corpus, Attribute *attribute)
{
int i;
char *str;
/* nr valid = n of strings in the var that are also in the corpus lexicon. */
int nr_valid, nr_invalid;
/* only verify the variable if (a) it is not already verified,
* or (b) it is verified, but for another corpus. */
if ( (! v->valid) ||
v->my_corpus == NULL || v->my_attribute == NULL ||
strcmp(v->my_corpus, corpus->registry_name) != 0 ||
strcmp(v->my_attribute, attribute->any.name) != 0) {
v->valid = 0;
cl_free(v->my_corpus);
cl_free(v->my_attribute);
if (attribute->any.type != ATT_POS)
return 0;
v->my_corpus = cl_strdup(corpus->registry_name);
v->my_attribute = cl_strdup(attribute->any.name);
nr_valid = 0;
nr_invalid = 0;
for (i = 0; i < v->nr_items; i++) {
/* check each string against the lexicon: store matching lexicon ID, if there is one. */
if (!v->items[i].free) {
if (v->items[i].sval == NULL) {
/* string shouldn't be NULL if free has been set to True */
Rprintf("Error #1 in variable logic. Contact developer.\n");
v->items[i].ival = -1;
}
else {
/* Variable strings are not verified on load - so we now need to check against the corpus charset. */
if (!cl_string_validate_encoding(v->items[i].sval, corpus->charset, 0))
cqpmessage(Error,
"Variable $%s includes one or more strings with characters that are invalid\n"
"in the encoding specified for corpus [%s]", v->my_name, v->my_corpus);
/* In utf8: lookup against canonicalised string. Otherwise: lookup against the string as-is. */
if (utf8 == corpus->charset) {
str = cl_string_canonical(v->items[i].sval, corpus->charset, REQUIRE_NFC, CL_STRING_CANONICAL_STRDUP);
v->items[i].ival = cl_str2id(attribute, str);
cl_free(str);
}
else
v->items[i].ival = cl_str2id(attribute, v->items[i].sval);
}
if (v->items[i].ival < 0)
nr_invalid++;
else
nr_valid++;
}
}
v->nr_valid_items = nr_valid;
v->nr_invalid_items = nr_invalid;
if (nr_valid > 0)
v->valid = 1;
else
v->valid = 0;
}
return v->valid;
}
/** comparison function for qsort() of id_list returned by GetVariableItems */
static
int intcompare(const void *i, const void *j)
{
return(*(int *)i - *(int *)j);
}
/**
* Get lexicon IDs of variable's strings in corpus.attribute lexicon.
*
* @param v The Variable object.
* @param corpus The corpus we are working with.
* @param attribute The attribute against which to verify the Variable's items
* @param nr_items This will be set to the number of integers in the returned array.
* @return Pointer to block of integers based on valid items from the variable;
* NULL if there were no valid items (i.e. items found in the
* attribute's lexicon).
*/
int *
GetVariableItems(Variable v,
Corpus *corpus,
Attribute *attribute,
/* returned: */
int *nr_items)
{
int *items;
int i, ip; /* ip = index into the new "items" array, whereas i indexes the v->items array */
if (VerifyVariable(v, corpus, attribute)) {
if (v->nr_valid_items > 0) {
items = (int *)cl_malloc(v->nr_valid_items * sizeof(int));
*nr_items = v->nr_valid_items;
ip = 0;
for (i = 0; i < v->nr_items; i++)
if (!v->items[i].free && v->items[i].ival >= 0) {
if (ip >= v->nr_valid_items)
Rprintf("Error #2 in variable logic. Please contact developer.\n");
else {
items[ip] = v->items[i].ival;
ip++;
}
}
if (ip != v->nr_valid_items)
Rprintf("Error #3 in variable logic. Please contact developer.\n");
/* eval_bool() expects a sorted list of IDs (for binary search) */
qsort(items, *nr_items, sizeof(int), intcompare);
return items;
}
else {
*nr_items = 0;
return NULL;
}
}
else {
*nr_items = 0;
return NULL;
}
}
/**
* Returns an array of pointers to a variable's strings.
*
* Return value is NULL if there were no strings stored in the variable.
* The number of strings that were found is inserted into nr_items.
*
* The array that is returned must be freed by the caller.
*
* @param v The Variable whose strings you want.
* @param nr_items The number of strings found will be put here.
* @return Table of pointers to the Variable's strings.
*/
char **
GetVariableStrings(Variable v, int *nr_items)
{
char **result;
int i, j, N;
/* count number of items (strings) stored in variable */
N = 0;
for (i=0; i < v->nr_items; i++)
if (!v->items[i].free)
N++;
*nr_items = N;
if (N == 0) {
return NULL;
}
else {
/* allocate pointer table which will be returned */
result = cl_malloc(N * sizeof(char *));
/* insert pointers into result table */
j = 0;
for (i=0; i < v->nr_items; i++) {
if (!v->items[i].free) {
result[j] = v->items[i].sval;
j++;
}
}
return result;
}
}
|
myoKun345/RcppCWB
|
src/utils.h
|
<reponame>myoKun345/RcppCWB
Corpus *corpus;
int cleanup(int error_code);
void compress_reversed_index(Attribute *attr, char *output_fn, char *corpus_id, int debug);
void decompress_check_reversed_index(Attribute *attr, char *output_fn, char *corpus_id, int debug);
int decode_check_huff(Attribute *attr, char* corpus_id, char *fname);
int compute_code_lengths(Attribute *attr, HCD *hc, char *fname);
int do_attribute(Attribute *attr, ComponentID cid, int validate);
|
myoKun345/RcppCWB
|
src/cwb/cqp/lex.yy.c
|
#line 3 "lex.yy.c"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 35
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
typedef uint64_t flex_uint64_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
#endif /* ! C99 */
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN (yy_start) = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START (((yy_start) - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart(yyin )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#define YY_BUF_SIZE 16384
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
extern yy_size_t yyleng;
extern FILE *yyin, *yyout;
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
#define YY_LESS_LINENO(n)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = (yy_hold_char); \
YY_RESTORE_YY_MORE_OFFSET \
(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, (yytext_ptr) )
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
yy_size_t yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* Stack of input buffers. */
static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
? (yy_buffer_stack)[(yy_buffer_stack_top)] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
/* yy_hold_char holds the character lost when yytext is formed. */
static char yy_hold_char;
static yy_size_t yy_n_chars; /* number of characters read into yy_ch_buf */
yy_size_t yyleng;
/* Points to current character in buffer. */
static char *yy_c_buf_p = (char *) 0;
static int yy_init = 0; /* whether we need to initialize */
static int yy_start = 0; /* start state number */
/* Flag which is used to allow yywrap()'s to do buffer switches
* instead of setting up a fresh yyin. A bit of a hack ...
*/
static int yy_did_buffer_switch_on_eof;
void yyrestart (FILE *input_file );
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer );
YY_BUFFER_STATE yy_create_buffer (FILE *file,int size );
void yy_delete_buffer (YY_BUFFER_STATE b );
void yy_flush_buffer (YY_BUFFER_STATE b );
void yypush_buffer_state (YY_BUFFER_STATE new_buffer );
void yypop_buffer_state (void );
static void yyensure_buffer_stack (void );
static void yy_load_buffer_state (void );
static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file );
#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER )
YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size );
YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str );
YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len );
void *yyalloc (yy_size_t );
void *yyrealloc (void *,yy_size_t );
void yyfree (void * );
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define yywrap(n) 1
#define YY_SKIP_YYWRAP
typedef unsigned char YY_CHAR;
FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
typedef int yy_state_type;
extern int yylineno;
int yylineno = 1;
extern char *yytext;
#define yytext_ptr yytext
static yy_state_type yy_get_previous_state (void );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state );
static int yy_get_next_buffer (void );
static void yy_fatal_error (yyconst char msg[] );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
(yytext_ptr) = yy_bp; \
yyleng = (yy_size_t) (yy_cp - yy_bp); \
(yy_hold_char) = *yy_cp; \
*yy_cp = '\0'; \
(yy_c_buf_p) = yy_cp;
#define YY_NUM_RULES 121
#define YY_END_OF_BUFFER 122
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static yyconst flex_int16_t yy_acclist[578] =
{ 0,
122, 120, 121, 99, 120, 121, 99, 121, 120, 121,
120, 121, 100, 120, 121, 120, 121, 120, 121, 120,
121, 120, 121, 120, 121, 120, 121, 120, 121, 120,
121, 86, 120, 121, 120, 121, 120, 121, 120, 121,
120, 121, 96, 120, 121, 96, 120, 121, 96, 120,
121, 96, 120, 121, 96, 120, 121, 120, 121, 119,
120, 121, 96, 120, 121, 96, 120, 121, 96, 120,
121, 96, 120, 121, 96, 120, 121, 96, 120, 121,
96, 120, 121, 96, 120, 121, 96, 120, 121, 96,
120, 121, 96, 120, 121, 96, 120, 121, 96, 120,
121, 96, 120, 121, 96, 120, 121, 96, 120, 121,
96, 120, 121, 96, 120, 121, 96, 120, 121, 96,
120, 121, 96, 120, 121, 99, 113, 101, 100, 97,
98, 101, 118, 86, 115, 116, 117, 110, 86, 108,
107, 111, 103, 103, 103, 103, 103, 112, 114, 93,
96, 96, 92, 28, 96, 96, 96, 96, 106, 102,
96, 32, 96, 96, 13, 96, 96, 96, 96, 96,
96, 96, 96, 96, 96, 96, 96, 96, 96, 96,
96, 96, 96, 96, 37, 96, 96, 34, 96, 96,
96, 96, 96, 96, 96, 96, 96, 96, 96, 96,
21, 96, 96, 96, 96, 96, 96, 101, 97, 101,
109, 90, 89, 103, 103, 103, 103, 103, 91, 96,
94, 94, 96, 84, 29, 96, 95, 38, 96, 2,
96, 96, 96, 96, 24, 96, 3, 96, 96, 96,
96, 96, 96, 96, 96, 96, 96, 96, 96, 96,
96, 96, 96, 96, 96, 96, 96, 96, 96, 96,
96, 96, 48, 96, 36, 96, 96, 96, 96, 96,
96, 22, 96, 96, 96, 96, 96, 96, 96, 96,
96, 96, 96, 96, 96, 96, 96, 35, 96, 89,
104, 103, 103, 103, 103, 91, 96, 91, 96, 94,
59, 96, 105, 96, 96, 96, 96, 96, 96, 39,
96, 4, 96, 96, 45, 96, 96, 1, 96, 96,
96, 96, 56, 96, 96, 53, 96, 96, 25, 96,
96, 7, 96, 96, 9, 96, 96, 96, 96, 26,
96, 96, 96, 96, 96, 96, 11, 96, 12, 96,
44, 96, 96, 30, 96, 96, 96, 96, 96, 96,
96, 96, 52, 96, 96, 17, 96, 85, 89, 103,
103, 103, 103, 91, 96, 94, 96, 96, 96, 31,
96, 96, 96, 96, 96, 96, 96, 96, 96, 96,
14, 96, 96, 6, 96, 96, 96, 54, 96, 60,
96, 96, 96, 96, 96, 96, 10, 96, 41, 96,
96, 96, 96, 96, 96, 27, 96, 96, 15, 96,
96, 96, 103, 103, 103, 103, 96, 96, 96, 3,
96, 19, 96, 96, 96, 96, 96, 20, 96, 96,
96, 96, 96, 96, 96, 65, 92, 96, 96, 96,
96, 42, 96, 96, 96, 23, 96, 8, 96, 96,
62, 96, 46, 96, 51, 96, 16, 96, 96, 88,
87, 103, 103, 70, 103, 103, 96, 96, 96, 96,
96, 5, 96, 96, 96, 33, 96, 96, 96, 64,
96, 96, 96, 50, 96, 43, 96, 82, 96, 96,
40, 96, 96, 96, 67, 92, 18, 96, 75, 104,
103, 103, 103, 72, 96, 96, 49, 96, 96, 96,
96, 83, 96, 96, 96, 69, 92, 80, 96, 61,
96, 96, 96, 47, 96, 77, 104, 103, 74, 103,
38, 96, 63, 96, 96, 96, 58, 96, 57, 96,
6, 96, 66, 92, 55, 96, 81, 96, 79, 104,
103, 71, 68, 92, 39, 96, 4, 96, 96, 76,
104, 73, 96, 78, 104, 6, 96
} ;
static yyconst flex_int16_t yy_accept[477] =
{ 0,
1, 1, 1, 2, 4, 7, 9, 11, 13, 16,
18, 20, 22, 24, 26, 28, 30, 32, 35, 37,
39, 41, 43, 46, 49, 52, 55, 58, 60, 63,
66, 69, 72, 75, 78, 81, 84, 87, 90, 93,
96, 99, 102, 105, 108, 111, 114, 117, 120, 123,
126, 127, 128, 128, 129, 129, 130, 131, 132, 132,
133, 133, 134, 135, 136, 137, 138, 139, 139, 139,
139, 140, 141, 142, 142, 143, 144, 145, 146, 147,
148, 149, 150, 151, 152, 153, 154, 154, 156, 157,
158, 159, 159, 160, 161, 161, 162, 164, 165, 167,
168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
178, 179, 180, 181, 182, 183, 184, 185, 187, 188,
190, 191, 192, 193, 194, 195, 196, 197, 198, 199,
200, 201, 203, 204, 205, 206, 207, 208, 208, 209,
209, 210, 210, 211, 211, 211, 212, 212, 213, 213,
214, 214, 214, 214, 214, 214, 215, 216, 217, 218,
219, 221, 222, 223, 224, 225, 227, 227, 227, 227,
228, 230, 232, 233, 234, 235, 237, 239, 240, 241,
242, 243, 244, 245, 246, 247, 248, 249, 250, 251,
252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
262, 263, 265, 267, 268, 269, 270, 271, 272, 274,
275, 276, 277, 278, 279, 280, 281, 282, 283, 284,
285, 286, 287, 288, 290, 291, 291, 291, 291, 291,
292, 292, 292, 292, 292, 293, 294, 295, 296, 298,
300, 301, 301, 303, 304, 305, 306, 307, 308, 309,
310, 312, 314, 315, 317, 318, 320, 321, 322, 323,
325, 326, 328, 329, 331, 332, 334, 335, 337, 338,
339, 340, 342, 343, 344, 345, 346, 347, 349, 351,
353, 354, 356, 357, 358, 359, 360, 361, 362, 363,
365, 366, 368, 369, 369, 369, 370, 370, 370, 370,
370, 371, 372, 373, 374, 376, 377, 378, 379, 380,
382, 383, 384, 385, 386, 387, 388, 389, 390, 391,
393, 394, 396, 397, 398, 400, 402, 403, 404, 405,
406, 407, 409, 411, 412, 413, 414, 415, 416, 418,
419, 421, 422, 423, 423, 423, 423, 423, 423, 424,
425, 426, 427, 428, 429, 430, 432, 434, 435, 436,
437, 438, 440, 441, 442, 443, 444, 445, 446, 448,
449, 450, 451, 452, 454, 455, 456, 458, 460, 461,
463, 465, 467, 469, 470, 471, 472, 472, 472, 472,
472, 473, 474, 475, 476, 477, 478, 479, 480, 481,
482, 484, 485, 486, 488, 489, 490, 492, 493, 494,
496, 498, 500, 501, 503, 504, 505, 507, 509, 509,
509, 511, 511, 511, 512, 513, 514, 515, 516, 517,
519, 520, 521, 522, 524, 525, 526, 528, 530, 532,
533, 534, 536, 536, 536, 536, 538, 539, 540, 541,
543, 545, 546, 547, 549, 551, 553, 555, 557, 559,
559, 561, 561, 562, 563, 565, 567, 569, 570, 570,
572, 573, 574, 576, 578, 578
} ;
static yyconst flex_int32_t yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
1, 1, 4, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 5, 6, 7, 8, 9, 1, 10, 11,
1, 12, 13, 1, 14, 15, 16, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 18, 1, 19,
20, 21, 22, 23, 24, 25, 26, 26, 27, 26,
26, 26, 26, 26, 26, 28, 29, 30, 31, 26,
26, 32, 26, 33, 34, 26, 26, 26, 26, 26,
35, 36, 37, 38, 26, 39, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 1, 1, 1, 1, 1, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66
} ;
static yyconst flex_int32_t yy_meta[67] =
{ 0,
1, 1, 2, 3, 1, 1, 1, 1, 1, 1,
4, 1, 1, 5, 5, 6, 5, 7, 1, 6,
8, 1, 1, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 4, 1, 1, 10, 11, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 13
} ;
static yyconst flex_int16_t yy_base[500] =
{ 0,
0, 0, 753, 1864, 65, 68, 730, 67, 0, 0,
0, 64, 716, 58, 59, 62, 0, 66, 64, 68,
65, 709, 75, 77, 87, 79, 104, 89, 0, 94,
115, 116, 120, 122, 129, 133, 128, 157, 159, 163,
173, 174, 178, 185, 187, 224, 206, 232, 211, 219,
159, 1864, 93, 717, 151, 0, 0, 0, 88, 712,
113, 1864, 99, 1864, 1864, 1864, 703, 681, 130, 694,
189, 1864, 1864, 224, 1864, 0, 645, 650, 653, 651,
1864, 1864, 1864, 218, 274, 0, 0, 262, 278, 283,
284, 102, 197, 1864, 646, 289, 290, 295, 296, 300,
302, 311, 321, 326, 332, 327, 337, 353, 358, 367,
368, 380, 382, 384, 393, 386, 399, 423, 425, 427,
433, 429, 435, 439, 440, 451, 465, 469, 476, 470,
477, 478, 494, 483, 502, 510, 520, 192, 237, 245,
0, 184, 209, 231, 660, 1864, 647, 1864, 173, 238,
650, 233, 129, 115, 303, 0, 613, 597, 599, 600,
511, 609, 0, 526, 1864, 532, 277, 603, 599, 1864,
537, 538, 542, 544, 548, 550, 556, 569, 574, 580,
581, 582, 590, 591, 596, 606, 615, 617, 624, 628,
630, 634, 636, 645, 652, 658, 664, 671, 677, 682,
686, 688, 690, 692, 701, 714, 716, 718, 722, 727,
729, 731, 733, 759, 761, 763, 765, 767, 772, 776,
780, 791, 797, 802, 392, 616, 610, 375, 605, 1864,
316, 188, 227, 240, 571, 555, 573, 545, 807, 824,
547, 0, 813, 1864, 818, 828, 832, 837, 839, 843,
845, 849, 850, 861, 876, 880, 882, 886, 888, 892,
893, 894, 901, 907, 919, 925, 926, 931, 932, 937,
936, 941, 947, 963, 972, 974, 978, 980, 982, 984,
988, 989, 990, 1006, 1015, 1020, 1021, 1027, 1033, 1031,
1039, 1052, 1864, 308, 566, 560, 342, 400, 66, 311,
519, 489, 484, 480, 1061, 0, 1066, 1070, 1076, 1077,
1078, 1083, 1087, 1092, 1105, 1113, 1114, 1120, 1118, 1127,
1129, 1135, 1148, 1154, 1159, 1160, 1161, 1165, 1173, 1191,
1192, 1199, 1198, 1200, 1204, 1209, 1216, 1228, 1230, 1238,
1240, 1242, 1244, 318, 327, 369, 325, 382, 480, 453,
453, 447, 1246, 1252, 1259, 1271, 1278, 1283, 1284, 1292,
1285, 1293, 1299, 1300, 1314, 1321, 1325, 1326, 0, 1333,
1331, 1335, 1340, 1352, 1357, 1359, 1361, 1365, 1374, 1378,
1387, 1389, 1391, 1393, 1864, 487, 481, 411, 546, 356,
436, 432, 1864, 411, 438, 1400, 1399, 1404, 1406, 1408,
1417, 1421, 1425, 1430, 1432, 1449, 1442, 1451, 1456, 1457,
1458, 1463, 1468, 1470, 1482, 1487, 0, 1489, 439, 518,
1864, 498, 428, 375, 412, 373, 1864, 1496, 1494, 1498,
1503, 1508, 1529, 1530, 1534, 1536, 0, 1542, 1543, 1544,
1548, 1561, 551, 337, 635, 1864, 275, 1864, 282, 1572,
1574, 1576, 1582, 1578, 1583, 1587, 0, 1591, 1593, 558,
1864, 248, 219, 1864, 0, 1600, 1609, 1615, 124, 1864,
1864, 1619, 1864, 1621, 1864, 1672, 1685, 1690, 84, 1703,
1708, 1715, 1723, 1727, 1739, 1748, 1761, 1771, 1775, 1783,
1791, 1795, 1803, 1811, 1819, 1827, 1835, 1843, 1851
} ;
static yyconst flex_int16_t yy_def[500] =
{ 0,
475, 1, 475, 475, 475, 475, 475, 476, 477, 478,
479, 480, 475, 475, 475, 475, 481, 475, 475, 482,
475, 475, 483, 483, 483, 483, 483, 475, 484, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
475, 475, 476, 475, 485, 477, 486, 479, 480, 475,
487, 475, 475, 475, 475, 475, 475, 475, 488, 475,
475, 475, 475, 489, 475, 490, 490, 490, 490, 490,
475, 475, 475, 483, 491, 492, 493, 483, 483, 483,
483, 475, 475, 475, 494, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 476, 476, 485,
486, 480, 480, 487, 475, 475, 475, 475, 488, 475,
495, 495, 495, 495, 495, 490, 490, 490, 490, 490,
496, 497, 493, 483, 475, 483, 475, 475, 494, 475,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 475, 475, 475, 475, 495, 475,
495, 495, 495, 495, 490, 490, 490, 490, 496, 498,
497, 499, 483, 475, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 475, 475, 475, 475, 495, 495, 495, 495,
490, 490, 490, 490, 496, 499, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 475, 495, 495, 495, 495, 490, 490,
490, 490, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 492, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 475, 475, 495, 495, 495, 495,
490, 490, 475, 490, 490, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 483, 483, 483, 483,
483, 483, 483, 483, 483, 483, 492, 483, 495, 495,
475, 495, 495, 490, 490, 490, 475, 483, 483, 483,
483, 483, 483, 483, 483, 483, 492, 483, 483, 483,
483, 483, 495, 495, 495, 475, 490, 475, 490, 483,
483, 483, 483, 483, 483, 483, 492, 483, 483, 495,
475, 495, 490, 475, 492, 483, 483, 483, 495, 475,
475, 483, 475, 483, 0, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475
} ;
static yyconst flex_int16_t yy_nxt[1931] =
{ 0,
4, 5, 6, 5, 7, 8, 9, 10, 11, 12,
13, 4, 14, 15, 16, 17, 18, 19, 20, 4,
21, 4, 22, 23, 23, 23, 23, 23, 24, 25,
23, 26, 27, 23, 28, 4, 4, 4, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 23, 23, 45, 46, 47, 48,
23, 49, 23, 50, 23, 4, 51, 51, 51, 51,
51, 51, 54, 60, 63, 63, 67, 64, 65, 66,
70, 72, 71, 74, 81, 82, 230, 75, 68, 85,
92, 85, 86, 85, 86, 58, 86, 60, 54, 61,
73, 85, 55, 92, 86, 90, 93, 347, 85, 77,
88, 86, 87, 145, 87, 63, 87, 78, 85, 79,
89, 86, 143, 61, 87, 94, 80, 91, 55, 85,
85, 87, 86, 86, 85, 230, 85, 86, 94, 86,
148, 87, 85, 85, 473, 86, 86, 85, 144, 230,
86, 96, 87, 87, 233, 98, 139, 87, 99, 87,
51, 51, 51, 102, 148, 87, 87, 103, 106, 100,
87, 85, 232, 85, 86, 101, 86, 85, 97, 104,
86, 110, 107, 148, 105, 108, 140, 85, 85, 109,
86, 86, 85, 60, 87, 86, 87, 54, 167, 85,
87, 85, 86, 70, 86, 71, 113, 148, 230, 111,
87, 87, 112, 115, 168, 87, 114, 116, 143, 61,
85, 117, 87, 86, 87, 85, 121, 55, 86, 119,
122, 118, 85, 85, 123, 86, 86, 120, 85, 471,
143, 86, 139, 87, 61, 131, 85, 230, 87, 86,
139, 298, 227, 230, 150, 87, 87, 135, 136, 132,
230, 87, 137, 124, 228, 152, 144, 125, 470, 87,
126, 127, 55, 153, 128, 154, 85, 129, 167, 86,
140, 228, 155, 130, 133, 299, 231, 84, 85, 134,
84, 86, 85, 165, 168, 86, 300, 85, 85, 87,
86, 86, 464, 85, 85, 164, 86, 86, 166, 85,
85, 87, 86, 86, 85, 87, 85, 86, 463, 86,
87, 87, 344, 230, 294, 85, 87, 87, 86, 385,
171, 230, 87, 87, 386, 85, 230, 87, 86, 87,
85, 85, 234, 86, 86, 230, 85, 230, 87, 86,
173, 85, 174, 172, 86, 177, 348, 461, 87, 175,
176, 178, 230, 87, 87, 180, 297, 85, 179, 87,
86, 389, 85, 183, 87, 86, 230, 182, 181, 184,
387, 85, 85, 186, 86, 86, 185, 295, 295, 230,
87, 296, 345, 187, 85, 87, 85, 86, 85, 86,
85, 86, 230, 86, 87, 87, 188, 85, 225, 191,
86, 189, 192, 85, 423, 449, 86, 87, 228, 87,
230, 87, 388, 87, 190, 390, 193, 194, 196, 200,
87, 230, 448, 447, 197, 228, 87, 85, 201, 85,
86, 85, 86, 85, 86, 195, 86, 85, 446, 85,
86, 198, 86, 85, 85, 199, 86, 86, 427, 230,
87, 346, 87, 426, 87, 85, 87, 420, 86, 203,
87, 205, 87, 393, 425, 424, 87, 87, 443, 85,
207, 202, 86, 85, 85, 204, 86, 86, 87, 206,
85, 85, 85, 86, 86, 86, 394, 85, 209, 208,
86, 230, 87, 386, 210, 395, 87, 87, 85, 392,
215, 86, 212, 87, 87, 87, 85, 216, 230, 86,
87, 391, 419, 352, 85, 240, 221, 86, 86, 211,
351, 87, 213, 217, 85, 214, 218, 86, 230, 87,
85, 219, 350, 86, 220, 222, 85, 87, 87, 86,
445, 85, 85, 243, 86, 86, 85, 87, 85, 86,
444, 86, 85, 87, 85, 86, 421, 86, 223, 87,
85, 230, 349, 86, 87, 87, 296, 224, 230, 87,
245, 87, 296, 85, 242, 87, 86, 87, 85, 422,
304, 86, 246, 87, 85, 85, 85, 86, 86, 86,
248, 469, 247, 249, 85, 85, 87, 86, 86, 460,
85, 87, 250, 86, 303, 251, 302, 87, 87, 87,
85, 301, 253, 86, 252, 230, 294, 87, 87, 85,
293, 85, 86, 87, 86, 257, 254, 170, 85, 244,
255, 86, 85, 87, 85, 86, 242, 86, 85, 256,
85, 86, 87, 86, 87, 230, 238, 237, 259, 85,
236, 87, 86, 235, 258, 87, 85, 87, 260, 86,
230, 87, 85, 87, 226, 86, 225, 462, 85, 265,
263, 86, 87, 261, 170, 85, 262, 264, 86, 87,
160, 85, 159, 158, 86, 87, 85, 266, 157, 86,
85, 87, 85, 86, 85, 86, 85, 86, 87, 86,
150, 147, 270, 267, 87, 85, 268, 146, 86, 87,
269, 59, 53, 87, 271, 87, 83, 87, 85, 87,
85, 86, 85, 86, 274, 86, 85, 62, 87, 86,
272, 85, 273, 85, 86, 85, 86, 85, 86, 52,
86, 87, 475, 87, 475, 87, 475, 276, 475, 87,
275, 278, 277, 475, 87, 475, 87, 475, 87, 475,
87, 475, 280, 85, 281, 85, 86, 85, 86, 85,
86, 85, 86, 475, 86, 475, 85, 475, 279, 86,
85, 282, 475, 86, 85, 475, 87, 86, 87, 475,
87, 475, 87, 475, 87, 85, 475, 475, 86, 87,
286, 85, 475, 87, 86, 283, 85, 87, 284, 86,
475, 240, 285, 475, 86, 288, 287, 85, 87, 289,
86, 475, 85, 475, 87, 86, 290, 239, 240, 87,
239, 86, 85, 292, 87, 86, 85, 291, 475, 86,
87, 85, 475, 85, 86, 87, 86, 85, 475, 85,
86, 87, 86, 85, 85, 87, 86, 86, 475, 87,
307, 309, 475, 475, 87, 85, 87, 475, 86, 475,
87, 308, 87, 475, 475, 475, 87, 87, 313, 315,
85, 311, 314, 86, 85, 310, 85, 86, 87, 86,
85, 312, 85, 86, 475, 86, 85, 85, 85, 86,
86, 86, 475, 87, 475, 85, 475, 87, 86, 87,
475, 85, 475, 87, 86, 87, 475, 319, 475, 87,
87, 87, 318, 85, 317, 316, 86, 475, 87, 85,
85, 475, 86, 86, 87, 85, 85, 320, 86, 86,
85, 85, 475, 86, 86, 85, 87, 475, 86, 475,
321, 85, 87, 87, 86, 475, 475, 475, 87, 87,
475, 475, 475, 87, 87, 322, 475, 85, 87, 323,
86, 475, 324, 326, 87, 325, 85, 327, 85, 86,
328, 86, 85, 475, 85, 86, 85, 86, 85, 86,
87, 86, 85, 85, 85, 86, 86, 86, 475, 87,
475, 87, 475, 330, 475, 87, 329, 87, 475, 87,
85, 87, 475, 86, 475, 87, 87, 87, 475, 85,
331, 334, 86, 475, 85, 85, 332, 86, 86, 475,
475, 85, 333, 87, 86, 85, 475, 85, 86, 335,
86, 475, 87, 85, 475, 475, 86, 87, 87, 475,
475, 475, 475, 337, 87, 336, 85, 475, 87, 86,
87, 475, 338, 475, 340, 240, 87, 475, 86, 339,
85, 475, 341, 86, 85, 475, 475, 86, 475, 87,
85, 85, 85, 86, 86, 86, 475, 85, 87, 342,
86, 85, 475, 87, 86, 343, 85, 87, 353, 86,
475, 354, 475, 87, 87, 87, 475, 475, 475, 85,
87, 356, 86, 355, 87, 475, 357, 85, 85, 87,
86, 86, 85, 475, 85, 86, 475, 86, 475, 358,
475, 85, 87, 85, 86, 475, 86, 475, 359, 85,
87, 87, 86, 475, 475, 87, 362, 87, 475, 364,
475, 360, 85, 363, 87, 86, 87, 475, 85, 475,
361, 86, 87, 85, 85, 85, 86, 369, 86, 85,
475, 475, 86, 475, 475, 87, 365, 85, 475, 475,
86, 87, 366, 475, 475, 475, 87, 87, 87, 475,
371, 475, 87, 370, 367, 85, 85, 368, 86, 86,
87, 475, 85, 85, 85, 86, 86, 86, 85, 475,
475, 86, 372, 85, 373, 475, 86, 475, 87, 87,
85, 475, 475, 86, 374, 87, 87, 87, 475, 475,
475, 87, 85, 377, 85, 86, 87, 86, 379, 375,
376, 475, 85, 87, 85, 86, 85, 86, 85, 86,
85, 86, 378, 86, 475, 87, 85, 87, 475, 86,
475, 475, 475, 85, 380, 87, 86, 87, 475, 87,
475, 87, 381, 87, 475, 85, 475, 382, 86, 87,
475, 397, 85, 396, 383, 86, 87, 85, 85, 85,
86, 86, 86, 384, 475, 475, 85, 85, 87, 86,
86, 398, 475, 85, 85, 87, 86, 86, 475, 475,
87, 87, 87, 475, 475, 399, 475, 400, 85, 87,
87, 86, 402, 475, 401, 85, 87, 87, 86, 85,
85, 475, 86, 86, 475, 85, 404, 85, 86, 85,
86, 87, 86, 475, 85, 475, 403, 86, 87, 475,
475, 405, 87, 87, 406, 475, 85, 407, 87, 86,
87, 85, 87, 85, 86, 85, 86, 87, 86, 85,
475, 411, 86, 408, 475, 409, 475, 413, 85, 87,
410, 86, 85, 412, 87, 417, 87, 475, 87, 475,
414, 85, 87, 85, 86, 85, 86, 85, 86, 475,
86, 87, 415, 85, 85, 87, 86, 86, 85, 475,
85, 86, 85, 86, 87, 86, 87, 475, 87, 475,
87, 85, 416, 475, 86, 85, 87, 87, 86, 85,
475, 87, 86, 87, 85, 87, 85, 86, 475, 86,
475, 418, 428, 431, 87, 475, 85, 429, 87, 437,
432, 430, 87, 85, 475, 85, 86, 87, 86, 87,
85, 85, 85, 86, 86, 86, 475, 85, 475, 87,
86, 433, 85, 434, 85, 86, 87, 86, 87, 475,
436, 475, 435, 87, 87, 87, 85, 475, 439, 86,
87, 85, 475, 85, 86, 87, 86, 87, 85, 438,
85, 86, 85, 86, 475, 86, 475, 85, 475, 87,
86, 475, 85, 475, 87, 86, 87, 475, 475, 475,
442, 87, 440, 87, 475, 87, 475, 451, 475, 441,
87, 450, 475, 85, 85, 87, 86, 86, 85, 453,
85, 86, 475, 86, 475, 452, 85, 85, 85, 86,
457, 86, 85, 475, 475, 86, 87, 87, 475, 475,
475, 87, 454, 87, 475, 85, 475, 455, 86, 87,
87, 87, 475, 475, 475, 87, 85, 458, 85, 86,
85, 465, 85, 86, 456, 86, 85, 85, 87, 86,
86, 85, 475, 475, 86, 85, 459, 85, 86, 87,
86, 87, 475, 87, 85, 87, 475, 86, 475, 87,
87, 466, 475, 85, 87, 467, 86, 475, 87, 85,
87, 475, 86, 85, 468, 85, 86, 87, 86, 475,
475, 475, 475, 475, 475, 475, 87, 475, 475, 475,
475, 475, 87, 475, 475, 475, 87, 475, 87, 475,
475, 475, 475, 475, 475, 475, 475, 475, 472, 475,
475, 474, 53, 475, 475, 53, 53, 53, 53, 53,
53, 53, 53, 53, 53, 56, 475, 56, 56, 56,
56, 56, 56, 56, 56, 56, 56, 56, 57, 475,
475, 57, 57, 59, 475, 475, 59, 59, 59, 59,
59, 59, 59, 59, 59, 59, 69, 475, 475, 69,
76, 475, 475, 76, 475, 475, 76, 84, 475, 84,
475, 84, 84, 475, 84, 95, 475, 475, 95, 138,
475, 475, 138, 138, 138, 138, 138, 138, 138, 138,
138, 138, 141, 475, 475, 475, 141, 475, 475, 141,
141, 142, 475, 475, 142, 142, 142, 142, 142, 142,
142, 142, 142, 142, 149, 149, 475, 475, 475, 149,
475, 475, 149, 151, 475, 475, 151, 156, 475, 475,
475, 156, 475, 475, 156, 161, 475, 161, 475, 161,
161, 475, 161, 162, 475, 475, 162, 163, 475, 475,
475, 163, 475, 475, 163, 169, 475, 475, 475, 169,
475, 169, 169, 229, 475, 475, 229, 229, 475, 475,
229, 239, 475, 239, 475, 239, 239, 475, 239, 241,
475, 475, 475, 241, 241, 475, 241, 305, 475, 305,
475, 305, 305, 475, 305, 306, 475, 475, 475, 306,
475, 475, 306, 3, 475, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475, 475
} ;
static yyconst flex_int16_t yy_chk[1931] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 5, 5, 5, 6,
6, 6, 8, 12, 14, 15, 16, 14, 15, 15,
18, 19, 18, 20, 21, 21, 299, 20, 16, 23,
28, 24, 23, 26, 24, 479, 26, 59, 53, 12,
19, 25, 8, 92, 25, 26, 28, 299, 30, 20,
24, 30, 23, 63, 24, 63, 26, 20, 27, 20,
25, 27, 61, 59, 25, 28, 20, 27, 53, 31,
32, 30, 31, 32, 33, 154, 34, 33, 92, 34,
69, 27, 37, 35, 469, 37, 35, 36, 61, 153,
36, 30, 31, 32, 154, 32, 55, 33, 32, 34,
51, 51, 51, 33, 69, 37, 35, 33, 35, 32,
36, 38, 153, 39, 38, 32, 39, 40, 31, 33,
40, 37, 35, 149, 34, 35, 55, 41, 42, 36,
41, 42, 43, 142, 38, 43, 39, 138, 93, 44,
40, 45, 44, 71, 45, 71, 40, 149, 232, 38,
41, 42, 39, 42, 93, 43, 41, 42, 143, 142,
47, 43, 44, 47, 45, 49, 45, 138, 49, 44,
45, 43, 84, 50, 45, 84, 50, 44, 46, 463,
144, 46, 139, 47, 143, 47, 48, 233, 49, 48,
140, 232, 150, 152, 150, 84, 50, 49, 49, 47,
234, 46, 50, 46, 150, 74, 144, 46, 462, 48,
46, 46, 139, 74, 46, 74, 88, 46, 167, 88,
140, 150, 74, 46, 48, 233, 152, 85, 85, 48,
85, 85, 89, 90, 167, 89, 234, 90, 91, 88,
90, 91, 449, 96, 97, 89, 96, 97, 91, 98,
99, 85, 98, 99, 100, 89, 101, 100, 447, 101,
90, 91, 294, 155, 294, 102, 96, 97, 102, 344,
96, 300, 98, 99, 344, 103, 231, 100, 103, 101,
104, 106, 155, 104, 106, 347, 105, 345, 102, 105,
100, 107, 100, 98, 107, 102, 300, 444, 103, 100,
101, 102, 297, 104, 106, 103, 231, 108, 102, 105,
108, 347, 109, 105, 107, 109, 390, 104, 103, 105,
345, 110, 111, 106, 110, 111, 105, 228, 228, 346,
108, 228, 297, 107, 112, 109, 113, 112, 114, 113,
116, 114, 348, 116, 110, 111, 108, 115, 225, 111,
115, 109, 111, 117, 390, 426, 117, 112, 225, 113,
298, 114, 346, 116, 110, 348, 111, 112, 114, 116,
115, 388, 425, 424, 115, 225, 117, 118, 117, 119,
118, 120, 119, 122, 120, 113, 122, 121, 423, 123,
121, 115, 123, 124, 125, 115, 124, 125, 395, 419,
118, 298, 119, 394, 120, 126, 122, 388, 126, 119,
121, 122, 123, 351, 392, 391, 124, 125, 419, 127,
123, 118, 127, 128, 130, 121, 128, 130, 126, 122,
129, 131, 132, 129, 131, 132, 351, 134, 125, 124,
134, 387, 127, 386, 126, 352, 128, 130, 133, 350,
130, 133, 128, 129, 131, 132, 135, 131, 422, 135,
134, 349, 387, 304, 136, 161, 134, 136, 161, 127,
303, 133, 129, 131, 137, 129, 133, 137, 420, 135,
164, 133, 302, 164, 133, 135, 166, 136, 161, 166,
422, 171, 172, 164, 171, 172, 173, 137, 174, 173,
420, 174, 175, 164, 176, 175, 389, 176, 136, 166,
177, 443, 301, 177, 171, 172, 296, 137, 460, 173,
171, 174, 295, 178, 241, 175, 178, 176, 179, 389,
238, 179, 173, 177, 180, 181, 182, 180, 181, 182,
175, 460, 174, 177, 183, 184, 178, 183, 184, 443,
185, 179, 178, 185, 237, 179, 236, 180, 181, 182,
186, 235, 181, 186, 180, 229, 227, 183, 184, 187,
226, 188, 187, 185, 188, 185, 182, 169, 189, 168,
183, 189, 190, 186, 191, 190, 162, 191, 192, 184,
193, 192, 187, 193, 188, 445, 160, 159, 187, 194,
158, 189, 194, 157, 186, 190, 195, 191, 188, 195,
151, 192, 196, 193, 147, 196, 145, 445, 197, 193,
191, 197, 194, 189, 95, 198, 190, 192, 198, 195,
80, 199, 79, 78, 199, 196, 200, 194, 77, 200,
201, 197, 202, 201, 203, 202, 204, 203, 198, 204,
70, 68, 198, 195, 199, 205, 196, 67, 205, 200,
197, 60, 54, 201, 199, 202, 22, 203, 206, 204,
207, 206, 208, 207, 204, 208, 209, 13, 205, 209,
200, 210, 201, 211, 210, 212, 211, 213, 212, 7,
213, 206, 3, 207, 0, 208, 0, 206, 0, 209,
205, 208, 207, 0, 210, 0, 211, 0, 212, 0,
213, 0, 211, 214, 212, 215, 214, 216, 215, 217,
216, 218, 217, 0, 218, 0, 219, 0, 210, 219,
220, 213, 0, 220, 221, 0, 214, 221, 215, 0,
216, 0, 217, 0, 218, 222, 0, 0, 222, 219,
217, 223, 0, 220, 223, 214, 224, 221, 215, 224,
0, 239, 216, 0, 239, 219, 218, 243, 222, 220,
243, 0, 245, 0, 223, 245, 221, 240, 240, 224,
240, 240, 246, 223, 239, 246, 247, 222, 0, 247,
243, 248, 0, 249, 248, 245, 249, 250, 0, 251,
250, 240, 251, 252, 253, 246, 252, 253, 0, 247,
245, 247, 0, 0, 248, 254, 249, 0, 254, 0,
250, 246, 251, 0, 0, 0, 252, 253, 251, 253,
255, 249, 252, 255, 256, 248, 257, 256, 254, 257,
258, 250, 259, 258, 0, 259, 260, 261, 262, 260,
261, 262, 0, 255, 0, 263, 0, 256, 263, 257,
0, 264, 0, 258, 264, 259, 0, 259, 0, 260,
261, 262, 258, 265, 257, 255, 265, 0, 263, 266,
267, 0, 266, 267, 264, 268, 269, 261, 268, 269,
271, 270, 0, 271, 270, 272, 265, 0, 272, 0,
263, 273, 266, 267, 273, 0, 0, 0, 268, 269,
0, 0, 0, 271, 270, 265, 0, 274, 272, 267,
274, 0, 268, 270, 273, 269, 275, 271, 276, 275,
273, 276, 277, 0, 278, 277, 279, 278, 280, 279,
274, 280, 281, 282, 283, 281, 282, 283, 0, 275,
0, 276, 0, 275, 0, 277, 274, 278, 0, 279,
284, 280, 0, 284, 0, 281, 282, 283, 0, 285,
276, 283, 285, 0, 286, 287, 277, 286, 287, 0,
0, 288, 281, 284, 288, 290, 0, 289, 290, 284,
289, 0, 285, 291, 0, 0, 291, 286, 287, 0,
0, 0, 0, 286, 288, 285, 292, 0, 290, 292,
289, 0, 287, 0, 289, 305, 291, 0, 305, 288,
307, 0, 291, 307, 308, 0, 0, 308, 0, 292,
309, 310, 311, 309, 310, 311, 0, 312, 305, 292,
312, 313, 0, 307, 313, 292, 314, 308, 307, 314,
0, 308, 0, 309, 310, 311, 0, 0, 0, 315,
312, 311, 315, 309, 313, 0, 312, 316, 317, 314,
316, 317, 319, 0, 318, 319, 0, 318, 0, 313,
0, 320, 315, 321, 320, 0, 321, 0, 314, 322,
316, 317, 322, 0, 0, 319, 317, 318, 0, 319,
0, 315, 323, 318, 320, 323, 321, 0, 324, 0,
316, 324, 322, 325, 326, 327, 325, 326, 327, 328,
0, 0, 328, 0, 0, 323, 321, 329, 0, 0,
329, 324, 322, 0, 0, 0, 325, 326, 327, 0,
327, 0, 328, 326, 323, 330, 331, 324, 330, 331,
329, 0, 333, 332, 334, 333, 332, 334, 335, 0,
0, 335, 328, 336, 329, 0, 336, 0, 330, 331,
337, 0, 0, 337, 330, 333, 332, 334, 0, 0,
0, 335, 338, 334, 339, 338, 336, 339, 336, 331,
332, 0, 340, 337, 341, 340, 342, 341, 343, 342,
353, 343, 335, 353, 0, 338, 354, 339, 0, 354,
0, 0, 0, 355, 337, 340, 355, 341, 0, 342,
0, 343, 338, 353, 0, 356, 0, 340, 356, 354,
0, 354, 357, 353, 342, 357, 355, 358, 359, 361,
358, 359, 361, 343, 0, 0, 360, 362, 356, 360,
362, 355, 0, 363, 364, 357, 363, 364, 0, 0,
358, 359, 361, 0, 0, 358, 0, 359, 365, 360,
362, 365, 361, 0, 360, 366, 363, 364, 366, 367,
368, 0, 367, 368, 0, 371, 364, 370, 371, 372,
370, 365, 372, 0, 373, 0, 363, 373, 366, 0,
0, 365, 367, 368, 366, 0, 374, 367, 371, 374,
370, 375, 372, 376, 375, 377, 376, 373, 377, 378,
0, 371, 378, 368, 0, 370, 0, 373, 379, 374,
370, 379, 380, 372, 375, 380, 376, 0, 377, 0,
375, 381, 378, 382, 381, 383, 382, 384, 383, 0,
384, 379, 376, 397, 396, 380, 397, 396, 398, 0,
399, 398, 400, 399, 381, 400, 382, 0, 383, 0,
384, 401, 379, 0, 401, 402, 397, 396, 402, 403,
0, 398, 403, 399, 404, 400, 405, 404, 0, 405,
0, 384, 396, 399, 401, 0, 407, 397, 402, 407,
400, 398, 403, 406, 0, 408, 406, 404, 408, 405,
409, 410, 411, 409, 410, 411, 0, 412, 0, 407,
412, 402, 413, 403, 414, 413, 406, 414, 408, 0,
406, 0, 405, 409, 410, 411, 415, 0, 409, 415,
412, 416, 0, 418, 416, 413, 418, 414, 429, 408,
428, 429, 430, 428, 0, 430, 0, 431, 0, 415,
431, 0, 432, 0, 416, 432, 418, 0, 0, 0,
416, 429, 413, 428, 0, 430, 0, 429, 0, 415,
431, 428, 0, 433, 434, 432, 433, 434, 435, 432,
436, 435, 0, 436, 0, 431, 438, 439, 440, 438,
439, 440, 441, 0, 0, 441, 433, 434, 0, 0,
0, 435, 433, 436, 0, 442, 0, 435, 442, 438,
439, 440, 0, 0, 0, 441, 450, 440, 451, 450,
452, 451, 454, 452, 436, 454, 453, 455, 442, 453,
455, 456, 0, 0, 456, 458, 441, 459, 458, 450,
459, 451, 0, 452, 466, 454, 0, 466, 0, 453,
455, 452, 0, 467, 456, 453, 467, 0, 458, 468,
459, 0, 468, 472, 456, 474, 472, 466, 474, 0,
0, 0, 0, 0, 0, 0, 467, 0, 0, 0,
0, 0, 468, 0, 0, 0, 472, 0, 474, 0,
0, 0, 0, 0, 0, 0, 0, 0, 468, 0,
0, 472, 476, 0, 0, 476, 476, 476, 476, 476,
476, 476, 476, 476, 476, 477, 0, 477, 477, 477,
477, 477, 477, 477, 477, 477, 477, 477, 478, 0,
0, 478, 478, 480, 0, 0, 480, 480, 480, 480,
480, 480, 480, 480, 480, 480, 481, 0, 0, 481,
482, 0, 0, 482, 0, 0, 482, 483, 0, 483,
0, 483, 483, 0, 483, 484, 0, 0, 484, 485,
0, 0, 485, 485, 485, 485, 485, 485, 485, 485,
485, 485, 486, 0, 0, 0, 486, 0, 0, 486,
486, 487, 0, 0, 487, 487, 487, 487, 487, 487,
487, 487, 487, 487, 488, 488, 0, 0, 0, 488,
0, 0, 488, 489, 0, 0, 489, 490, 0, 0,
0, 490, 0, 0, 490, 491, 0, 491, 0, 491,
491, 0, 491, 492, 0, 0, 492, 493, 0, 0,
0, 493, 0, 0, 493, 494, 0, 0, 0, 494,
0, 494, 494, 495, 0, 0, 495, 495, 0, 0,
495, 496, 0, 496, 0, 496, 496, 0, 496, 497,
0, 0, 0, 497, 497, 0, 497, 498, 0, 498,
0, 498, 498, 0, 498, 499, 0, 0, 0, 499,
0, 0, 499, 475, 475, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475, 475,
475, 475, 475, 475, 475, 475, 475, 475, 475, 475
} ;
extern int yy_flex_debug;
int yy_flex_debug = 0;
static yy_state_type *yy_state_buf=0, *yy_state_ptr=0;
static char *yy_full_match;
static int yy_lp;
#define REJECT \
{ \
*yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ \
yy_cp = (yy_full_match); /* restore poss. backed-over text */ \
++(yy_lp); \
goto find_rule; \
}
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
char *yytext;
#line 1 "parser.l"
#line 2 "parser.l"
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
#include "../cl/globals.h"
#include "../cl/macros.h"
#include "cqp.h"
#include "corpmanag.h"
#include "eval.h"
#include "tree.h"
#include "options.h"
#include "output.h"
#include "symtab.h"
#include "ranges.h"
#include "macro.h"
#include "targets.h"
#include "parser.tab.h"
/* By default, flex uses block-reads rather than character-reads from the */
/* input stream. Since there are at least two different input streams in */
/* this program (the stream which flex uses and the input stream of cmds) */
/* you have to redefine YY_INPUT as follows: */
#undef YY_INPUT
/* replace YY_INPUT macro with call to yy_input_char() <macro.c> for
macro expansion -- this version suffers from the 0xff2k-Bug anyway */
/*
#define YY_INPUT(buf,result,max_size) { \
int c = (cqp_input_string ? cqp_input_string[cqp_input_string_position++] \
: getc(yyin)); \
result = ((c == EOF) || (c == 0)) ? 0 : (buf[0] = c, 1); }
*/
#define YY_INPUT(buf, result, max_size) { \
int c = yy_input_char(); \
result = ((c == EOF) || (c == 0)) ? 0 : (buf[0] = c, 1); \
}
/* new_string = strip_quotes(string); */
/* Removes single or double quotes around string as well as doubling escapes inside (e.g. 'it''s' => it's),
while keeping track of backslash escapes. */
char *
strip_quotes(char *s) {
char *t;
int i, k, len;
char delim = s[0];
len = strlen(s);
assert(len >= 2 && (delim == '"' || delim == '\'') && s[len-1] == delim); /* should be guaranteed by grammar rule */
t = (char *) cl_malloc(len - 1); /* at most l-2 characters + NUL */
i = 1; k = 0;
while (i < len-1) {
char c = s[i];
t[k++] = s[i++]; /* copy this character, then check what to do with next character */
if (c == '\\') {
assert(i < len-1); /* no stranded backslash at end of string (should be guaranteed by grammar rule) */
t[k++] = s[i++]; /* copy backslash and following character */
}
else if (c == delim && s[i] == delim) {
i++; /* delete doubled delimiter */
}
}
t[k] = 0; /* NUL-terminate new string */
return t;
}
/* with this option set, we shouldn't need libfl.a */
/* old identifiers:
id {letter}{xletter}*(:{xletter}+)?(^{xletter}+)?
id {idletter}{xidletter}*(:{xidletter}+)?(^{xidletter}+)?
*/
/* ID (corpus name, attribute name, macro name, etc.) */
/* specifier for named query result, with mother name and/or implicit expansion */
/* -- no idea why accents should be matched explicitly here, so just remove the rule */
/* accents \\\"|\\,|\\\'|\\`|\\\^ */
/* -- strings are enclosed in single or double quotes, which can be escaped inside by doubling (automatically removed) */
/* -- a backslash escapes any following character (except newline), but is passed through together with the character */
#line 1210 "lex.yy.c"
#define INITIAL 0
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
static int yy_init_globals (void );
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy (void );
int yyget_debug (void );
void yyset_debug (int debug_flag );
YY_EXTRA_TYPE yyget_extra (void );
void yyset_extra (YY_EXTRA_TYPE user_defined );
FILE *yyget_in (void );
void yyset_in (FILE * in_str );
FILE *yyget_out (void );
void yyset_out (FILE * out_str );
yy_size_t yyget_leng (void );
char *yyget_text (void );
int yyget_lineno (void );
void yyset_lineno (int line_number );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap (void );
#else
extern int yywrap (void );
#endif
#endif
/* static void yyunput (int c,char *buf_ptr ); */
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int );
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * );
#endif
#ifndef YY_NO_INPUT
/*
#ifdef __cplusplus
static int yyinput (void );
#else
static int input (void );
#endif
*/
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 8192
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO fwrite( yytext, yyleng, 1, yyout )
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
yy_size_t n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex (void);
#define YY_DECL int yylex (void)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK break;
#endif
#define YY_RULE_SETUP \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
register yy_state_type yy_current_state;
register char *yy_cp, *yy_bp;
register int yy_act;
#line 123 "parser.l"
#line 1394 "lex.yy.c"
if ( !(yy_init) )
{
(yy_init) = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
/* Create the reject buffer large enough to save one state per allowed character. */
if ( ! (yy_state_buf) )
(yy_state_buf) = (yy_state_type *)yyalloc(YY_STATE_BUF_SIZE );
if ( ! (yy_state_buf) )
YY_FATAL_ERROR( "out of dynamic memory in yylex()" );
if ( ! (yy_start) )
(yy_start) = 1; /* first start state */
if ( ! yyin )
yyin = stdin;
if ( ! yyout )
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_load_buffer_state( );
}
while ( 1 ) /* loops until end-of-file is reached */
{
yy_cp = (yy_c_buf_p);
/* Support of yytext. */
*yy_cp = (yy_hold_char);
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = (yy_start);
(yy_state_ptr) = (yy_state_buf);
*(yy_state_ptr)++ = yy_current_state;
yy_match:
do
{
register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 476 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
*(yy_state_ptr)++ = yy_current_state;
++yy_cp;
}
while ( yy_base[yy_current_state] != 1864 );
yy_find_action:
yy_current_state = *--(yy_state_ptr);
(yy_lp) = yy_accept[yy_current_state];
goto find_rule; /* Shut up GCC warning -Wall */
find_rule: /* we branch to this label when backing up */
for ( ; ; ) /* until we find what rule we matched */
{
if ( (yy_lp) && (yy_lp) < yy_accept[yy_current_state + 1] )
{
yy_act = yy_acclist[(yy_lp)];
{
(yy_full_match) = yy_cp;
break;
}
}
--yy_cp;
yy_current_state = *--(yy_state_ptr);
(yy_lp) = yy_accept[yy_current_state];
}
YY_DO_BEFORE_ACTION;
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case YY_STATE_EOF(INITIAL):
#line 124 "parser.l"
{ return(0); }
YY_BREAK
case 1:
YY_RULE_SETUP
#line 125 "parser.l"
{ return(EXIT_SYM); }
YY_BREAK
case 2:
YY_RULE_SETUP
#line 126 "parser.l"
{ return(CAT_SYM); }
YY_BREAK
case 3:
YY_RULE_SETUP
#line 127 "parser.l"
{ return(DEFINE_SYM); }
YY_BREAK
case 4:
YY_RULE_SETUP
#line 128 "parser.l"
{ return(DIFF_SYM); }
YY_BREAK
case 5:
YY_RULE_SETUP
#line 129 "parser.l"
{ return(DISCARD_SYM); }
YY_BREAK
case 6:
YY_RULE_SETUP
#line 130 "parser.l"
{ return(INTER_SYM); }
YY_BREAK
case 7:
YY_RULE_SETUP
#line 131 "parser.l"
{ return(JOIN_SYM); }
YY_BREAK
case 8:
YY_RULE_SETUP
#line 132 "parser.l"
{ return(SUBSET_SYM); }
YY_BREAK
case 9:
YY_RULE_SETUP
#line 133 "parser.l"
{ return(LEFT_SYM); }
YY_BREAK
case 10:
YY_RULE_SETUP
#line 134 "parser.l"
{ return(RIGHT_SYM); }
YY_BREAK
case 11:
YY_RULE_SETUP
#line 135 "parser.l"
{ return(SAVE_SYM); }
YY_BREAK
case 12:
YY_RULE_SETUP
#line 136 "parser.l"
{ return(SHOW_SYM); }
YY_BREAK
case 13:
YY_RULE_SETUP
#line 137 "parser.l"
{ return(CD_SYM); } /* show context descriptor */
YY_BREAK
case 14:
YY_RULE_SETUP
#line 138 "parser.l"
{ return(GROUP_SYM); }
YY_BREAK
case 15:
YY_RULE_SETUP
#line 139 "parser.l"
{ return(WHERE_SYM); }
YY_BREAK
case 16:
YY_RULE_SETUP
#line 141 "parser.l"
{ return(WITHIN_SYM); }
YY_BREAK
case 17:
YY_RULE_SETUP
#line 142 "parser.l"
{ return(WITH_SYM); }
YY_BREAK
case 18:
YY_RULE_SETUP
#line 143 "parser.l"
{ return(WITHOUT_SYM); }
YY_BREAK
case 19:
YY_RULE_SETUP
#line 144 "parser.l"
{ return(DELETE_SYM); }
YY_BREAK
case 20:
YY_RULE_SETUP
#line 145 "parser.l"
{ return(EXPAND_SYM); }
YY_BREAK
case 21:
YY_RULE_SETUP
#line 146 "parser.l"
{ return(TO_SYM); }
YY_BREAK
case 22:
YY_RULE_SETUP
#line 147 "parser.l"
{ return(SET_SYM); }
YY_BREAK
case 23:
YY_RULE_SETUP
#line 149 "parser.l"
{ return(EXEC_SYM); }
YY_BREAK
case 24:
YY_RULE_SETUP
#line 150 "parser.l"
{ return(CUT_SYM); }
YY_BREAK
case 25:
YY_RULE_SETUP
#line 152 "parser.l"
{ return(INFO_SYM); }
YY_BREAK
case 26:
YY_RULE_SETUP
#line 154 "parser.l"
{ return(MEET_SYM); }
YY_BREAK
case 27:
YY_RULE_SETUP
#line 155 "parser.l"
{ return(UNION_SYM); }
YY_BREAK
case 28:
YY_RULE_SETUP
#line 156 "parser.l"
{ return(MU_SYM); }
YY_BREAK
case 29:
YY_RULE_SETUP
#line 157 "parser.l"
{ return(TAB_SYM); }
YY_BREAK
case 30:
YY_RULE_SETUP
#line 159 "parser.l"
{ return(SORT_SYM); }
YY_BREAK
case 31:
YY_RULE_SETUP
#line 160 "parser.l"
{ return(COUNT_SYM); }
YY_BREAK
case 32:
YY_RULE_SETUP
#line 161 "parser.l"
{ return(BY_SYM); }
YY_BREAK
case 33:
YY_RULE_SETUP
#line 162 "parser.l"
{ return(FOREACH_SYM); }
YY_BREAK
case 34:
YY_RULE_SETUP
#line 163 "parser.l"
{ return(ON_SYM); }
YY_BREAK
case 35:
YY_RULE_SETUP
#line 164 "parser.l"
{ return(YES_SYM); }
YY_BREAK
case 36:
YY_RULE_SETUP
#line 165 "parser.l"
{ return(OFF_SYM); }
YY_BREAK
case 37:
YY_RULE_SETUP
#line 166 "parser.l"
{ return(NO_SYM); }
YY_BREAK
case 38:
YY_RULE_SETUP
#line 167 "parser.l"
{ return(ASC_SYM); }
YY_BREAK
case 39:
YY_RULE_SETUP
#line 168 "parser.l"
{ return(DESC_SYM); }
YY_BREAK
case 40:
YY_RULE_SETUP
#line 169 "parser.l"
{ return(REVERSE_SYM); }
YY_BREAK
case 41:
YY_RULE_SETUP
#line 170 "parser.l"
{ return(SLEEP_SYM); }
YY_BREAK
case 42:
YY_RULE_SETUP
#line 172 "parser.l"
{ return(REDUCE_SYM); }
YY_BREAK
case 43:
YY_RULE_SETUP
#line 173 "parser.l"
{ return(MAXIMAL_SYM); } /* "reduce to maximal" */
YY_BREAK
case 44:
YY_RULE_SETUP
#line 175 "parser.l"
{ return(SIZE_SYM); }
YY_BREAK
case 45:
YY_RULE_SETUP
#line 176 "parser.l"
{ return(DUMP_SYM); }
YY_BREAK
case 46:
YY_RULE_SETUP
#line 177 "parser.l"
{ return(UNDUMP_SYM); }
YY_BREAK
case 47:
YY_RULE_SETUP
#line 178 "parser.l"
{ return(TABULATE_SYM); }
YY_BREAK
case 48:
YY_RULE_SETUP
#line 180 "parser.l"
{ return(NOT_SYM); }
YY_BREAK
case 49:
YY_RULE_SETUP
#line 181 "parser.l"
{ return(CONTAINS_SYM); }
YY_BREAK
case 50:
YY_RULE_SETUP
#line 182 "parser.l"
{ return(MATCHES_SYM); }
YY_BREAK
case 51:
YY_RULE_SETUP
#line 184 "parser.l"
{ return(UNLOCK_SYM); }
YY_BREAK
case 52:
YY_RULE_SETUP
#line 186 "parser.l"
{ return(USER_SYM); } /* for CQPserver user authentication file */
YY_BREAK
case 53:
YY_RULE_SETUP
#line 187 "parser.l"
{ return(HOST_SYM); }
YY_BREAK
case 54:
YY_RULE_SETUP
#line 189 "parser.l"
{ return(MACRO_SYM); }
YY_BREAK
case 55:
YY_RULE_SETUP
#line 191 "parser.l"
{ return(RANDOMIZE_SYM); }
YY_BREAK
case 56:
YY_RULE_SETUP
#line 193 "parser.l"
{ return(FROM_SYM); }
YY_BREAK
case 57:
YY_RULE_SETUP
#line 195 "parser.l"
{ return(INCLUSIVE_SYM); }
YY_BREAK
case 58:
YY_RULE_SETUP
#line 196 "parser.l"
{ return(EXCLUSIVE_SYM); }
YY_BREAK
case 59:
YY_RULE_SETUP
#line 198 "parser.l"
{ return(NULL_SYM); }
YY_BREAK
case 60:
YY_RULE_SETUP
#line 200 "parser.l"
{ yylval.field = MatchField; return(FIELD); } /* the fields (or 'anchor points') of a subcorpus */
YY_BREAK
case 61:
YY_RULE_SETUP
#line 201 "parser.l"
{ yylval.field = MatchEndField; return(FIELD); }
YY_BREAK
case 62:
YY_RULE_SETUP
#line 202 "parser.l"
{ yylval.field = TargetField; return(FIELD); }
YY_BREAK
case 63:
YY_RULE_SETUP
#line 203 "parser.l"
{ yylval.field = TargetField; return(FIELD); }
YY_BREAK
case 64:
YY_RULE_SETUP
#line 204 "parser.l"
{ yylval.field = KeywordField; return(FIELD); }
YY_BREAK
case 65:
YY_RULE_SETUP
#line 206 "parser.l"
{ yylval.field = MatchField; return(FIELDLABEL); } /* labels referring to fields (in "subset" command, probably in future as well in "sort", "fdist", ...) */
YY_BREAK
case 66:
YY_RULE_SETUP
#line 207 "parser.l"
{ yylval.field = MatchEndField; return(FIELDLABEL); }
YY_BREAK
case 67:
YY_RULE_SETUP
#line 208 "parser.l"
{ yylval.field = TargetField; return(FIELDLABEL); }
YY_BREAK
case 68:
YY_RULE_SETUP
#line 209 "parser.l"
{ yylval.field = TargetField; return(FIELDLABEL); }
YY_BREAK
case 69:
YY_RULE_SETUP
#line 210 "parser.l"
{ yylval.field = KeywordField; return(FIELDLABEL); }
YY_BREAK
case 70:
YY_RULE_SETUP
#line 212 "parser.l"
{ yylval.field = MatchField; return(ANCHORTAG); } /* anchor point (start) tags for subqueries */
YY_BREAK
case 71:
YY_RULE_SETUP
#line 213 "parser.l"
{ yylval.field = MatchEndField; return(ANCHORTAG); }
YY_BREAK
case 72:
YY_RULE_SETUP
#line 214 "parser.l"
{ yylval.field = TargetField; return(ANCHORTAG); }
YY_BREAK
case 73:
YY_RULE_SETUP
#line 215 "parser.l"
{ yylval.field = TargetField; return(ANCHORTAG); }
YY_BREAK
case 74:
YY_RULE_SETUP
#line 216 "parser.l"
{ yylval.field = KeywordField; return(ANCHORTAG); }
YY_BREAK
case 75:
YY_RULE_SETUP
#line 218 "parser.l"
{ yylval.field = MatchEndField; return(ANCHORENDTAG); } /* anchor point (end) tags for subqueries */
YY_BREAK
case 76:
YY_RULE_SETUP
#line 219 "parser.l"
{ yylval.field = MatchEndField; return(ANCHORENDTAG); } /* special feature: </match> marks end of entire match -> </match> == </matchend> */
YY_BREAK
case 77:
YY_RULE_SETUP
#line 220 "parser.l"
{ yylval.field = TargetField; return(ANCHORENDTAG); }
YY_BREAK
case 78:
YY_RULE_SETUP
#line 221 "parser.l"
{ yylval.field = TargetField; return(ANCHORENDTAG); }
YY_BREAK
case 79:
YY_RULE_SETUP
#line 222 "parser.l"
{ yylval.field = KeywordField; return(ANCHORENDTAG); }
YY_BREAK
case 80:
YY_RULE_SETUP
#line 224 "parser.l"
{ yylval.search_strategy = SearchLeftmost; return(SEARCH_STRATEGY); } /* search strategy in "set <field> ..." command */
YY_BREAK
case 81:
YY_RULE_SETUP
#line 225 "parser.l"
{ yylval.search_strategy = SearchRightmost; return(SEARCH_STRATEGY); }
YY_BREAK
case 82:
YY_RULE_SETUP
#line 226 "parser.l"
{ yylval.search_strategy = SearchNearest; return(SEARCH_STRATEGY); }
YY_BREAK
case 83:
YY_RULE_SETUP
#line 227 "parser.l"
{ yylval.search_strategy = SearchFarthest; return(SEARCH_STRATEGY); }
YY_BREAK
case 84:
YY_RULE_SETUP
#line 229 "parser.l"
{ return(RE_PAREN); } /* for [lemma = RE($var)] */
YY_BREAK
case 85:
YY_RULE_SETUP
#line 231 "parser.l"
{ return(EOL_SYM); } /* for child mode (prints special code on separate line) */
YY_BREAK
case 86:
YY_RULE_SETUP
#line 234 "parser.l"
{
yylval.ival = atoi(yytext);
return(INTEGER);
}
YY_BREAK
case 87:
YY_RULE_SETUP
#line 238 "parser.l"
{
yylval.strval = cl_strdup(yytext);
return(IPAddress);
}
YY_BREAK
case 88:
YY_RULE_SETUP
#line 242 "parser.l"
{
yylval.strval = cl_strdup(yytext);
yylval.strval[yyleng-1] = '\0'; /* cut off asterisk */
return(IPSubnet);
}
YY_BREAK
case 89:
YY_RULE_SETUP
#line 247 "parser.l"
{
yylval.fval = atof(yytext);
return(DOUBLEFLOAT);
}
YY_BREAK
case 90:
YY_RULE_SETUP
#line 251 "parser.l"
{
if (!enable_macros) {
REJECT; /* for absolute backward compatibility */
}
else {
/* strdup macro name (stripping the / and ( or [ chars) */
char *macro = cl_strdup(yytext+1);
macro[strlen(macro)-1] = '\0';
if (!expand_macro(macro)) {
cl_free(macro);
return(UNDEFINED_MACRO);
}
else
cl_free(macro);
}
}
YY_BREAK
case 91:
YY_RULE_SETUP
#line 267 "parser.l"
{
yylval.strval = cl_strdup(yytext);
return(QID);
}
YY_BREAK
case 92:
YY_RULE_SETUP
#line 271 "parser.l"
{
yylval.strval = cl_strdup(yytext);
if (yylval.strval[yyleng-1] == ':')
yylval.strval[yyleng-1] = '\0';
return(LABEL);
}
YY_BREAK
case 93:
YY_RULE_SETUP
#line 277 "parser.l"
{ /* allowing @: targets makes distinction between labels & target in macros unnecessary */
return('@');
}
YY_BREAK
case 94:
YY_RULE_SETUP
#line 280 "parser.l"
{
yylval.strval = cl_strdup(yytext);
return(NQRID);
}
YY_BREAK
case 95:
YY_RULE_SETUP
#line 284 "parser.l"
{
/* quoted ID: must still be valid ID but can be a reserved word */
yylval.strval = cl_strdup(yytext + 1); /* strip `...` quotes */
yylval.strval[strlen(yylval.strval) - 1] = '\0';
return(ID);
}
YY_BREAK
case 96:
YY_RULE_SETUP
#line 290 "parser.l"
{
yylval.strval = cl_strdup(yytext);
return(ID);
}
YY_BREAK
case 97:
YY_RULE_SETUP
#line 294 "parser.l"
{
yylval.strval = cl_strdup(yytext + 1);
return(VARIABLE);
}
YY_BREAK
case 98:
YY_RULE_SETUP
#line 298 "parser.l"
{
yylval.strval = cl_strdup(yytext + 1);
return(FLAG);
}
YY_BREAK
case 99:
/* rule 99 can match eol */
YY_RULE_SETUP
#line 302 "parser.l"
;
YY_BREAK
case 100:
YY_RULE_SETUP
#line 303 "parser.l"
; /* single line comment */
YY_BREAK
case 101:
YY_RULE_SETUP
#line 304 "parser.l"
{
/* cut off the leading "/' and the trailing "/' */
yylval.strval = strip_quotes(yytext);
return(STRING);
}
YY_BREAK
case 102:
YY_RULE_SETUP
#line 309 "parser.l"
{
return(MATCHALL);
}
YY_BREAK
case 103:
YY_RULE_SETUP
#line 312 "parser.l"
{ /* closing '>' not included to allow condition in the tag (nyi) */
yylval.strval = cl_strdup(yytext+1);
return(TAGSTART);
}
YY_BREAK
case 104:
YY_RULE_SETUP
#line 317 "parser.l"
{
yylval.strval = cl_strdup(yytext+2);
yylval.strval[yyleng-3] = '\0'; /* chop off trailing '>' */
return(TAGEND);
}
YY_BREAK
case 105:
YY_RULE_SETUP
#line 324 "parser.l"
{ return(LCMATCHALL); } /* lookahead matchall [::] */
YY_BREAK
case 106:
YY_RULE_SETUP
#line 325 "parser.l"
{ return(LCSTART); } /* lookahead constraint pattern [: ... :] */
YY_BREAK
case 107:
YY_RULE_SETUP
#line 326 "parser.l"
{ return(LCEND); }
YY_BREAK
case 108:
YY_RULE_SETUP
#line 327 "parser.l"
{ return(GCDEL); }
YY_BREAK
case 109:
YY_RULE_SETUP
#line 328 "parser.l"
{ return(ELLIPSIS); }
YY_BREAK
case 110:
YY_RULE_SETUP
#line 329 "parser.l"
{ return(ELLIPSIS); }
YY_BREAK
case 111:
YY_RULE_SETUP
#line 330 "parser.l"
{ return(LET); }
YY_BREAK
case 112:
YY_RULE_SETUP
#line 331 "parser.l"
{ return(GET); }
YY_BREAK
case 113:
YY_RULE_SETUP
#line 332 "parser.l"
{ return(NEQ); }
YY_BREAK
case 114:
YY_RULE_SETUP
#line 333 "parser.l"
{ return APPEND; }
YY_BREAK
case 115:
YY_RULE_SETUP
#line 334 "parser.l"
{ return PLUSEQ; }
YY_BREAK
case 116:
YY_RULE_SETUP
#line 335 "parser.l"
{ return MINUSEQ; }
YY_BREAK
case 117:
YY_RULE_SETUP
#line 336 "parser.l"
{ return IMPLIES; }
YY_BREAK
case 118:
YY_RULE_SETUP
#line 337 "parser.l"
{ return EXTENSION; } /* for standard query extensions of the form (?...) */
YY_BREAK
case 119:
YY_RULE_SETUP
#line 338 "parser.l"
{ return ESCAPE_SYM; }
YY_BREAK
case 120:
YY_RULE_SETUP
#line 339 "parser.l"
{ return yytext[0]; }
YY_BREAK
case 121:
YY_RULE_SETUP
#line 341 "parser.l"
ECHO;
YY_BREAK
#line 2167 "lex.yy.c"
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = (yy_hold_char);
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state );
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++(yy_c_buf_p);
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = (yy_c_buf_p);
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_END_OF_FILE:
{
(yy_did_buffer_switch_on_eof) = 0;
if ( yywrap( ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) =
(yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
(yy_c_buf_p) =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (void)
{
register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
register char *source = (yytext_ptr);
register int number_to_move, i;
int ret_val;
if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
else
{
yy_size_t num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
YY_FATAL_ERROR(
"input buffer overflow, can't enlarge buffer because scanner uses REJECT" );
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
(yy_n_chars), num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
if ( (yy_n_chars) == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
yyrestart(yyin );
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
}
(yy_n_chars) += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (void)
{
register yy_state_type yy_current_state;
register char *yy_cp;
yy_current_state = (yy_start);
(yy_state_ptr) = (yy_state_buf);
*(yy_state_ptr)++ = yy_current_state;
for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
{
register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 476 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
*(yy_state_ptr)++ = yy_current_state;
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
{
register int yy_is_jam;
register YY_CHAR yy_c = 1;
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 476 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 475);
if ( ! yy_is_jam )
*(yy_state_ptr)++ = yy_current_state;
return yy_is_jam ? 0 : yy_current_state;
}
/*
static void yyunput (int c, register char * yy_bp )
{
register char *yy_cp;
yy_cp = (yy_c_buf_p);
*yy_cp = (yy_hold_char);
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
register yy_size_t number_to_move = (yy_n_chars) + 2;
register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
register char *source =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
*--dest = *--source;
yy_cp += (int) (dest - source);
yy_bp += (int) (dest - source);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
YY_FATAL_ERROR( "flex scanner push-back overflow" );
}
*--yy_cp = (char) c;
(yytext_ptr) = yy_bp;
(yy_hold_char) = *yy_cp;
(yy_c_buf_p) = yy_cp;
}
*/
/*
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void)
#else
static int input (void)
#endif
{
int c;
*(yy_c_buf_p) = (yy_hold_char);
if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
{
if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
*(yy_c_buf_p) = '\0';
else
yy_size_t offset = (yy_c_buf_p) - (yytext_ptr);
++(yy_c_buf_p);
switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_LAST_MATCH:
yyrestart(yyin );
case EOB_ACT_END_OF_FILE:
{
if ( yywrap( ) )
return 0;
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput();
#else
return input();
#endif
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) = (yytext_ptr) + offset;
break;
}
}
}
c = *(unsigned char *) (yy_c_buf_p);
*(yy_c_buf_p) = '\0';
(yy_hold_char) = *++(yy_c_buf_p);
return c;
}
#endif
*/
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
*
* @note This function does not reset the start condition to @c INITIAL .
*/
void yyrestart (FILE * input_file )
{
if ( ! YY_CURRENT_BUFFER ){
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_init_buffer(YY_CURRENT_BUFFER,input_file );
yy_load_buffer_state( );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
*
*/
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer )
{
/* TODO. We should be able to replace this entire function body
* with
* yypop_buffer_state();
* yypush_buffer_state(new_buffer);
*/
yyensure_buffer_stack ();
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
yy_load_buffer_state( );
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
(yy_did_buffer_switch_on_eof) = 1;
}
static void yy_load_buffer_state (void)
{
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
(yy_hold_char) = *(yy_c_buf_p);
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
*
* @return the allocated buffer state.
*/
YY_BUFFER_STATE yy_create_buffer (FILE * file, int size )
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
yy_init_buffer(b,file );
return b;
}
/** Destroy the buffer.
* @param b a buffer created with yy_create_buffer()
*
*/
void yy_delete_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
yyfree((void *) b->yy_ch_buf );
yyfree((void *) b );
}
#ifndef __cplusplus
extern int isatty (int );
#endif /* __cplusplus */
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a yyrestart() or at EOF.
*/
static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file )
{
int oerrno = errno;
yy_flush_buffer(b );
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then yy_init_buffer was _probably_
* called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
*
*/
void yy_flush_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
yy_load_buffer_state( );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
*
*/
void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
{
if (new_buffer == NULL)
return;
yyensure_buffer_stack();
/* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
(yy_buffer_stack_top)++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from yy_switch_to_buffer. */
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
*
*/
void yypop_buffer_state (void)
{
if (!YY_CURRENT_BUFFER)
return;
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
if ((yy_buffer_stack_top) > 0)
--(yy_buffer_stack_top);
if (YY_CURRENT_BUFFER) {
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void yyensure_buffer_stack (void)
{
yy_size_t num_to_alloc;
if (!(yy_buffer_stack)) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1;
(yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
(yy_buffer_stack_top) = 0;
return;
}
if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
/* Increase the buffer to prepare for a possible push. */
int grow_size = 8 /* arbitrary grow size */;
num_to_alloc = (yy_buffer_stack_max) + grow_size;
(yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
((yy_buffer_stack),
num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size )
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer(b );
return b;
}
/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
*
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* yy_scan_bytes() instead.
*/
YY_BUFFER_STATE yy_scan_string (yyconst char * yystr )
{
return yy_scan_bytes(yystr,strlen(yystr) );
}
/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param bytes the byte buffer to scan
* @param len the number of bytes in the buffer pointed to by @a bytes.
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len )
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n, i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = _yybytes_len + 2;
buf = (char *) yyalloc(n );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer(buf,n );
if ( ! b )
YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yy_fatal_error (yyconst char* msg )
{
(void) Rprintf("%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
yytext[yyleng] = (yy_hold_char); \
(yy_c_buf_p) = yytext + yyless_macro_arg; \
(yy_hold_char) = *(yy_c_buf_p); \
*(yy_c_buf_p) = '\0'; \
yyleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the current line number.
*
*/
int yyget_lineno (void)
{
return yylineno;
}
/** Get the input stream.
*
*/
FILE *yyget_in (void)
{
return yyin;
}
/** Get the output stream.
*
*/
FILE *yyget_out (void)
{
return yyout;
}
/** Get the length of the current token.
*
*/
yy_size_t yyget_leng (void)
{
return yyleng;
}
/** Get the current token.
*
*/
char *yyget_text (void)
{
return yytext;
}
/** Set the current line number.
* @param line_number
*
*/
void yyset_lineno (int line_number )
{
yylineno = line_number;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param in_str A readable stream.
*
* @see yy_switch_to_buffer
*/
void yyset_in (FILE * in_str )
{
yyin = in_str ;
}
void yyset_out (FILE * out_str )
{
yyout = out_str ;
}
int yyget_debug (void)
{
return yy_flex_debug;
}
void yyset_debug (int bdebug )
{
yy_flex_debug = bdebug ;
}
static int yy_init_globals (void)
{
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from yylex_destroy(), so don't allocate here.
*/
(yy_buffer_stack) = 0;
(yy_buffer_stack_top) = 0;
(yy_buffer_stack_max) = 0;
(yy_c_buf_p) = (char *) 0;
(yy_init) = 0;
(yy_start) = 0;
(yy_state_buf) = 0;
(yy_state_ptr) = 0;
(yy_full_match) = 0;
(yy_lp) = 0;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = (FILE *) 0;
yyout = (FILE *) 0;
#endif
/* For future reference: Set errno on error, since we are called by
* yylex_init()
*/
return 0;
}
/* yylex_destroy is for both reentrant and non-reentrant scanners. */
int yylex_destroy (void)
{
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
yypop_buffer_state();
}
/* Destroy the stack itself. */
yyfree((yy_buffer_stack) );
(yy_buffer_stack) = NULL;
yyfree ( (yy_state_buf) );
(yy_state_buf) = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* yylex() is called, initialization will occur. */
yy_init_globals( );
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
{
register int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s )
{
register int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *yyalloc (yy_size_t size )
{
return (void *) malloc( size );
}
void *yyrealloc (void * ptr, yy_size_t size )
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
void yyfree (void * ptr )
{
free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
#line 341 "parser.l"
|
myoKun345/RcppCWB
|
src/cwb/cl/attributes.c
|
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
void Rprintf(const char *, ...);
#include <ctype.h>
#include <sys/types.h>
#include "globals.h"
#include "endian2.h"
#include "corpus.h"
#include "macros.h"
#include "fileutils.h"
#include "cdaccess.h"
#include "makecomps.h"
#include "list.h"
#include "attributes.h"
/*
*******************************************************************
* FLAGS controlling how ensure_component() behaves.
*******************************************************************
*/
/* TODO: these should be either
* (a) dynamic - set at runtime or
* (b) bound to a setting in config.mk or definitions.mk
* changing these settings should not require hacking the source! */
/**
* if CL_ENSURE_COMPONENT_EXITS is defined, ensure_component will exit
* when the component can't be created or loaded.
*/
#if 0
#define CL_ENSURE_COMPONENT_EXITS
#endif
/**
* if CL_ENSURE_COMPONENT_ALLOW_CREATION is defined, components may be created
* on the fly by ensure_component.
*/
#if 0
#define CL_ENSURE_COMPONENT_ALLOW_CREATION
#endif
/**
* if KEEP_SILENT is defined, ensure_component won't complain about
* non-accessible data.
*
* @see ensure_component
*/
#define CL_ENSURE_COMPONENT_KEEP_SILENT
/*******************************************************************/
/**
* The component_field_spec data type.
*
* @see Component_Field_Specs
*/
typedef struct component_field_spec {
ComponentID id; /**< the specifier for what kind of blob of info this component is; also used
as the index for this component in its Attribute's component array. */
char *name; /**< String used as the label for this component (abbreviation of the
relevant label from in the ComponentID enumeration). */
int using_atts; /**< The attribute type of the Attributes that use this component */
char *default_path; /**< The default location of the file corresponding to this component;
can contain variables ($DIR=directory, $ANAME=attribute name) */
} component_field_spec;
/**
* Global object in the "attributes" module, giving specifications
* for each component in the array of components that each Attribute
* object contains.
*/
static struct component_field_spec Component_Field_Specs[] =
{
{ CompDirectory, "DIR", ATT_ALL, "$APATH"},
{ CompCorpus, "CORPUS", ATT_POS, "$DIR" SUBDIR_SEP_STRING "$ANAME.corpus"},
{ CompRevCorpus, "REVCORP", ATT_POS, "$CORPUS.rev"},
{ CompRevCorpusIdx, "REVCIDX", ATT_POS, "$CORPUS.rdx"},
{ CompCorpusFreqs, "FREQS", ATT_POS, "$CORPUS.cnt"},
{ CompLexicon, "LEXICON", ATT_POS, "$DIR" SUBDIR_SEP_STRING "$ANAME.lexicon"},
{ CompLexiconIdx, "LEXIDX", ATT_POS, "$LEXICON.idx"},
{ CompLexiconSrt, "LEXSRT", ATT_POS, "$LEXICON.srt"},
{ CompAlignData, "ALIGN", ATT_ALIGN, "$DIR" SUBDIR_SEP_STRING "$ANAME.alg"},
{ CompXAlignData, "XALIGN", ATT_ALIGN, "$DIR" SUBDIR_SEP_STRING "$ANAME.alx"},
{ CompStrucData, "STRUC", ATT_STRUC, "$DIR" SUBDIR_SEP_STRING "$ANAME.rng"},
{ CompStrucAVS, "STRAVS", ATT_STRUC, "$DIR" SUBDIR_SEP_STRING "$ANAME.avs"},
{ CompStrucAVX, "STRAVX", ATT_STRUC, "$DIR" SUBDIR_SEP_STRING "$ANAME.avx"},
{ CompHuffSeq, "CIS", ATT_POS, "$DIR" SUBDIR_SEP_STRING "$ANAME.huf"},
{ CompHuffCodes, "CISCODE", ATT_POS, "$DIR" SUBDIR_SEP_STRING "$ANAME.hcd"},
{ CompHuffSync, "CISSYNC", ATT_POS, "$CIS.syn"},
{ CompCompRF, "CRC", ATT_POS, "$DIR" SUBDIR_SEP_STRING "$ANAME.crc"},
{ CompCompRFX, "CRCIDX", ATT_POS, "$DIR" SUBDIR_SEP_STRING "$ANAME.crx"},
{ CompLast, "INVALID", 0, "INVALID"}
};
/* ---------------------------------------------------------------------- */
/*TODO needed here? move to header file? */
ComponentState comp_component_state(Component *component);
/* ---------------------------------------------------------------------- */
/**
* Gets the specification for the named component field.
*
* This function returns a pointer to an element of the global, static
* Component_Field_Specs array.
*
* @param name A string that identifies the component field to be looked up.
* @return Pointer to the desired specification, or NULL if not found.
* @see Component_Field_Specs
*/
struct component_field_spec *
find_cid_name(char *name)
{
int i;
for (i = 0; i < CompLast; i++) {
if (strcmp(Component_Field_Specs[i].name, name) == 0)
return &Component_Field_Specs[i];
}
return NULL;
}
/**
* Gets the specification for the identified component field.
*
* This function returns a pointer to an element of the global, static
* Component_Field_Specs array.
*
* @param id The ComponentID for the component field to be looked up.
* @return Pointer to the desired specification, or NULL if not found.
* @see Component_Field_Specs
*/
struct component_field_spec *
find_cid_id(ComponentID id)
{
if (id < CompLast)
return &Component_Field_Specs[id];
else
return NULL;
}
/**
* Gets a string containing the name of the attribute component
* with the specified ID-code.
*/
char *
cid_name(ComponentID id)
{
struct component_field_spec *spec = find_cid_id(id);
return (spec == NULL ? "((NULL))" : spec->name);
}
/**
* Gets the identifier of the attribute component with the specified name.
*/
ComponentID
component_id(char *name)
{
struct component_field_spec *spec = find_cid_name(name);
return (spec == NULL ? CompLast : spec->id);
}
/* this function does not appear to be used anywhere ??*/
/**
* Checks whether a particular Attribute type can possess
* the specified component field.
*
* @return True or false.
*/
int
MayHaveComponent(int attr_type, ComponentID cid)
{
struct component_field_spec *spec;
spec = find_cid_id(cid);
if (spec && (spec->id != CompLast))
return (spec->using_atts & attr_type) ? 1 : 0;
else
return 0;
}
/**
* Gets a string containing a description of the specified attribute type.
*
* Non-exported function.
*
* @param i The attribute-type whose name is required.
* (Should be one of the values of the constants
* defined in cl.h.)
* @return String (pointer to internal constant string,
* do not change or free).
*/
char *
aid_name(int i)
{
switch (i) {
case ATT_NONE: return "NONE (ILLEGAL)"; break;
case ATT_POS: return "Positional Attribute"; break;
case ATT_STRUC: return "Structural Attribute"; break;
case ATT_ALIGN: return "Alignment Attribute"; break;
case ATT_DYN: return "Dynamic Attribute"; break;
default: return "ILLEGAL ATTRIBUTE TYPE"; break;
}
/* NOTREACHED */
return NULL;
}
/**
* Gets a string containing a description of the specified dynamic attribute argument type.
*
* Non-exported function.
*
* @param i The argument-type whose name is required.
* (Should be one of the values of the constants
* defined in cl.h.)
* @return String (pointer to internal constant string,
* do not change or free).
*/
char *
argid_name(int i)
{
switch (i) {
case ATTAT_NONE: return "NONE(ILLEGAL)"; break;
case ATTAT_POS: return "CorpusPosition"; break;
case ATTAT_STRING: return "String"; break;
case ATTAT_VAR: return "Variable[StringList]"; break;
case ATTAT_INT: return "Integer"; break;
case ATTAT_FLOAT: return "Float"; break;
case ATTAT_PAREF: return "PARef"; break;
default: return "ILLEGAL*ARGUMENT*TYPE"; break;
}
/* NOTREACHED */
return NULL;
}
/**
* Creates a DynArg object.
*
* The object created is a dynamic argument of the type specified by the argument type_id,
* with its "next" pointer set to NULL.
*
* @see DynArg
* @param type_id String specifying the type of argument required; choose from:
* STRING, POS, INT, VARARG, FLOAT
* @return Pointer to the new DynArg object, or NULL in case of an invalid
* type_id.
*/
DynArg *
makearg(char *type_id)
{
DynArg *arg;
arg = NULL;
if (strcmp(type_id, "STRING") == 0) {
arg = new(DynArg);
arg->type = ATTAT_STRING;
arg->next = NULL;
}
else if (strcmp(type_id, "POS") == 0) {
arg = new(DynArg);
arg->type = ATTAT_POS;
arg->next = NULL;
}
else if (strcmp(type_id, "INT") == 0) {
arg = new(DynArg);
arg->type = ATTAT_INT;
arg->next = NULL;
}
else if (strcmp(type_id, "VARARG") == 0) {
arg = new(DynArg);
arg->type = ATTAT_VAR;
arg->next = NULL;
}
else if (strcmp(type_id, "FLOAT") == 0) {
arg = new(DynArg);
arg->type = ATTAT_FLOAT;
arg->next = NULL;
}
else
arg = NULL;
return arg;
}
/* ---------------------------------------------------------------------- */
/**
* Sets up a corpus attribute.
*
* NEVER CALL THIS!! ONLY USED WHILE PARSING A REGISTRY ENTRY!!!!
*
* @param corpus The corpus this attribute belongs to.
* @param attribute_name The name of the attribute (i.e. the handle it has in the registry file).
* @param type Type of attribute to be created.
* @param data Unused. It can just be NULL.
*/
Attribute *
setup_attribute(Corpus *corpus,
char *attribute_name,
int type,
char *data)
{
Attribute *attr;
Attribute *prev;
/* count of attributes that the corpus possesses already, including the default
* used to calculate this attribute's attr_number value. */
int a_num;
attr = NULL;
if (cl_new_attribute(corpus, attribute_name, type) != NULL)
Rprintf("attributes:setup_attribute(): Warning: \n"
" Attribute %s of type %s already defined in corpus %s\n",
attribute_name, aid_name(type), corpus->id);
else {
ComponentID cid;
attr = new(Attribute);
attr->type = type;
attr->any.mother = corpus;
attr->any.name = attribute_name;
for (cid = CompDirectory; cid < CompLast; cid++)
attr->any.components[cid] = NULL;
if (strcmp(attribute_name, DEFAULT_ATT_NAME) == 0 && type == ATTAT_POS)
a_num = 0;
else
a_num = 1;
/* insert at end of attribute list */
attr->any.next = NULL;
if (corpus->attributes == NULL)
corpus->attributes = attr;
else {
for (prev = corpus->attributes; prev->any.next; prev = prev->any.next)
a_num++;
assert(prev);
assert(prev->any.next == NULL);
prev->any.next = attr;
}
attr->any.attr_number = a_num;
attr->any.path = NULL;
/* ======================================== type specific initializations */
switch (attr->type) {
case ATT_POS:
attr->pos.hc = NULL;
attr->pos.this_block_nr = -1;
break;
case ATT_STRUC:
attr->struc.has_attribute_values = -1; /* not yet known */
break;
default:
break;
}
}
return attr;
}
/**
* Finds an attribute that matches the specified parameters, if one exists,
* for the given corpus.
*
* Note that although this is a cl_new_* function, and it is the canonical way
* that we get an Attribute to call Attribute-functions on, it doesn't actually
* create any kind of object. The Attribute exists already as one of the dependents
* of the Corpus object; this function simply locates it and returns a pointer
* to it.
*
* This function is DEPRACATED. Use cl_new_attribute() instead (which is
* actually a macro to this function, but the parameter list is different.)
*
* @see cl_new_attribute
*
* @param corpus The corpus in which to search for the attribute.
* @param attribute_name The name of the attribute (i.e. the handle it has in the registry file).
* @param type Type of attribute to be searched for.
* @param data NOT USED.
*
* @return Pointer to Attribute object, or NULL if not found.
*/
Attribute *
cl_new_attribute_oldstyle(Corpus *corpus,
char *attribute_name,
int type,
char *data)
{
Attribute *attr;
attr = NULL;
if (corpus == NULL)
Rprintf("attributes:cl_new_attribute_oldstyle(): called with NULL corpus\n");
else {
for (attr = corpus->attributes; attr != NULL; attr = attr->any.next)
if ((type == attr->type) &&
STREQ(attr->any.name, attribute_name))
break;
}
return attr;
}
/**
* Drops an attribute for the given corpus.
*
* The attribute to be dropped is specified by its attribute name
* and its type (i.e. no pointer needed: compare cl_delete_attribute).
*
* After calling this, the corpus does not have the attribute any
* longer -- it is the same as it was never defined.
*
* This is an internal function; the function exposed in the API for
* this purpose is cl_delete_attribute().
*
* tODO: this function can probably actually be deleted. It doesn't
* todo: seem to be used anywhere, and is much more complex than
* todo: cl_delete_attribute
*
* @see cl_delete_attribute
* @return Boolean: true for all OK, false for a problem
*/
int
drop_attribute(Corpus *corpus,
char *attribute_name,
int type,
char *data)
{
if (corpus == NULL) {
Rprintf("attributes:drop_attribute(): called with NULL corpus\n");
return 0;
}
else
return cl_delete_attribute(cl_new_attribute_oldstyle(corpus, attribute_name, type, data));
}
/**
* Deletes the specified Attribute object.
*
* The function also appropriately amends the Corpus object of which this
* Attribute is a dependent. This means you can call it repreatedly on the first
* element of a Corpus's Attribute list (as the linked list is automatically
* adjusted).
*
* @return Boolean: true for all OK, false for a problem.
*/
int
cl_delete_attribute(Attribute *attribute)
{
Attribute *prev = NULL;
DynArg *arg;
Corpus *corpus;
ComponentID cid;
if (attribute == NULL)
return 0;
else {
corpus = attribute->any.mother;
assert("NULL corpus in attribute" && (corpus != NULL));
/* remove attribute from corpus attribute list */
if (attribute == corpus->attributes)
corpus->attributes = attribute->any.next;
else {
for (prev = corpus->attributes;
(prev != NULL) && (prev->any.next != attribute);
prev = prev->any.next)
;
if (prev == NULL)
Rprintf("attributes:cl_delete_attribute():\n"
" Warning: Attribute %s not in list of corpus attributes\n",
attribute->any.name);
else {
assert("Error in attribute chain" && (prev->any.next == attribute));
prev->any.next = attribute->any.next;
}
}
/* get rid of components */
for (cid = CompDirectory; cid < CompLast; cid++)
if (attribute->any.components[cid]) {
comp_drop_component(attribute->any.components[cid]);
attribute->any.components[cid] = NULL;
}
cl_free(attribute->any.name);
cl_free(attribute->any.path);
/* get rid of special fields */
switch (attribute->type) {
case ATT_POS:
cl_free(attribute->pos.hc);
break;
case ATT_DYN:
cl_free(attribute->dyn.call);
while (attribute->dyn.arglist != NULL) {
arg = attribute->dyn.arglist;
attribute->dyn.arglist = arg->next;
cl_free(arg);
}
break;
default:
break;
}
/* TODO do we really need to overwrite these members when we are about to free the attribute? */
attribute->any.mother = NULL;
attribute->any.type = ATT_NONE;
attribute->any.next = NULL;
cl_free(attribute);
return 1;
}
/* notreached */
assert("Notreached point reached ..." && 0);
return 1;
}
/**
* Accessor function to get the mother corpus of the attribute.
*/
Corpus *
cl_attribute_mother_corpus(Attribute *attribute)
{
return attribute->any.mother;
}
/* ---------------------------------------------------------------------- */
/**
* Sets up a component for the given attribute.
*
* If the component of the specified ComponentID does not already exist,
* a new Component object is created, set up, and assigned to the attribute's
* component array. Finally, the component path is initialised using the
* path argument.
*
* @see component_full_name
* @param attribute The Attribute for which to create this component.
* @param cid The ID of the component to create.
* @param path Path to be passed to component_full_name. Can be NULL.
* @return The new component if all is OK. If a component with the
* specified ID already exists, it is returned and no new
* component is created (and a warning message is printed
* to STDERR). If the attribute is NULL, return is NULL
* (and a warning is printed).
*/
Component *
declare_component(Attribute *attribute, ComponentID cid, char *path)
{
Component *component;
if (attribute == NULL) {
Rprintf("attributes:declare_component(): \n"
" NULL attribute passed in declaration of %s component\n",
cid_name(cid));
return NULL;
}
if ((component = attribute->any.components[cid]) == NULL) {
component = new(Component);
component->id = cid;
component->corpus = attribute->any.mother;
component->attribute = attribute;
component->path = NULL;
init_mblob(&(component->data));
attribute->any.components[cid] = component;
/* we can then initialize the component path within the attribute */
(void) component_full_name(attribute, cid, path);
}
else {
Rprintf("attributes:declare_component(): Warning:\n"
" Component %s of %s declared twice\n",
cid_name(cid), attribute->any.name);
}
return component;
}
/**
* Sets up a default set of components on the given attribute.
*
* Note that in each case, a call is made to declare_component
* with the path as NULL.
*
* @see declare_component
*/
void
declare_default_components(Attribute *attribute)
{
int i;
if (attribute == NULL)
Rprintf("attributes:declare_default_components(): \n"
" NULL attribute passed -- can't create defaults\n");
else {
for (i = CompDirectory; i < CompLast; i++)
if (((Component_Field_Specs[i].using_atts & attribute->type) != 0) &&
(attribute->any.components[i] == NULL))
(void) declare_component(attribute, i, NULL);
/* TODO should the return value of declare_component be checked for error? */
}
}
/* ---------------------------------------------------------------------- */
/**
* Works out and returns the state of the component.
*/
ComponentState
comp_component_state(Component *comp)
{
assert(comp);
if (comp->data.data != NULL)
return ComponentLoaded;
else if (comp->id == CompDirectory)
return ComponentDefined;
else if (comp->path == NULL)
return ComponentUndefined;
else if (file_length(comp->path) < 0) /* access error == EOF -> assume file doesn't exist */
return ComponentDefined;
else
return ComponentUnloaded;
}
/**
* Gets the state of a specified component on the given attribute.
*
* @param attribute The attribute to look at.
* @param cid The component whose state to get.
* @return The return value in case the component is not
* found is ComponentUndefined. Otherwise, some
* other value of ComponentState.
*/
ComponentState
component_state(Attribute *attribute, ComponentID cid)
{
if (cid < CompLast) {
Component *comp = attribute->any.components[cid];
if (comp == NULL)
return ComponentUndefined;
else
return comp_component_state(comp);
}
else
return ComponentUndefined;
}
/* ---------------------------------------------------------------------- */
/**
* Initializes the path of an attribute Component.
*
* This function starts with the path it is passed, and then evaluates variables
* in the form $UPPERCASE. The resulting path is assigned to the specified
* entry in the component array for the given Attribute.
*
* Note that if it is called for a Component that does not yet exist, this function
* creates the component by calling declare_component().
*
* @see declare_component
* @see Component_Field_Specs
* @param attribute The Attribute object to work with.
* @param cid The identifier of the Component to which the path is to
* be added.
* @param path The path to assign to the component. Can be NULL,
* in which case, the default path from Component_Field_Specs
* is used.
* @return Pointer to this function's static buffer for creating the
* path (NB: NOT to the path in the actual component! which
* is a copy). If a path already exists, a pointer to that
* path. NULL in case of error in Component_Field_Specs.
* TODO: could this be a void function?
*/
char *
component_full_name(Attribute *attribute, ComponentID cid, char *path)
{
component_field_spec *compspec;
Component *component;
static char buf[CL_MAX_LINE_LENGTH];
char rname[CL_MAX_LINE_LENGTH];
char *reference;
char c;
int ppos, bpos, rpos;
/* did we do the job before? */
if ((component = attribute->any.components[cid]) != NULL &&
(component->path != NULL))
return component->path;
/* yet undeclared. So try to guess the name: */
compspec = NULL;
if (path == NULL) {
if ((compspec = find_cid_id(cid)) == NULL) {
Rprintf("attributes:component_full_name(): Warning:\n"
" can't find component table entry for Component #%d\n", cid);
return NULL;
}
path = compspec->default_path;
}
/* index in string "path" */
ppos = 0;
/* index in string "buf" */
bpos = 0;
/* dollar = 0; */
rpos = 0;
buf[bpos] = '\0';
while ((c = path[ppos]) != '\0') {
if (c == '$') {
/* reference to the name of another component. */
/* dollar = ppos; */ /* memorize the position of the $ */
rpos = 0;
c = path[++ppos]; /* first skip the '$' */
while (isupper(c)) {
rname[rpos++] = c;
c = path[++ppos];
}
rname[rpos] = '\0';
/* ppos now points to the first character after the reference
* rname holds the UPPERCASE name of the referenced component
*/
reference = NULL;
if (STREQ(rname, "HOME"))
reference = getenv(rname);
else if (STREQ(rname, "APATH"))
reference = (attribute->any.path ? attribute->any.path
: attribute->any.mother->path);
else if (STREQ(rname, "ANAME"))
reference = attribute->any.name;
else if ((compspec = find_cid_name(rname)) != NULL)
reference = component_full_name(attribute, compspec->id, NULL);
if (reference == NULL) {
Rprintf("attributes:component_full_name(): Warning:\n"
" Can't reference to the value of %s -- copying\n",
rname);
reference = rname;
}
for (rpos = 0; reference[rpos] != '\0'; rpos++) {
buf[bpos] = reference[rpos];
bpos++;
}
}
else {
/* just copy the character and scroll */
buf[bpos] = c;
bpos++;
ppos++;
}
}
buf[bpos] = '\0';
if (component != NULL)
component->path = (char *)cl_strdup(buf);
else
(void) declare_component(attribute, cid, buf);
/* and return it */
return &buf[0];
/* ?? why is buf returned instead of component->path, as earlier in the function? -- AH 16/9/09 */
}
/* ---------------------------------------------------------------------- */
/**
* Loads the specified component for this attribute.
*
* "Loading" means that the file specified by the component's "path" member
* is read into the "data" member.
*
* If the component is CompHuffCodes, part of the data is also copied to the
* attribute's pos.hc member (that is, the beginning of the file).
*
* Note that the action of this function is dependent on the component's state.
* If the component's state is ComponentUnloaded, the component is loaded.
* If the component's state is ComponentDefined, the size is set to 0 and
* nothing else is done.
*
* @param attribute The Attribute object to work with.
* @param cid The identifier of the Component to load.
* @return Pointer to the component. This will be NULL if the
* component has not been declared (i.e. created).
*/
Component *
load_component(Attribute *attribute, ComponentID cid)
{
Component *comp;
assert((attribute != NULL) && "Null attribute passed to load_component");
comp = attribute->any.components[cid];
if (comp == NULL) {
Rprintf("attributes:load_component(): Warning:\n"
" Component %s is not declared for %s attribute\n",
cid_name(cid), aid_name(attribute->type));
}
else if (comp_component_state(comp) == ComponentUnloaded) {
assert(comp->path != NULL);
if (cid == CompHuffCodes) {
if (cl_sequence_compressed(attribute)) {
if (read_file_into_blob(comp->path, MMAPPED, sizeof(int), &(comp->data)) == 0)
Rprintf("attributes:load_component(): Warning:\n"
" Data of %s component of attribute %s can't be loaded\n",
cid_name(cid), attribute->any.name);
else {
if (attribute->pos.hc != NULL)
Rprintf("attributes:load_component: WARNING:\n\t"
"HCD block already loaded, overwritten.\n");
attribute->pos.hc = new(HCD);
/* bcopy(comp->data.data, attribute->pos.hc, sizeof(HCD)); */
memcpy(attribute->pos.hc, comp->data.data, sizeof(HCD));
{ /* convert network byte order to native integers */
int i;
attribute->pos.hc->size = ntohl(attribute->pos.hc->size);
attribute->pos.hc->length = ntohl(attribute->pos.hc->length);
attribute->pos.hc->min_codelen = ntohl(attribute->pos.hc->min_codelen);
attribute->pos.hc->max_codelen = ntohl(attribute->pos.hc->max_codelen);
for (i = 0; i < MAXCODELEN; i++) {
attribute->pos.hc->lcount[i] = ntohl(attribute->pos.hc->lcount[i]);
attribute->pos.hc->symindex[i] = ntohl(attribute->pos.hc->symindex[i]);
attribute->pos.hc->min_code[i] = ntohl(attribute->pos.hc->min_code[i]);
}
}
attribute->pos.hc->symbols = comp->data.data + (4+3*MAXCODELEN);
comp->size = attribute->pos.hc->length;
assert(comp_component_state(comp) == ComponentLoaded);
}
}
else {
Rprintf("attributes/load_component: missing files of compressed PA,\n"
"\tcomponent CompHuffCodes not loaded\n");
}
}
else if ((cid > CompDirectory) && (cid < CompLast)) {
/* i.e. any ComponentID value except CompDirectory / CompLast and CompHuffCodes */
if (read_file_into_blob(comp->path, MMAPPED, sizeof(int), &(comp->data)) == 0)
Rprintf("attributes:load_component(): Warning:\n"
" Data of %s component of attribute %s can't be loaded\n",
cid_name(cid), attribute->any.name);
else {
comp->size = comp->data.nr_items;
assert(comp_component_state(comp) == ComponentLoaded);
}
}
}
else if (comp_component_state(comp) == ComponentDefined)
comp->size = 0;
return comp;
}
/* ---------------------------------------------------------------------- */
/**
* Creates the specified component for the given Attribute.
*
* This function only works for the following components:
* CompRevCorpus, CompRevCorpusIdx, CompLexiconSrt, CompCorpusFreqs.
* Also, it only works if the state of the component is
* ComponentDefined.
*
* "Create" here means create the CWB data files. This is accomplished by
* calling one of the "creat_*" functions, of which there is one for each
* of the four available component types. These are defined in makecomps.c.
*
* Each of these functions reads in the data it needs, processes it, and then
* writes a new file.
*
* @param attribute The Attribute object to work with.
* @param cid The identifier of the Component to create.
*
* @return Pointer to the component created, or NULL in case of
* error (e.g. if an invalid component was requested).
*
*/
Component *
create_component(Attribute *attribute, ComponentID cid)
{
Component *comp = attribute->any.components[cid];
if (cl_debug) {
Rprintf("Creating %s\n", cid_name(cid));
}
if (component_state(attribute, cid) == ComponentDefined) {
assert(comp != NULL);
assert(comp->data.data == NULL);
assert(comp->path != NULL);
switch (cid) {
case CompLast:
case CompDirectory:
/* cannot create these */
break;
case CompCorpus:
case CompLexicon:
case CompLexiconIdx:
Rprintf("attributes:create_component(): Warning:\n"
" Can't create the '%s' component. Use 'encode' to create it"
" out of a text file\n",
cid_name(cid));
return NULL;
break;
case CompHuffSeq:
case CompHuffCodes:
case CompHuffSync:
Rprintf("attributes:create_component(): Warning:\n"
" Can't create the '%s' component. Use 'huffcode' to create it"
" out of an item sequence file\n",
cid_name(cid));
return NULL;
break;
case CompCompRF:
case CompCompRFX:
Rprintf("attributes:create_component(): Warning:\n"
" Can't create the '%s' component. Use 'compress-rdx' to create it"
" out of the reversed file index\n",
cid_name(cid));
return NULL;
break;
case CompRevCorpus:
creat_rev_corpus(comp);
break;
case CompRevCorpusIdx:
creat_rev_corpus_idx(comp);
break;
case CompLexiconSrt:
creat_sort_lexicon(comp);
break;
case CompCorpusFreqs:
creat_freqs(comp);
break;
case CompAlignData:
case CompXAlignData:
case CompStrucData:
case CompStrucAVS:
case CompStrucAVX:
Rprintf("attributes:create_component(): Warning:\n"
" Can't create the '%s' component of %s attribute %s.\n"
" Use the appropriate external tool to create it.\n",
cid_name(cid), aid_name(attribute->type), attribute->any.name);
return NULL;
break;
default:
comp = NULL;
Rprintf("attributes:create_component(): Unknown cid: %d\n", cid);
assert(0);
break;
}
return comp;
}
return NULL;
}
/**
* Ensures that a component is loaded and ready.
*
* The state of the component specified should be ComponentLoaded
* once this function has run (assuming all is well). If the
* component is unloaded, the function will try to load it. If the
* component is defined, the function MAY try to create it. If the
* component is undefined, nothing will be done.
*
* There are flags in attributes.c that control the behaviour of
* this function (e.g. if failure to ensure causes the program
* to abort).
*
* @see CL_ENSURE_COMPONENT_KEEP_SILENT
* @see CL_ENSURE_COMPONENT_EXITS
* @see CL_ENSURE_COMPONENT_ALLOW_CREATION
*
* @param attribute The Attribute object to work with.
* @param cid The identifier of the Component to "ensure".
* @param try_creation Boolean. True = attempt to create a
* component that does not exist. False = don't.
* This behaviour only applies when
* CL_ENSURE_COMPONENT_ALLOW_CREATION is defined;
* otherwise component creation will never be attempted.
* @return A pointer to the specified component (or NULL
* if the component cannot be "ensured").
*/
Component *
ensure_component(Attribute *attribute, ComponentID cid, int try_creation)
{
Component *comp = NULL;
if ((comp = attribute->any.components[cid]) == NULL) {
/* component is undeclared */
Rprintf("attributes:ensure_component(): Warning:\n"
" Undeclared component: %s\n", cid_name(cid));
#ifdef CL_ENSURE_COMPONENT_EXITS
exit(1);
#endif
return NULL;
}
else {
switch (comp_component_state(comp)) {
case ComponentLoaded:
/* already here, so do nothing */
break;
case ComponentUnloaded:
(void) load_component(attribute, cid); /* try to load the component */
if (comp_component_state(comp) != ComponentLoaded) {
#ifndef CL_ENSURE_COMPONENT_KEEP_SILENT
Rprintf("attributes:ensure_component(): Warning:\n"
" Can't load %s component of %s\n",
cid_name(cid), attribute->any.name);
#endif
#ifdef CL_ENSURE_COMPONENT_EXITS
exit(1);
#endif
return NULL;
}
break;
case ComponentDefined: /* try to create the component */
if (try_creation != 0) {
#ifdef CL_ENSURE_COMPONENT_ALLOW_CREATION
(void) create_component(attribute, cid);
if (comp_component_state(comp) != ComponentLoaded) {
#ifndef CL_ENSURE_COMPONENT_KEEP_SILENT
Rprintf("attributes:ensure_component(): Warning:\n"
" Can't load or create %s component of %s\n",
cid_name(cid), attribute->any.name);
#endif
#ifdef CL_ENSURE_COMPONENT_EXITS
exit(1);
#endif
return NULL;
}
#else
Rprintf("Sorry, but this program is not set up to allow the\n"
"creation of corpus components. Please refer to the manuals\n"
"or use the ''cwb-makeall'' tool.\n");
#ifdef CL_ENSURE_COMPONENT_EXITS
exit(1);
#endif
return NULL;
#endif
}
else {
#ifndef CL_ENSURE_COMPONENT_KEEP_SILENT
Rprintf("attributes:ensure_component(): Warning:\n"
" I'm not allowed to create %s component of %s\n",
cid_name(cid), attribute->any.name);
#endif
#ifdef CL_ENSURE_COMPONENT_EXITS
exit(1);
#endif
return NULL;
}
break;
case ComponentUndefined: /* don't have this, -> error */
Rprintf("attributes:ensure_component(): Warning:\n"
" Can't ensure undefined/illegal %s component of %s\n",
cid_name(cid), attribute->any.name);
#ifdef CL_ENSURE_COMPONENT_EXITS
exit(1);
#endif
break;
default:
Rprintf("attributes:ensure_component(): Warning:\n"
" Illegal state of %s component of %s\n",
cid_name(cid), attribute->any.name);
#ifdef CL_ENSURE_COMPONENT_EXITS
exit(1);
#endif
break;
}
}
return comp;
}
/* ---------------------------------------------------------------------- */
/**
* Gets a pointer to the specified component for the given Attribute.
*/
Component *
find_component(Attribute *attribute, ComponentID cid)
{
return attribute->any.components[cid];
}
/* ---------------------------------------------------------------------- */
/**
* Delete a Component object.
*
* The specified component object, and all memory associated with it, is freed.
*
* @return Always 1.
*/
int
comp_drop_component(Component *comp)
{
assert((comp != NULL) && "NULL component passed to attributes:comp_drop_component");
assert(comp->attribute);
if (comp->attribute->any.components[comp->id] != comp)
assert(0 && "comp is not member of that attr");
comp->attribute->any.components[comp->id] = NULL;
if (comp->id == CompHuffCodes) {
/* it may be empty, since declare_component doesn't yet load the data */
cl_free(comp->attribute->pos.hc);
}
mfree(&(comp->data));
cl_free(comp->path);
comp->corpus = NULL;
comp->attribute = NULL;
comp->id = CompLast;
free(comp);
return 1;
}
/**
* Drops the specified component for the given Attribute.
*
* @see comp_drop_component
* @param attribute The Attribute object to work with.
* @param cid The identifier of the Component to drop.
* @return Always 1.
*/
int
drop_component(Attribute *attribute, ComponentID cid)
{
Component *comp;
if ((comp = attribute->any.components[cid]) != NULL)
return comp_drop_component(comp);
else
return 1;
}
/* =============================================== LOOP THROUGH ATTRIUBTES */
/**
* Non-exported variable: accessed via the attribute-looping functions.
*
* @see first_corpus_attribute
* @see next_corpus_attribute
*/
Attribute *loop_ptr;
/**
* Get a pointer to the head entry in the specified corpus's list of attributes.
*
* @return NULL if the corpus parameter is NULL; otherwise a pointer to Attribute.
*/
Attribute *
first_corpus_attribute(Corpus *corpus)
{
if (corpus)
loop_ptr = corpus->attributes;
else
loop_ptr = NULL;
return loop_ptr;
}
/**
* Get a pointer to the next attribute on the list currently being processed.
*/
Attribute *
next_corpus_attribute()
{
if (loop_ptr)
loop_ptr = loop_ptr->any.next;
return loop_ptr;
}
/* =============================================== INTERACTIVE FUNCTIONS */
/**
* Prints a description of the attribute (inc.components) to STDOUT.
*/
void
describe_attribute(Attribute *attribute)
{
DynArg *arg;
ComponentID cid;
Rprintf("Attribute %s:\n", attribute->any.name);
Rprintf(" Type: %s\n", aid_name(attribute->any.type));
/* print type dependent additional data */
if (attribute->type == ATT_DYN) {
Rprintf(" Arguments: (");
for (arg = attribute->dyn.arglist; arg; arg = arg->next) {
Rprintf("%s", argid_name(arg->type));
if (arg->next != NULL)
Rprintf(", ");
}
Rprintf("):%s\n"
" by \"%s\"\n",
argid_name(attribute->dyn.res_type),
attribute->dyn.call);
}
Rprintf("\n");
for (cid = CompDirectory; cid < CompLast; cid++)
if (attribute->any.components[cid])
describe_component(attribute->any.components[cid]);
Rprintf("\n\n");
}
/**
* Prints a description of the component to STDOUT.
*/
void
describe_component(Component *component)
{
Rprintf(" Component %s:\n", cid_name(component->id));
Rprintf(" Attribute: %s\n", component->attribute->any.name);
Rprintf(" Path/Value: %s\n", component->path);
Rprintf(" State: ");
switch (comp_component_state(component)) {
case ComponentLoaded:
Rprintf("loaded");
break;
case ComponentUnloaded:
Rprintf("unloaded (valid & on disk)");
break;
case ComponentDefined:
Rprintf("defined (valid, but not on disk)");
break;
case ComponentUndefined:
Rprintf("undefined (not valid)");
break;
default:
Rprintf("ILLEGAL! (Illegal component state %d)", comp_component_state(component));
break;
}
Rprintf("\n\n");
}
/* =============================================== SET ATTRIBUTES */
/* TODO the feature set functions don't really seemt o belong in this file */
/**
* Generates a feature-set attribute value.
*
* @param s The input string.
* @param split Boolean; if True, s is split on whitespace.
* If False, the function expects input in '|'-delimited format.
* @return The set attribute value in standard syntax ('|' delimited, sorted with cl_strcmp).
* If there is any syntax error, cl_make_set() returns NULL.
*/
char *
cl_make_set(char *s, int split)
{
char *copy = cl_strdup(s); /* work on copy of <s> */
cl_string_list l = cl_new_string_list(); /* list of set elements */
int ok = 0; /* for split and element check */
char *p, *mark, *set;
int i, sl, length;
cl_errno = CDA_OK;
/* (1) split input string into set elements */
if (split) {
/* split on whitespace */
p = copy;
while (*p != 0) {
while (*p == ' ' || *p == '\t' || *p == '\n') {
p++;
}
mark = p;
while (*p != 0 && *p != ' ' && *p != '\t' && *p != '\n') {
p++;
}
if (*p != 0) { /* mark end of substring */
*p = 0;
p++;
}
else {
/* p points to end of string; since it hasn't been advanced, the while loop will terminate */
}
if (p != mark) {
cl_string_list_append(l, mark);
}
}
ok = 1; /* split on whitespace can't really fail */
}
else {
/* check and split '|'-delimited syntax */
if (copy[0] == '|') {
mark = p = copy+1;
while (*p != 0) {
if (*p == '|') {
*p = 0;
cl_string_list_append(l, mark);
mark = p = p+1;
}
else {
p++;
}
}
if (p == mark) { /* otherwise, there was no trailing '|' */
ok = 1;
}
}
}
/* (2) check set elements: must not contain '|' character */
length = cl_string_list_size(l);
for (i = 0; i < length; i++) {
if (strchr(cl_string_list_get(l, i), '|') != NULL) {
ok = 0;
}
}
/* (3) abort if there was any error */
if (!ok) {
cl_delete_string_list(l);
cl_free(copy);
cl_errno = CDA_EFSETINV;
return NULL;
}
/* (4) sort set elements (for unify() function) */
cl_string_list_qsort(l);
/* (5) combine elements into set attribute string */
sl = 2; /* compute length of string */
for (i = 0; i < length; i++) {
sl += strlen(cl_string_list_get(l, i)) + 1;
}
set = cl_malloc(sl); /* allocate string of exact size */
p = set;
*p++ = '|';
for (i = 0; i < length; i++) {
strcpy(p, cl_string_list_get(l, i));
p += strlen(cl_string_list_get(l, i));
*p++ = '|'; /* overwrites EOS mark inserted by strcpy() */
}
*p = 0; /* EOS */
/* (6) free intermediate data and return the set string */
cl_delete_string_list(l);
cl_free(copy);
return set;
}
/**
* Counts the number of elements in a set attribute value.
*
* This function counts the number of elements in a set attribute value
* (using '|'-delimited standard syntax);
*
* @return -1 on error (in particular, if set is malformed)
*/
int
cl_set_size(char *s)
{
int count = 0;
cl_errno = CDA_OK;
if (*s++ != '|') {
cl_errno = CDA_EFSETINV;
return -1;
}
while (*s) {
if (*s == '|') count++;
s++;
}
if (s[-1] != '|') {
cl_errno = CDA_EFSETINV;
return -1;
}
return count;
}
/**
* Computes the intersection of two set attribute values.
*
* Compute intersection of two set attribute values (in standard syntax, i.e. sorted and '|'-delimited);
* memory for the result string must be allocated by the caller.
*
* @return 0 on error, 1 otherwise
*/
int
cl_set_intersection(char *result, const char *s1, const char *s2)
{
static char f1[CL_DYN_STRING_SIZE], f2[CL_DYN_STRING_SIZE]; /* static feature buffers (hold current feature) */
char *p;
int comparison;
cl_errno = CDA_OK;
if ((*s1++ != '|') || (*s2++ != '|')) {
cl_errno = CDA_EFSETINV;
return 0;
}
if (strlen(s1) >= CL_DYN_STRING_SIZE || strlen(s2) >= CL_DYN_STRING_SIZE) {
cl_errno = CDA_EBUFFER;
return 0;
}
*result++ = '|'; /* Initialise result */
while (*s1 && *s2) {
/* while a feature is active, *s_i points to the '|' separator at its end;
when the feature is used up, *s_i is advanced and we read the next feature */
if (*s1 != '|') {
for (p = f1; *s1 != '|'; s1++) {
if (!*s1) {
cl_errno = CDA_EFSETINV;
return 0; /* unexpected end of string */
}
*p++ = *s1;
/* should check for buffer overflow here! */
}
*p = 0; /* terminate feature string */
}
if (*s2 != '|') {
for (p = f2; *s2 != '|'; s2++) {
if (!*s2) {
cl_errno = CDA_EFSETINV;
return 0; /* unexpected end of string */
}
*p++ = *s2;
/* should check for buffer overflow here! */
}
*p = 0; /* terminate feature string */
}
/* now compare the two active features (uses cl_strcmp to ensure standard behaviour) */
comparison = cl_strcmp(f1,f2);
if (comparison == 0) {
/* common feature -> copy to result vector */
for (p = f1; *p; p++)
*result++ = *p;
*result++ = '|';
/* both features are used up now */
s1++; s2++;
}
else if (comparison < 0) {
/* advance s1 */
s1++;
}
else {
/* advance s2 */
s2++;
}
} /* ends: while (*s1 && *s2) */
/* computation complete: terminate result string */
*result = 0;
return 1;
}
/* EOF */
|
maguangxiao/GXKit_OC
|
GXKit_OC/Class/Frame/Controller/GXNavigationController.h
|
<gh_stars>0
//
// GXNavigationController.h
// GXKit_OC
//
// Created by GuangXiao on 2018/2/24.
// Copyright © 2018年 guangxiao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface GXNavigationController : UINavigationController
@end
|
maguangxiao/GXKit_OC
|
GXKit_OC/Class/Mine/mine/Controller/MineViewController.h
|
<reponame>maguangxiao/GXKit_OC
//
// MineViewController.h
// GXKit_OC
//
// Created by GuangXiao on 2018/2/24.
// Copyright © 2018年 guangxiao. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "GXViewController.h"
@interface MineViewController : GXViewController
@end
|
maguangxiao/GXKit_OC
|
GXKit_OC/Class/Frame/Controller/GXTabBarController.h
|
<gh_stars>0
//
// GXTabBarController.h
// GXKit_OC
//
// Created by GuangXiao on 2018/2/24.
// Copyright © 2018年 guangxiao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface GXTabBarController : UITabBarController
@end
|
maguangxiao/GXKit_OC
|
GXKit_OC/Class/Home/home/Controller/HomeViewController.h
|
<reponame>maguangxiao/GXKit_OC
//
// HomeViewController.h
// GXKit_OC
//
// Created by GuangXiao on 2018/2/24.
// Copyright © 2018年 guangxiao. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "GXViewController.h"
@interface HomeViewController : GXViewController
@end
|
maguangxiao/GXKit_OC
|
GXKit_OC/Class/Frame/Controller/GXViewController.h
|
//
// GXViewController.h
// GXKit_OC
//
// Created by GuangXiao on 2018/2/24.
// Copyright © 2018年 guangxiao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface GXViewController : UIViewController
@end
|
eliasdaler/sfgc
|
include/sfgc/sfgc.h
|
#ifndef SFGC_H
#define SFGC_H
#pragma once
#include <array>
#include <cstdint>
#include <SFML/Window/Joystick.hpp>
namespace sf
{
class Event;
}
namespace sfgc
{
enum class Button : std::size_t {
A,
B,
X,
Y,
LeftShoulder,
RightShoulder,
LeftTrigger,
RightTrigger,
LeftStick,
RightStick,
Back,
Start,
Guide,
None
};
static const std::size_t NUM_BUTTONS = 13;
enum class Axis : std::size_t {
DPadX,
DPadY,
LeftX,
LeftY,
RightX,
RightY,
LeftTrigger,
RightTrigger,
None
};
static const std::size_t NUM_AXES = 8;
using GamepadId = unsigned int;
using SFMLButtonId = unsigned int;
struct AxisMapping {
enum class Type {
Axis, // SFGC axis <-> SFML axis
Button, // SFGC axis <-> SFML button (TODO: needs two buttons to work actually)
None
};
Type type = Type::None;
sf::Joystick::Axis axis = sf::Joystick::PovX;
SFMLButtonId button = 0; // TODO: store TWO buttons, because won't work with one
bool inverted = false; // if true - positive value of axis in SFML will mean negative value in
// SFGC
};
struct Mapping {
void addAxisMapping(Axis axis, const AxisMapping& axisMapping);
void addButtonMapping(Button button, SFMLButtonId sfmlButton);
Button getButton(SFMLButtonId button) const;
Axis getAxis(sf::Joystick::Axis axis) const;
Axis getAxis(SFMLButtonId button) const;
bool isAxisInverted(Axis axis) const;
const std::string& getGamepadName() const;
std::array<SFMLButtonId, NUM_BUTTONS> buttons; // index - Button
std::array<AxisMapping, NUM_AXES> axes; // index - sf::Joystick::Axis
std::string gamepadName;
};
struct Event {
enum class Type { ButtonPressed, ButtonReleased, AxisMoved, None };
Type type = Type::None;
Axis axis = Axis::None;
Button button = Button::None;
GamepadId gamepadId = 0;
float axisPosition = 0.f;
};
void loadMappings();
bool mappingExists(const sf::Joystick::Identification& id);
Mapping& getMapping(const sf::Joystick::Identification& id);
bool isGamepadEvent(const sf::Event& event);
Event fromSFMLEvent(const Mapping& mapping, const sf::Event& event);
} // namespace sfgc
#endif //# IMGUI_SFML_H
|
janbiedermann/cstl
|
tests/http.c
|
/* *****************************************************************************
Copyright: <NAME>, 2019-2020
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
/* *****************************************************************************
This is a simple HTTP "Hello World" / echo server example using `poll`.
Benchmark with keep-alive:
ab -c 200 -t 4 -n 1000000 -k http://127.0.0.1:3000/
wrk -c200 -d4 -t1 http://localhost:3000/
Note: This is a **TOY** example, no security whatsoever!!!
***************************************************************************** */
/* include some of the modules we use... */
#define FIO_LOG
#define FIO_URL
#define FIO_SOCK
#define FIO_SIGNAL
#define FIO_CLI
#define FIO_TIME
#define FIO_POLL
// #define FIO_POLL_DEBUG
// #define FIO_MEMORY_DISABLE 1
#include "fio-stl.h"
/* Short string object used for response objects. */
#define FIO_STREAM
#define FIO_MEMORY_NAME str_allocator /* response & stream string allocator */
#define FIO_STR_NAME str
#include "fio-stl.h"
/* we use local global variables to make the code easier. */
/** A flag telling us when to stop reviewing IO events. */
static volatile uint8_t server_stop_flag = 0;
#define HTTP_CLIENT_BUFFER 32768
#define HTTP_MAX_HEADERS 16
/* an echo response is always dynamic (allocated on the heap). */
#define HTTP_RESPONSE_ECHO 1
/* if not echoing, the response is "Hello World" - but is it allocated? */
#define HTTP_RESPONSE_DYNAMIC 1
/* *****************************************************************************
Callbacks and object used by main()
***************************************************************************** */
/** Called when the socket have available space in the outgoing buffer. */
FIO_SFUNC void on_ready(int fd, void *arg);
/** Called there's incoming data (from STDIN / the client socket. */
FIO_SFUNC void on_data(int fd, void *arg);
/** Called when the monitored IO is closed or has a fatal error. */
FIO_SFUNC void on_close(int fd, void *arg);
/** The IO polling object - it keeps a one-shot list of monitored IOs. */
static fio_poll_s *monitor;
/* facil.io delays signal callbacks so they can safely with no restrictions. */
FIO_SFUNC void on_signal(int sig, void *udata);
/* *****************************************************************************
Starting the program - main()
***************************************************************************** */
int main(int argc, char const *argv[]) {
/* initialize the CLI options */
int srv_fd;
fio_cli_start(argc,
argv,
0, /* allow 1 unnamed argument - the address to connect to */
1,
"A simple HTTP \"hello world\" example, listening on the "
"specified URL. i.e.\n"
"\tNAME <url>\n\n"
"Unix socket examples:\n"
"\tNAME unix://./my.sock\n"
"\tNAME /full/path/to/my.sock\n"
"\nTCP/IP socket examples:\n"
"\tNAME tcp://localhost:3000/\n"
"\tNAME localhost://3000\n",
FIO_CLI_BOOL("--verbose -V -d print out debugging messages."),
FIO_CLI_PRINT_LINE(
"NOTE: requests are limited to 32Kb and 16 headers each."));
/* review CLI for logging */
if (fio_cli_get_bool("-V")) {
FIO_LOG_LEVEL = FIO_LOG_LEVEL_DEBUG;
}
/* review CLI connection address (in URL format) */
const char *url = fio_cli_unnamed(0);
if (!url)
url = "0.0.0.0:3000";
size_t url_len = strlen(url);
FIO_ASSERT(url_len < 1024, "URL address too long");
fio_url_s a = fio_url_parse(url, url_len);
if (!a.host.buf && !a.port.buf) {
/* Unix Socket */
#if FIO_OS_WIN
FIO_ASSERT(0, "Unix style sockets are unsupported on Windows.");
#else
srv_fd = fio_sock_open(a.path.buf,
NULL,
FIO_SOCK_UNIX | FIO_SOCK_SERVER | FIO_SOCK_NONBLOCK);
FIO_LOG_DEBUG("Opened a Unix Socket (%d).", srv_fd);
#endif
} else if (!a.scheme.buf || a.scheme.len != 3 ||
(a.scheme.buf[0] | 32) != 'u' || (a.scheme.buf[1] | 32) != 'd' ||
(a.scheme.buf[2] | 32) != 'p') {
/* TCP/IP Socket */
char buf[1024];
/* copy because we need to add NUL bytes between the address and the port
*/
memcpy(buf, a.host.buf, a.host.len + a.port.len + 2);
buf[a.host.len + a.port.len + 1] = 0;
buf[a.host.len] = 0;
/* open the socket, passing NUL terminated strings for address and port */
srv_fd = fio_sock_open(buf,
buf + a.host.len + 1,
FIO_SOCK_TCP | FIO_SOCK_SERVER | FIO_SOCK_NONBLOCK);
/* log */
FIO_LOG_DEBUG("Opened a TCP/IP Socket (%d) to %s port %s.",
srv_fd,
buf,
buf + a.host.len + 1);
} else {
/* UDP Socket */
FIO_ASSERT(0, "This example doesn't support UDP sockets.");
}
/* we're dome with the CLI, release resources */
fio_cli_end();
/* test socket / connection success */
if (srv_fd == -1) {
FIO_LOG_FATAL("Couldn't open connection");
}
/* select signals to be monitored */
fio_signal_monitor(SIGINT, on_signal, NULL);
fio_signal_monitor(SIGTERM, on_signal, NULL);
#if FIO_OS_POSIX
fio_signal_monitor(SIGQUIT, on_signal, NULL);
#endif
/* select IO objects to be monitored */
monitor = fio_poll_new(.on_data = on_data,
.on_ready = on_ready,
.on_close = on_close);
fio_poll_monitor(monitor, srv_fd, NULL, POLLIN);
FIO_LOG_INFO("Listening for HTTP echo @ %s", url);
/* loop until the stop flag is raised */
while (!server_stop_flag) {
/* review IO events (calls the registered callbacks) */
fio_poll_review(monitor, 1000);
/* review signals (calls the registered callback) */
fio_signal_review();
}
/* cleanup */
fio_poll_close_all(monitor);
fio_poll_free(monitor);
FIO_LOG_INFO("Shutdown complete.");
return 0;
}
/* *****************************************************************************
Signal callback(s)
***************************************************************************** */
/* facil.io delays signal callbacks so they can safely with no restrictions. */
FIO_SFUNC void on_signal(int sig, void *udata) {
/* since there are no restrictions, we can safely print to the log. */
FIO_LOG_INFO("Exit signal %d detected, shutting down.", sig);
/* If the signal repeats, crash. */
if (server_stop_flag)
exit(-1);
server_stop_flag = 1;
(void)sig;
(void)udata;
}
/* *****************************************************************************
IO "Objects"and helpers
***************************************************************************** */
#include "http1_parser.h"
typedef struct {
http1_parser_s parser;
fio_stream_s out;
struct {
char *name;
char *value;
int32_t name_len;
int32_t value_len;
} headers[HTTP_MAX_HEADERS];
char *method;
char *path;
char *body;
int method_len;
int path_len;
int headers_len;
int body_len;
int buf_pos;
int buf_consumed;
int fd;
char buf[]; /* header and data buffer */
} client_s;
/** Sends a "dynamic" HTTP response. */
static void http_send_response(client_s *c,
int status,
fio_str_info_s status_str,
size_t header_count,
fio_str_info_s headers[][2],
fio_str_info_s body);
#if FIO_OS_POSIX /* on POSIX we can take the easy path for constructors. */
#define FIO_MEMORY_NAME fio_client_memory_allocator
#define FIO_REF_NAME client
#define FIO_REF_CONSTRUCTOR_ONLY
#define FIO_REF_FLEX_TYPE char
#define FIO_REF_DESTROY(obj) \
do { \
fio_stream_destroy(&(obj).out); \
} while (0)
#include "fio-stl.h"
#else /* on Windows the reference counter is not yet supported... so: */
FIO_IFUNC client_s *client_new(size_t len) {
client_s *c = malloc(sizeof(*c) + len);
FIO_ASSERT_ALLOC(c);
memset(c, 0, sizeof(*c));
return c;
}
FIO_IFUNC void client_free(client_s *c) {
if (!c)
return;
fio_stream_destroy(&c->out);
free(c);
}
#endif
/* *****************************************************************************
IO callback(s)
***************************************************************************** */
/** Called when the socket have available space in the outgoing buffer. */
FIO_SFUNC void on_ready(int fd, void *arg) {
if (!arg)
return;
client_s *c = arg;
char mem[32768];
size_t len = 32768;
/* send as much data as we can until the system buffer is full */
do {
/* set buffer to copy to, in case a copy is performed */
char *buf = mem;
len = 32768;
/* read from the stream, copy might not be required. updates buf and len. */
fio_stream_read(&c->out, &buf, &len);
/* write to the IO object */
if (!len || fio_sock_write(fd, buf, len) <= 0)
goto finish;
/* advance the stream by the amount actually written to the IO (partial?) */
fio_stream_advance(&c->out, len);
/* log */
FIO_LOG_DEBUG2("on_ready send %zu bytes to %d.", len, fd);
} while (len);
finish:
/* if there's data left to write, monitor the outgoing buffer. */
if (fio_stream_any(&c->out))
fio_poll_monitor(monitor, fd, arg, POLLOUT);
}
/** Called there's incoming data (from STDIN / the client socket. */
FIO_SFUNC void on_data(int fd, void *arg) {
client_s *c = arg;
if (!arg)
goto accept_new_connections;
ssize_t r =
fio_sock_read(fd, c->buf + c->buf_pos, HTTP_CLIENT_BUFFER - c->buf_pos);
if (r > 0) {
c->buf_pos += r;
c->buf[c->buf_pos] = 0;
while ((r = http1_parse(&c->parser,
c->buf + c->buf_consumed,
(size_t)(c->buf_pos - c->buf_consumed)))) {
c->buf_consumed += r;
if (!http1_complete(&c->parser))
break;
if (c->buf_consumed == c->buf_pos)
c->buf_pos = c->buf_consumed = 0;
else {
c->buf_pos = c->buf_pos - c->buf_consumed;
memmove(c->buf, c->buf + c->buf_consumed, c->buf_pos);
c->buf_consumed = 0;
}
}
}
/* remember to reschedule event monitoring (one-shot by design) */
fio_poll_monitor(monitor, fd, arg, POLLIN);
return;
accept_new_connections : {
/* accept is a macro for fio_sock_accept, which int Windows safe. */
int cl = accept(fd, NULL, NULL);
if (cl == -1)
goto accept_error;
fio_sock_set_non_block(cl);
c = client_new(HTTP_CLIENT_BUFFER + 1);
c->fd = cl;
client_free(fio_poll_forget(monitor, cl)); /* if on_close wasn't called. */
fio_poll_monitor(monitor, cl, c, POLLIN | POLLOUT);
/* remember to reschedule event monitoring (one-shot by design) */
fio_poll_monitor(monitor, fd, NULL, POLLIN);
return;
}
accept_error:
FIO_LOG_ERROR("Couldn't accept connection? %s", strerror(errno));
/* remember to reschedule event monitoring (one-shot by design) */
fio_poll_monitor(monitor, fd, NULL, POLLIN);
}
/** Called when the monitored IO is closed or has a fatal error. */
FIO_SFUNC void on_close(int fd, void *arg) {
fio_sock_close(fd);
if (arg) {
client_free(arg);
} else {
FIO_LOG_DEBUG2("on_close callback called for %d, stopping.", fd);
server_stop_flag = 1;
}
}
/* *****************************************************************************
HTTP/1.1 callback(s)
***************************************************************************** */
/** called when a request was received. */
static int http1_on_request(http1_parser_s *parser) {
client_s *c = (client_s *)parser;
#ifdef HTTP_RESPONSE_ECHO
http_send_response(c,
200,
(fio_str_info_s){"OK", 2},
0,
NULL,
(fio_str_info_s){c->method, strlen(c->method)});
#elif HTTP_RESPONSE_DYNAMIC
http_send_response(c,
200,
(fio_str_info_s){"OK", 2},
0,
NULL,
(fio_str_info_s){"Hello World!", 12});
#else
char *response =
"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World!\n";
fio_stream_add(&c->out,
fio_stream_pack_data(response, strlen(response), 0, 0, NULL));
(void)http_send_response; /* unused in this branch */
#endif
/* reset client request data */
c->method = NULL;
c->path = NULL;
c->body = NULL;
c->method_len = 0;
c->path_len = 0;
c->headers_len = 0;
c->body_len = 0;
fio_poll_monitor(monitor, c->fd, c, POLLOUT);
return 0;
}
/** called when a response was received. */
static int http1_on_response(http1_parser_s *parser) {
(void)parser;
FIO_LOG_ERROR("response receieved instead of a request. Silently ignored.");
return -1;
}
/** called when a request method is parsed. */
static int http1_on_method(http1_parser_s *parser,
char *method,
size_t method_len) {
client_s *c = (client_s *)parser;
c->method = method;
c->method_len = method_len;
return 0;
}
/** called when a response status is parsed. the status_str is the string
* without the prefixed numerical status indicator.*/
static int http1_on_status(http1_parser_s *parser,
size_t status,
char *status_str,
size_t len) {
return -1;
(void)parser;
(void)status;
(void)status_str;
(void)len;
}
/** called when a request path (excluding query) is parsed. */
static int http1_on_path(http1_parser_s *parser, char *path, size_t path_len) {
client_s *c = (client_s *)parser;
c->path = path;
c->path_len = path_len;
return 0;
}
/** called when a request path (excluding query) is parsed. */
static int http1_on_query(http1_parser_s *parser,
char *query,
size_t query_len) {
return 0;
(void)parser;
(void)query;
(void)query_len;
}
/** called when a the HTTP/1.x version is parsed. */
static int http1_on_version(http1_parser_s *parser, char *version, size_t len) {
return 0;
(void)parser;
(void)version;
(void)len;
}
/** called when a header is parsed. */
static int http1_on_header(http1_parser_s *parser,
char *name,
size_t name_len,
char *value,
size_t value_len) {
client_s *c = (client_s *)parser;
if (c->headers_len >= HTTP_MAX_HEADERS)
return -1;
c->headers[c->headers_len].name = name;
c->headers[c->headers_len].name_len = name_len;
c->headers[c->headers_len].value = value;
c->headers[c->headers_len].value_len = value_len;
++c->headers_len;
return 0;
}
/** called when a body chunk is parsed. */
static int http1_on_body_chunk(http1_parser_s *parser,
char *data,
size_t data_len) {
if (parser->state.content_length >= HTTP_CLIENT_BUFFER)
return -1;
client_s *c = (client_s *)parser;
if (!c->body)
c->body = data;
c->body_len += data_len;
return 0;
}
/** called when a protocol error occurred. */
static int http1_on_error(http1_parser_s *parser) {
client_s *c = (client_s *)parser;
fio_sock_close(c->fd);
c->fd = -1;
return -1;
}
/* *****************************************************************************
HTTP/1.1 response authorship helper
***************************************************************************** */
static char http_date_buf[128];
static size_t http_date_len;
static time_t http_date_tm;
static void http_send_response(client_s *c,
int status,
fio_str_info_s status_str,
size_t header_count,
fio_str_info_s headers[][2],
fio_str_info_s body) {
struct timespec tm = fio_time_real();
if (http_date_tm != tm.tv_sec) {
http_date_len = fio_time2rfc7231(http_date_buf, tm.tv_sec);
http_date_tm = tm.tv_sec;
}
size_t total_len = 9 + 4 + 15 + 20 /* max content length */ + 2 +
status_str.len + 2 + http_date_len + 5 + 7 + 2 + body.len;
for (size_t i = 0; i < header_count; ++i) {
total_len += headers[i][0].len + 1 + headers[i][1].len + 2;
}
if (status < 100 || status > 999)
status = 500;
str_s *response = str_new();
str_reserve(response, total_len);
str_write(response, "HTTP/1.1 ", 9);
str_write_i(response, status);
str_write(response, " ", 1);
str_write(response, status_str.buf, status_str.len);
str_write(response, "\r\nContent-Length:", 17);
str_write_i(response, body.len);
str_write(response, "\r\nDate: ", 8);
str_write(response, http_date_buf, http_date_len);
str_write(response, "\r\n", 2);
for (size_t i = 0; i < header_count; ++i) {
str_write(response, headers[i][0].buf, headers[i][0].len);
str_write(response, ":", 1);
str_write(response, headers[i][1].buf, headers[i][1].len);
str_write(response, "\r\n", 2);
}
fio_str_info_s final = str_write(response, "\r\n", 2);
if (body.len && body.buf)
final = str_write(response, body.buf, body.len);
fio_stream_add(
&c->out,
fio_stream_pack_data(response,
final.len,
((uintptr_t) final.buf) - (uintptr_t)response,
0,
(void (*)(void *))str_free));
FIO_LOG_DEBUG2("Sending response %d, %zu bytes", status, final.len);
}
|
janbiedermann/cstl
|
stl_slices/299 reference counter.h
|
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#define FIO_REF_NAME long_ref /* Development inclusion - ignore line */
#define FIO_REF_TYPE long /* Development inclusion - ignore line */
#include "000 header.h" /* Development inclusion - ignore line */
#include "003 atomics.h" /* Development inclusion - ignore line */
#include "100 mem.h" /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
Reference Counting / Wrapper
(must be placed after all type macros)
***************************************************************************** */
#ifdef FIO_REF_NAME
#ifndef fio_atomic_add
#error FIO_REF_NAME requires enabling the FIO_ATOMIC extension.
#endif
#ifndef FIO_REF_TYPE
#define FIO_REF_TYPE FIO_NAME(FIO_REF_NAME, s)
#endif
#ifndef FIO_REF_INIT
#define FIO_REF_INIT(obj) \
do { \
(obj) = (FIO_REF_TYPE){0}; \
} while (0)
#endif
#ifndef FIO_REF_DESTROY
#define FIO_REF_DESTROY(obj)
#endif
#ifndef FIO_REF_METADATA_INIT
#ifdef FIO_REF_METADATA
#define FIO_REF_METADATA_INIT(meta) \
do { \
(meta) = (FIO_REF_METADATA){0}; \
} while (0)
#else
#define FIO_REF_METADATA_INIT(meta)
#endif
#endif
#ifndef FIO_REF_METADATA_DESTROY
#define FIO_REF_METADATA_DESTROY(meta)
#endif
/**
* FIO_REF_CONSTRUCTOR_ONLY allows the reference counter constructor (TYPE_new)
* to be the only constructor function.
*
* When set, the reference counting functions will use `X_new` and `X_free`.
* Otherwise (assuming `X_new` and `X_free` are already defined), the reference
* counter will define `X_new2` and `X_free2` instead.
*/
#ifdef FIO_REF_CONSTRUCTOR_ONLY
#define FIO_REF_CONSTRUCTOR new
#define FIO_REF_DESTRUCTOR free
#define FIO_REF_DUPNAME dup
#else
#define FIO_REF_CONSTRUCTOR new2
#define FIO_REF_DESTRUCTOR free2
#define FIO_REF_DUPNAME dup2
#endif
typedef struct {
volatile size_t ref;
#ifdef FIO_REF_METADATA
FIO_REF_METADATA metadata;
#endif
} FIO_NAME(FIO_REF_NAME, _wrapper_s);
#ifdef FIO_PTR_TAG_TYPE
#define FIO_REF_TYPE_PTR FIO_PTR_TAG_TYPE
#else
#define FIO_REF_TYPE_PTR FIO_REF_TYPE *
#endif
/* *****************************************************************************
Reference Counter (Wrapper) API
***************************************************************************** */
/** Allocates a reference counted object. */
#ifdef FIO_REF_FLEX_TYPE
IFUNC FIO_REF_TYPE_PTR FIO_NAME(FIO_REF_NAME,
FIO_REF_CONSTRUCTOR)(size_t members);
#else
IFUNC FIO_REF_TYPE_PTR FIO_NAME(FIO_REF_NAME, FIO_REF_CONSTRUCTOR)(void);
#endif /* FIO_REF_FLEX_TYPE */
/** Increases the reference count. */
IFUNC FIO_REF_TYPE_PTR FIO_NAME(FIO_REF_NAME,
FIO_REF_DUPNAME)(FIO_REF_TYPE_PTR wrapped);
/**
* Frees a reference counted object (or decreases the reference count).
*
* Returns 1 if the object was actually freed, returns 0 otherwise.
*/
IFUNC int FIO_NAME(FIO_REF_NAME, FIO_REF_DESTRUCTOR)(FIO_REF_TYPE_PTR wrapped);
#ifdef FIO_REF_METADATA
/** Returns a pointer to the object's metadata, if defined. */
IFUNC FIO_REF_METADATA *FIO_NAME(FIO_REF_NAME,
metadata)(FIO_REF_TYPE_PTR wrapped);
#endif
/* *****************************************************************************
Reference Counter (Wrapper) Implementation
***************************************************************************** */
#ifdef FIO_EXTERN_COMPLETE
#if defined(DEBUG) || defined(FIO_LEAK_COUNTER)
static size_t FIO_NAME(FIO_REF_NAME, ___leak_tester);
#define FIO_REF_ON_ALLOC() \
fio_atomic_add(&FIO_NAME(FIO_REF_NAME, ___leak_tester), 1)
#define FIO_REF_ON_FREE() \
fio_atomic_sub(&FIO_NAME(FIO_REF_NAME, ___leak_tester), 1)
static void __attribute__((destructor))
FIO_NAME(FIO_REF_NAME, ___leak_test)(void) {
if (FIO_NAME(FIO_REF_NAME, ___leak_tester)) {
FIO_LOG_ERROR(
"(" FIO_MACRO2STR(FIO_REF_NAME) "):\n "
"%zd memory leak(s) detected for "
"type: " FIO_MACRO2STR(FIO_REF_TYPE),
FIO_NAME(FIO_REF_NAME, ___leak_tester));
}
}
#else
#define FIO_REF_ON_ALLOC()
#define FIO_REF_ON_FREE()
#endif /* defined(DEBUG) || defined(FIO_LEAK_COUNTER) */
/** Allocates a reference counted object. */
#ifdef FIO_REF_FLEX_TYPE
IFUNC FIO_REF_TYPE_PTR FIO_NAME(FIO_REF_NAME,
FIO_REF_CONSTRUCTOR)(size_t members) {
FIO_NAME(FIO_REF_NAME, _wrapper_s) *o =
(FIO_NAME(FIO_REF_NAME, _wrapper_s) *)FIO_MEM_REALLOC_(
NULL,
0,
sizeof(*o) + sizeof(FIO_REF_TYPE) +
(sizeof(FIO_REF_FLEX_TYPE) * members),
0);
#else
IFUNC FIO_REF_TYPE_PTR FIO_NAME(FIO_REF_NAME, FIO_REF_CONSTRUCTOR)(void) {
FIO_NAME(FIO_REF_NAME, _wrapper_s) *o = (FIO_NAME(FIO_REF_NAME, _wrapper_s) *)
FIO_MEM_REALLOC_(NULL, 0, sizeof(*o) + sizeof(FIO_REF_TYPE), 0);
#endif /* FIO_REF_FLEX_TYPE */
if (!o)
return (FIO_REF_TYPE_PTR)(o);
FIO_REF_ON_ALLOC();
o->ref = 1;
FIO_REF_METADATA_INIT((o->metadata));
FIO_REF_TYPE *ret = (FIO_REF_TYPE *)(o + 1);
FIO_REF_INIT((ret[0]));
return (FIO_REF_TYPE_PTR)(FIO_PTR_TAG(ret));
}
/** Increases the reference count. */
IFUNC FIO_REF_TYPE_PTR FIO_NAME(FIO_REF_NAME,
FIO_REF_DUPNAME)(FIO_REF_TYPE_PTR wrapped_) {
FIO_REF_TYPE *wrapped = (FIO_REF_TYPE *)(FIO_PTR_UNTAG(wrapped_));
FIO_NAME(FIO_REF_NAME, _wrapper_s) *o =
((FIO_NAME(FIO_REF_NAME, _wrapper_s) *)wrapped) - 1;
fio_atomic_add(&o->ref, 1);
return wrapped_;
}
/** Frees a reference counted object (or decreases the reference count). */
IFUNC int FIO_NAME(FIO_REF_NAME,
FIO_REF_DESTRUCTOR)(FIO_REF_TYPE_PTR wrapped_) {
FIO_REF_TYPE *wrapped = (FIO_REF_TYPE *)(FIO_PTR_UNTAG(wrapped_));
if (!wrapped || !wrapped_)
return -1;
FIO_NAME(FIO_REF_NAME, _wrapper_s) *o =
((FIO_NAME(FIO_REF_NAME, _wrapper_s) *)wrapped) - 1;
if (!o)
return -1;
if (fio_atomic_sub_fetch(&o->ref, 1))
return 0;
FIO_REF_DESTROY((wrapped[0]));
FIO_REF_METADATA_DESTROY((o->metadata));
FIO_MEM_FREE_(o, sizeof(*o) + sizeof(FIO_REF_TYPE));
FIO_REF_ON_FREE();
return 1;
}
#ifdef FIO_REF_METADATA
/** Returns a pointer to the object's metadata, if defined. */
IFUNC FIO_REF_METADATA *FIO_NAME(FIO_REF_NAME,
metadata)(FIO_REF_TYPE_PTR wrapped_) {
FIO_REF_TYPE *wrapped = (FIO_REF_TYPE *)(FIO_PTR_UNTAG(wrapped_));
FIO_NAME(FIO_REF_NAME, _wrapper_s) *o =
((FIO_NAME(FIO_REF_NAME, _wrapper_s) *)wrapped) - 1;
return &o->metadata;
}
#endif
/* *****************************************************************************
Reference Counter (Wrapper) Cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE */
#undef FIO_REF_NAME
#undef FIO_REF_FLEX_TYPE
#undef FIO_REF_TYPE
#undef FIO_REF_INIT
#undef FIO_REF_DESTROY
#undef FIO_REF_METADATA
#undef FIO_REF_METADATA_INIT
#undef FIO_REF_METADATA_DESTROY
#undef FIO_REF_TYPE_PTR
#undef FIO_REF_CONSTRUCTOR_ONLY
#undef FIO_REF_CONSTRUCTOR
#undef FIO_REF_DUPNAME
#undef FIO_REF_DESTRUCTOR
#endif
|
janbiedermann/cstl
|
stl_slices/211 unordered map.h
|
<filename>stl_slices/211 unordered map.h
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#define FIO_UMAP_NAME map /* Development inclusion - ignore line */
#include "004 bitwise.h" /* Development inclusion - ignore line */
#include "100 mem.h" /* Development inclusion - ignore line */
#include "210 map api.h" /* Development inclusion - ignore line */
#define FIO_MAP_TEST /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
Unordered Map - an Unordered Hash Map / Set
***************************************************************************** */
#if defined(FIO_MAP_NAME) && !FIO_MAP_ORDERED
/* *****************************************************************************
Unordered Map Types - Implementation
TODO?
Benchmark: https://tessil.github.io/2016/08/29/benchmark-hopscotch-map.html
***************************************************************************** */
/** An Unordered Map Type */
struct FIO_NAME(FIO_MAP_NAME, s) {
/** Internal map / memory - do not access directly */
FIO_NAME(FIO_MAP_NAME, each_s) * map;
/** Object count - do not access directly */
FIO_MAP_SIZE_TYPE count;
#if FIO_MAP_EVICT_LRU
/** LRU evicion monitoring - do not access directly */
FIO_MAP_SIZE_TYPE last_used;
#endif /* FIO_MAP_EVICT_LRU */
uint8_t bits;
uint8_t under_attack;
};
/* *****************************************************************************
Unordered Map Implementation - inlined static functions
***************************************************************************** */
#ifndef FIO_MAP_CAPA
#define FIO_MAP_CAPA(bits) ((uintptr_t)1ULL << (bits))
#endif
/* do we have a constructor? */
#ifndef FIO_REF_CONSTRUCTOR_ONLY
/* Allocates a new object on the heap and initializes it's memory. */
FIO_IFUNC FIO_MAP_PTR FIO_NAME(FIO_MAP_NAME, new)(void) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_MEM_REALLOC_(NULL, 0, sizeof(*m), 0);
if (!m)
return (FIO_MAP_PTR)NULL;
*m = (FIO_NAME(FIO_MAP_NAME, s))FIO_MAP_INIT;
return (FIO_MAP_PTR)FIO_PTR_TAG(m);
}
/* Frees any internal data AND the object's container! */
FIO_IFUNC int FIO_NAME(FIO_MAP_NAME, free)(FIO_MAP_PTR map) {
FIO_PTR_TAG_VALID_OR_RETURN(map, 0);
FIO_NAME(FIO_MAP_NAME, destroy)(map);
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
FIO_MEM_FREE_(m, sizeof(*m));
return 0;
}
#endif /* FIO_REF_CONSTRUCTOR_ONLY */
/** IInternal helper - do not access */
FIO_IFUNC uint8_t *FIO_NAME(FIO_MAP_NAME,
__imap)(FIO_NAME(FIO_MAP_NAME, s) * m) {
return (uint8_t *)(m->map + FIO_MAP_CAPA(m->bits));
}
FIO_IFUNC size_t FIO_NAME(FIO_MAP_NAME, count)(FIO_MAP_PTR map) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return 0;
FIO_PTR_TAG_VALID_OR_RETURN(map, 0);
return m->count;
}
FIO_IFUNC size_t FIO_NAME(FIO_MAP_NAME, capa)(FIO_MAP_PTR map) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return 0;
FIO_PTR_TAG_VALID_OR_RETURN(map, 0);
return FIO_MAP_CAPA(m->bits);
}
FIO_IFUNC FIO_NAME(FIO_MAP_NAME, each_s) *
FIO_NAME(FIO_MAP_NAME, each_next)(FIO_MAP_PTR map,
FIO_NAME(FIO_MAP_NAME, each_s) * *first,
FIO_NAME(FIO_MAP_NAME, each_s) * pos) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m || !first)
return NULL;
FIO_PTR_TAG_VALID_OR_RETURN(map, NULL);
if (!m->count || !m->map)
return NULL;
size_t i;
#if FIO_MAP_EVICT_LRU
FIO_MAP_SIZE_TYPE next;
if (!pos) {
i = m->last_used;
*first = m->map;
return m->map + i;
}
i = pos - *first;
*first = m->map; /* was it updated? */
next = m->map[i].node.next;
if (next == m->last_used)
return NULL;
return m->map + next;
#else /*FIO_MAP_EVICT_LRU*/
if (!pos || !(*first)) {
i = -1;
} else {
i = pos - *first;
}
++i;
*first = m->map;
uint8_t *imap = FIO_NAME(FIO_MAP_NAME, __imap)(m);
while (i + 8 < FIO_MAP_CAPA(m->bits)) {
/* test only groups with valid values (test for all bytes == 0 || 255 */
register uint64_t row = fio_buf2u64_local(imap + i);
row = (fio_has_full_byte64(row) | fio_has_zero_byte64(row));
if (row != UINT64_C(0x8080808080808080)) {
row ^= UINT64_C(0x8080808080808080);
for (int j = 0; j < 8; ++j) {
if ((row & UINT64_C(0x80))) {
return m->map + i + j;
}
row >>= 8;
}
i += 8;
}
}
while (i < FIO_MAP_CAPA(m->bits)) {
if (imap[i] && imap[i] != 255)
return m->map + i;
++i;
}
return NULL;
#endif /* FIO_MAP_EVICT_LRU */
}
/* *****************************************************************************
Unordered Map Implementation - possibly externed functions.
***************************************************************************** */
#ifdef FIO_EXTERN_COMPLETE
#ifndef FIO_MAP_MEMORY_SIZE
#define FIO_MAP_MEMORY_SIZE(bits) \
((sizeof(FIO_NAME(FIO_MAP_NAME, each_s)) + sizeof(uint8_t)) * \
FIO_MAP_CAPA(bits))
#endif
/* *****************************************************************************
Unordered Map Implementation - helper functions.
***************************************************************************** */
#ifndef FIO_MAP___IMAP_DELETED
#define FIO_MAP___IMAP_DELETED 255
#endif
#ifndef FIO_MAP___IMAP_FREE
#define FIO_MAP___IMAP_FREE 0
#endif
FIO_IFUNC FIO_MAP_SIZE_TYPE FIO_NAME(FIO_MAP_NAME,
__hash2imap)(FIO_MAP_HASH hash,
uint8_t bits) {
FIO_MAP_SIZE_TYPE r = (((hash >> bits) ^ hash) & 255);
if (!r || r == 255)
r ^= 1;
return r;
}
FIO_SFUNC FIO_MAP_SIZE_TYPE FIO_NAME(FIO_MAP_NAME,
__index)(FIO_NAME(FIO_MAP_NAME, s) * m,
const FIO_MAP_HASH hash,
FIO_MAP_OBJ_KEY key) {
FIO_MAP_SIZE_TYPE pos = (FIO_MAP_SIZE_TYPE)-1LL;
FIO_MAP_SIZE_TYPE free_slot = (FIO_MAP_SIZE_TYPE)-1LL;
size_t total_collisions = 0;
if (!m->map)
return pos;
const uint8_t *imap = FIO_NAME(FIO_MAP_NAME, __imap)(m);
/* note: hash MUST be normalized by this point */
const uint64_t simd_base =
FIO_NAME(FIO_MAP_NAME, __hash2imap)(hash, m->bits) *
UINT64_C(0x0101010101010101);
const FIO_MAP_SIZE_TYPE pos_mask = FIO_MAP_CAPA(m->bits) - 1;
const int max_attempts = (FIO_MAP_CAPA(m->bits) >> 3) >= FIO_MAP_MAX_SEEK
? (int)FIO_MAP_MAX_SEEK
: (FIO_MAP_CAPA(m->bits) >> 3);
if (m->bits <= FIO_MAP_SEEK_AS_ARRAY_LOG_LIMIT)
goto seek_as_array;
/* we perrform X attempts using large cuckoo steps */
pos = hash;
for (int attempts = 0; attempts < max_attempts;
(++attempts), (pos += FIO_MAP_CUCKOO_STEPS)) {
/* each attempt test a group of 8 slots spaced by a few bytes (comb) */
const uint8_t offsets[] = {0, 3, 7, 12, 18, 25, 33, 41};
const uint64_t comb =
(uint64_t)imap[(pos + offsets[0]) & pos_mask] |
((uint64_t)imap[(pos + offsets[1]) & pos_mask] << (1 * 8)) |
((uint64_t)imap[(pos + offsets[2]) & pos_mask] << (2 * 8)) |
((uint64_t)imap[(pos + offsets[3]) & pos_mask] << (3 * 8)) |
((uint64_t)imap[(pos + offsets[4]) & pos_mask] << (4 * 8)) |
((uint64_t)imap[(pos + offsets[5]) & pos_mask] << (5 * 8)) |
((uint64_t)imap[(pos + offsets[6]) & pos_mask] << (6 * 8)) |
((uint64_t)imap[(pos + offsets[7]) & pos_mask] << (7 * 8));
uint64_t simd_result = simd_base ^ comb;
simd_result = fio_has_zero_byte64(simd_result);
/* test for exact match in each of the bytes in the 8 byte group */
/* note: the MSB is 1 for both (x-1) and (~x) only if x == 0. */
if (simd_result) {
for (int i = 0; simd_result; ++i) {
/* test cache friendly 8bit match */
if ((simd_result & UINT64_C(0x80))) {
/* test full hash */
register FIO_MAP_HASH obj_hash =
FIO_MAP_HASH_GET_HASH(m, ((pos + offsets[i]) & pos_mask));
if (obj_hash == hash) {
/* test full collisions (attack) / match */
if (m->under_attack ||
FIO_MAP_OBJ_KEY_CMP(m->map[(pos + offsets[i]) & pos_mask].obj,
key)) {
pos = (pos + offsets[i]) & pos_mask;
return pos;
} else if (++total_collisions >= FIO_MAP_MAX_FULL_COLLISIONS) {
m->under_attack = 1;
FIO_LOG_SECURITY("Unordered map under attack?");
}
}
}
simd_result >>= 8;
}
}
/* test if there's an available slot in the group */
if (free_slot == (FIO_MAP_SIZE_TYPE)-1LL &&
(simd_result =
(fio_has_zero_byte64(comb) | fio_has_full_byte64(comb)))) {
for (int i = 0; simd_result; ++i) {
if (simd_result & UINT64_C(0x80)) {
free_slot = (pos + offsets[i]) & pos_mask;
break;
}
simd_result >>= 8;
}
}
/* test if there's a free slot in the group (never used => stop seeking) */
/* note: the MSB is 1 for both (x-1) and (~x) only if x == 0. */
if (fio_has_zero_byte64(comb))
break;
}
pos = free_slot;
return pos;
seek_as_array:
if (m->count < FIO_MAP_CAPA(m->bits))
free_slot = m->count;
pos = 0;
while (pos < m->count) {
switch (imap[pos]) {
case 0:
return pos;
case 255:
if (free_slot > pos)
free_slot = pos;
break;
default:
if (imap[pos] == (uint8_t)(simd_base & 0xFF)) {
FIO_MAP_HASH obj_hash = FIO_MAP_HASH_GET_HASH(m, pos);
if (obj_hash == hash) {
/* test full collisions (attack) / match */
if (m->under_attack || FIO_MAP_OBJ_KEY_CMP(m->map[pos].obj, key)) {
return pos;
} else if (++total_collisions >= FIO_MAP_MAX_FULL_COLLISIONS) {
m->under_attack = 1;
FIO_LOG_SECURITY("Unordered map under attack?");
}
}
}
}
++pos;
}
pos = free_slot;
return pos;
(void)key; /* if unused */
}
FIO_IFUNC int FIO_NAME(FIO_MAP_NAME, __realloc)(FIO_NAME(FIO_MAP_NAME, s) * m,
size_t bits) {
if (!m || bits >= (sizeof(FIO_MAP_SIZE_TYPE) * 8))
return -1;
FIO_NAME(FIO_MAP_NAME, each_s) *tmp = (FIO_NAME(FIO_MAP_NAME, each_s) *)
FIO_MEM_REALLOC_(NULL, 0, FIO_MAP_MEMORY_SIZE(bits), 0);
if (!tmp)
return -1;
if (!FIO_MEM_REALLOC_IS_SAFE_)
memset(tmp, 0, FIO_MAP_MEMORY_SIZE(bits));
/* rehash the map */
FIO_NAME(FIO_MAP_NAME, s) m2;
m2 = (FIO_NAME(FIO_MAP_NAME, s)){
.map = tmp,
.bits = (uint8_t)bits,
};
if (m->count) {
#if FIO_MAP_EVICT_LRU
/* use eviction list to re-insert data. */
FIO_MAP_SIZE_TYPE last = 0;
FIO_INDEXED_LIST_EACH(m->map, node, m->last_used, i) {
/* place old values in new hash */
FIO_MAP_HASH obj_hash = FIO_MAP_HASH_GET_HASH(m, i);
FIO_MAP_SIZE_TYPE pos =
FIO_NAME(FIO_MAP_NAME,
__index)(&m2, obj_hash, FIO_MAP_OBJ2KEY(m->map[i].obj));
if (pos == (FIO_MAP_SIZE_TYPE)-1)
goto error;
FIO_NAME(FIO_MAP_NAME, __imap)
(&m2)[pos] = FIO_NAME(FIO_MAP_NAME, __hash2imap)(obj_hash, m2.bits);
#if FIO_MAP_HASH_CACHED
m2.map[pos].hash = obj_hash;
#endif /* FIO_MAP_HASH_CACHED */
m2.map[pos].obj = m->map[i].obj;
if (m2.count) {
FIO_INDEXED_LIST_PUSH(m2.map, node, last, pos);
} else {
m2.map[pos].node.prev = m2.map[pos].node.next = pos;
m2.last_used = pos;
}
last = pos;
++m2.count;
}
#else /* FIO_MAP_EVICT_LRU */
/* scan map for used slots to re-insert data */
if (FIO_MAP_CAPA(m->bits) > 8) {
uint64_t *imap64 = (uint64_t *)FIO_NAME(FIO_MAP_NAME, __imap)(m);
for (FIO_MAP_SIZE_TYPE i = 0;
m2.count < m->count && i < FIO_MAP_CAPA(m->bits);
i += 8) {
/* skip empty groups (test for all bytes == 0) (can we test == 255?) */
uint64_t result = (fio_has_zero_byte64(imap64[(i >> 3)]) |
fio_has_full_byte64(imap64[(i >> 3)]));
if (result == UINT64_C(0x8080808080808080))
continue;
result ^= UINT64_C(0x8080808080808080);
for (int j = 0; j < 8 && result; ++j) {
const FIO_MAP_SIZE_TYPE n = i + j;
if ((result & UINT64_C(0x80))) {
/* place in new hash */
FIO_MAP_HASH obj_hash = FIO_MAP_HASH_GET_HASH(m, n);
FIO_MAP_SIZE_TYPE pos = FIO_NAME(
FIO_MAP_NAME,
__index)(&m2, obj_hash, FIO_MAP_OBJ2KEY(m->map[n].obj));
if (pos == (FIO_MAP_SIZE_TYPE)-1)
goto error;
FIO_NAME(FIO_MAP_NAME, __imap)
(&m2)[pos] = FIO_NAME(FIO_MAP_NAME, __hash2imap)(obj_hash, m2.bits);
m2.map[pos] = m->map[n];
#if FIO_MAP_EVICT_LRU
if (!m2.count) {
m2.last_used = pos;
m2.map[pos].node.prev = m2.map[pos].node.next = pos;
}
FIO_INDEXED_LIST_PUSH(m2.map, node, m2.last_used, pos);
if (m->last_used == n)
m2.last_used = pos;
#endif /* FIO_MAP_EVICT_LRU */
++m2.count;
}
result >>= 8;
}
}
} else {
for (FIO_MAP_SIZE_TYPE i = 0; m->count && i < FIO_MAP_CAPA(m->bits);
++i) {
if (FIO_NAME(FIO_MAP_NAME, __imap)(m)[i] &&
FIO_NAME(FIO_MAP_NAME, __imap)(m)[i] != 255) {
FIO_MAP_HASH obj_hash = FIO_MAP_HASH_GET_HASH(m, i);
FIO_MAP_SIZE_TYPE pos =
FIO_NAME(FIO_MAP_NAME,
__index)(&m2, obj_hash, FIO_MAP_OBJ2KEY(m->map[i].obj));
if (pos == (FIO_MAP_SIZE_TYPE)-1)
goto error;
FIO_NAME(FIO_MAP_NAME, __imap)
(&m2)[pos] = FIO_NAME(FIO_MAP_NAME, __hash2imap)(obj_hash, m2.bits);
m2.map[pos] = m->map[i];
++m2.count;
}
}
}
#endif /* FIO_MAP_EVICT_LRU */
}
FIO_MEM_FREE_(m->map, FIO_MAP_MEMORY_SIZE(m->bits));
*m = m2;
return 0;
error:
FIO_MEM_FREE_(tmp, FIO_MAP_MEMORY_SIZE(bits));
return -1;
}
/* *****************************************************************************
Unordered Map Implementation - API implementation
*****************************************************************************
*/
/* Frees any internal data AND the object's container! */
SFUNC void FIO_NAME(FIO_MAP_NAME, destroy)(FIO_MAP_PTR map) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return;
FIO_PTR_TAG_VALID_OR_RETURN_VOID(map);
FIO_NAME(FIO_MAP_NAME, clear)(map);
FIO_MEM_FREE_(m->map, FIO_MAP_MEMORY_SIZE(m->bits));
*m = (FIO_NAME(FIO_MAP_NAME, s))FIO_MAP_INIT;
return;
}
/* *****************************************************************************
Get / Set / Remove
*****************************************************************************
*/
SFUNC FIO_MAP_TYPE *FIO_NAME(FIO_MAP_NAME, get_ptr)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
FIO_MAP_OBJ_KEY key) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return NULL;
FIO_PTR_TAG_VALID_OR_RETURN(map, NULL);
hash = FIO_MAP_HASH_FIX(hash);
FIO_MAP_SIZE_TYPE pos = FIO_NAME(FIO_MAP_NAME, __index)(m, hash, key);
if (pos == (FIO_MAP_SIZE_TYPE)(-1) ||
FIO_NAME(FIO_MAP_NAME, __imap)(m)[pos] == 255 ||
!FIO_NAME(FIO_MAP_NAME, __imap)(m)[pos])
return NULL;
#if FIO_MAP_EVICT_LRU
if (m->last_used != pos) {
FIO_INDEXED_LIST_REMOVE(m->map, node, pos);
FIO_INDEXED_LIST_PUSH(m->map, node, m->last_used, pos);
m->last_used = pos;
}
#endif /* FIO_MAP_EVICT_LRU */
return &FIO_MAP_OBJ2TYPE(m->map[pos].obj);
}
SFUNC FIO_MAP_TYPE *FIO_NAME(FIO_MAP_NAME, set_ptr)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
#ifdef FIO_MAP_KEY
FIO_MAP_KEY key,
#endif /* FIO_MAP_KEY */
FIO_MAP_TYPE obj,
FIO_MAP_TYPE *old,
uint8_t overwrite) {
if (old)
*old = FIO_MAP_TYPE_INVALID;
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return NULL;
FIO_PTR_TAG_VALID_OR_RETURN(map, NULL);
hash = FIO_MAP_HASH_FIX(hash);
#ifdef FIO_MAP_KEY
FIO_MAP_SIZE_TYPE pos = FIO_NAME(FIO_MAP_NAME, __index)(m, hash, key);
#else
FIO_MAP_SIZE_TYPE pos = FIO_NAME(FIO_MAP_NAME, __index)(m, hash, obj);
#endif /* FIO_MAP_KEY */
for (int i = 0; pos == (FIO_MAP_SIZE_TYPE)-1 && i < 2; ++i) {
if (FIO_NAME(FIO_MAP_NAME, __realloc)(m, m->bits + 1))
goto error;
#ifdef FIO_MAP_KEY
pos = FIO_NAME(FIO_MAP_NAME, __index)(m, hash, key);
#else
pos = FIO_NAME(FIO_MAP_NAME, __index)(m, hash, obj);
#endif /* FIO_MAP_KEY */
}
if (pos == (FIO_MAP_SIZE_TYPE)-1)
goto error;
if (!FIO_NAME(FIO_MAP_NAME, __imap)(m)[pos] ||
FIO_NAME(FIO_MAP_NAME, __imap)(m)[pos] == 255) {
/* new */
FIO_NAME(FIO_MAP_NAME, __imap)
(m)[pos] = FIO_NAME(FIO_MAP_NAME, __hash2imap)(hash, m->bits);
#if FIO_MAP_HASH_CACHED
m->map[pos].hash = hash;
#endif
FIO_MAP_TYPE_COPY(FIO_MAP_OBJ2TYPE(m->map[pos].obj), obj);
FIO_MAP_KEY_COPY(FIO_MAP_OBJ2KEY(m->map[pos].obj), key);
#if FIO_MAP_EVICT_LRU
if (m->count) {
FIO_INDEXED_LIST_PUSH(m->map, node, m->last_used, pos);
} else {
m->map[pos].node.prev = m->map[pos].node.next = pos;
}
m->last_used = pos;
#endif /* FIO_MAP_EVICT_LRU */
++m->count;
} else if (overwrite &&
FIO_MAP_SHOULD_OVERWRITE(FIO_MAP_OBJ2TYPE(m->map[pos].obj), obj)) {
/* overwrite existing */
FIO_MAP_KEY_DISCARD(key);
if (old) {
FIO_MAP_TYPE_COPY(old[0], FIO_MAP_OBJ2TYPE(m->map[pos].obj));
if (FIO_MAP_DESTROY_AFTER_COPY) {
FIO_MAP_TYPE_DESTROY(FIO_MAP_OBJ2TYPE(m->map[pos].obj));
}
} else {
FIO_MAP_TYPE_DESTROY(FIO_MAP_OBJ2TYPE(m->map[pos].obj));
}
FIO_MAP_TYPE_COPY(FIO_MAP_OBJ2TYPE(m->map[pos].obj), obj);
#if FIO_MAP_EVICT_LRU
if (m->last_used != pos) {
FIO_INDEXED_LIST_REMOVE(m->map, node, pos);
FIO_INDEXED_LIST_PUSH(m->map, node, m->last_used, pos);
m->last_used = pos;
}
#endif /* FIO_MAP_EVICT_LRU */
} else {
FIO_MAP_TYPE_DISCARD(obj);
FIO_MAP_KEY_DISCARD(key);
}
return &FIO_MAP_OBJ2TYPE(m->map[pos].obj);
error:
FIO_MAP_TYPE_DISCARD(obj);
FIO_MAP_KEY_DISCARD(key);
return NULL;
}
SFUNC int FIO_NAME(FIO_MAP_NAME, remove)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
FIO_MAP_OBJ_KEY key,
FIO_MAP_TYPE *old) {
if (old)
*old = FIO_MAP_TYPE_INVALID;
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m || !m->count)
return -1;
FIO_PTR_TAG_VALID_OR_RETURN(map, NULL);
hash = FIO_MAP_HASH_FIX(hash);
FIO_MAP_SIZE_TYPE pos = FIO_NAME(FIO_MAP_NAME, __index)(m, hash, key);
if (pos == (FIO_MAP_SIZE_TYPE)(-1) ||
FIO_NAME(FIO_MAP_NAME, __imap)(m)[pos] == 255 ||
!FIO_NAME(FIO_MAP_NAME, __imap)(m)[pos])
return -1;
FIO_NAME(FIO_MAP_NAME, __imap)(m)[pos] = 255;
#if FIO_MAP_HASH_CACHED
m->map[pos].hash = 0;
#endif
--m->count;
if (old) {
FIO_MAP_TYPE_COPY(*old, FIO_MAP_OBJ2TYPE(m->map[pos].obj));
FIO_MAP_OBJ_DESTROY_AFTER(m->map[pos].obj);
} else {
FIO_MAP_OBJ_DESTROY(m->map[pos].obj);
}
#if FIO_MAP_EVICT_LRU
if (pos == m->last_used)
m->last_used = m->map[pos].node.next;
FIO_INDEXED_LIST_REMOVE(m->map, node, pos);
#endif
return 0;
}
SFUNC void FIO_NAME(FIO_MAP_NAME, clear)(FIO_MAP_PTR map) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return;
FIO_PTR_TAG_VALID_OR_RETURN_VOID(map);
/* scan map to clear data. */
if (m->bits > 3) {
uint64_t *imap64 = (uint64_t *)FIO_NAME(FIO_MAP_NAME, __imap)(m);
for (FIO_MAP_SIZE_TYPE i = 0; m->count && i < FIO_MAP_CAPA(m->bits);
i += 8) {
/* skip empty groups (test for all bytes == 0 || 255 */
register uint64_t row = imap64[i >> 3];
row = (fio_has_full_byte64(row) | fio_has_zero_byte64(row));
if (row == UINT64_C(0x8080808080808080)) {
imap64[i >> 3] = 0;
continue;
}
imap64[i >> 3] = 0;
row ^= UINT64_C(0x8080808080808080);
for (int j = 0; j < 8; ++j) {
if ((row & UINT64_C(0x80))) {
FIO_MAP_OBJ_DESTROY(m->map[i + j].obj);
#if FIO_MAP_HASH_CACHED
m->map[i + j].hash = 0;
#endif
--m->count; /* stop seeking if no more elements */
}
row >>= 8;
}
}
} else {
for (FIO_MAP_SIZE_TYPE i = 0; m->count && i < FIO_MAP_CAPA(m->bits); ++i) {
if (FIO_NAME(FIO_MAP_NAME, __imap)(m)[i] &&
FIO_NAME(FIO_MAP_NAME, __imap)(m)[i] != 255) {
FIO_MAP_OBJ_DESTROY(m->map[i].obj);
--m->count;
}
}
}
FIO_ASSERT_DEBUG(!m->count, "logic error @ unordered map clear.");
}
SFUNC int FIO_NAME(FIO_MAP_NAME, evict)(FIO_MAP_PTR map,
size_t number_of_elements) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return -1;
FIO_PTR_TAG_VALID_OR_RETURN(map, -1);
if (!m->count)
return -1;
if (number_of_elements >= m->count) {
FIO_NAME(FIO_MAP_NAME, clear)(map);
return -1;
}
#if FIO_MAP_EVICT_LRU
/* evict by LRU */
do {
FIO_MAP_SIZE_TYPE n = m->map[m->last_used].node.prev;
FIO_INDEXED_LIST_REMOVE(m->map, node, n);
} while (--number_of_elements);
#else /* FIO_MAP_EVICT_LRU */
/* scan map and evict semi randomly. */
uint64_t *imap64 = (uint64_t *)FIO_NAME(FIO_MAP_NAME, __imap)(m);
for (FIO_MAP_SIZE_TYPE i = 0;
number_of_elements && (i + 7) < FIO_MAP_CAPA(m->bits);
i += 8) {
/* skip empty groups (test for all bytes == 0 || 255 */
register uint64_t row = imap64[i >> 3];
row = (fio_has_full_byte64(row) | fio_has_zero_byte64(row));
if (row == UINT64_C(0x8080808080808080))
continue;
row ^= UINT64_C(0x8080808080808080);
for (int j = 0; number_of_elements && j < 8; ++j) {
if ((row & UINT64_C(0x80))) {
FIO_MAP_OBJ_DESTROY(m->map[i + j].obj);
#if FIO_MAP_HASH_CACHED
m->map[i + j].hash = 0;
#endif
FIO_NAME(FIO_MAP_NAME, __imap)(m)[i + j] = 255;
--m->count;
--number_of_elements; /* stop evicting? */
}
row >>= 8;
}
}
#endif /* FIO_MAP_EVICT_LRU */
return -1;
}
/* *****************************************************************************
Object state information
*****************************************************************************
*/
/** Reservse enough space for a theoretical capacity of `capa` objects. */
SFUNC size_t FIO_NAME(FIO_MAP_NAME, reserve)(FIO_MAP_PTR map,
FIO_MAP_SIZE_TYPE capa) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return 0;
FIO_PTR_TAG_VALID_OR_RETURN(map, 0);
if (FIO_MAP_CAPA(m->bits) < capa) {
size_t bits = 3;
while (FIO_MAP_CAPA(bits) < capa)
++bits;
for (int i = 0; FIO_NAME(FIO_MAP_NAME, __realloc)(m, bits + i) && i < 2;
++i) {
}
if (m->bits < bits)
return 0;
}
return FIO_MAP_CAPA(m->bits);
}
/** Attempts to minimize memory use. */
SFUNC void FIO_NAME(FIO_MAP_NAME, compact)(FIO_MAP_PTR map) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return;
FIO_PTR_TAG_VALID_OR_RETURN_VOID(map);
if (!m->bits)
return;
if (!m->count) {
FIO_NAME(FIO_MAP_NAME, destroy)(map);
return;
}
size_t bits = m->bits;
size_t count = 0;
while (bits && FIO_MAP_CAPA((bits - 1)) > m->count) {
--bits;
++count;
}
for (size_t i = 0; i < count; ++i) {
if (!FIO_NAME(FIO_MAP_NAME, __realloc)(m, bits + i))
return;
}
}
/** Rehashes the map. No need to call this, rehashing is automatic. */
SFUNC int FIO_NAME(FIO_MAP_NAME, rehash)(FIO_MAP_PTR map) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return -1;
FIO_PTR_TAG_VALID_OR_RETURN(map, -1);
return FIO_NAME(FIO_MAP_NAME, __realloc)(m, m->bits);
}
/* *****************************************************************************
Iteration
*****************************************************************************
*/
FIO_SFUNC __thread FIO_MAP_SIZE_TYPE FIO_NAME(FIO_MAP_NAME, __each_pos) = 0;
FIO_SFUNC __thread FIO_NAME(FIO_MAP_NAME, s) *
FIO_NAME(FIO_MAP_NAME, __each_map) = NULL;
SFUNC FIO_MAP_SIZE_TYPE FIO_NAME(FIO_MAP_NAME,
each)(FIO_MAP_PTR map,
ssize_t start_at,
int (*task)(FIO_MAP_TYPE obj, void *arg),
void *arg) {
FIO_MAP_SIZE_TYPE count = (FIO_MAP_SIZE_TYPE)start_at;
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return 0;
FIO_PTR_TAG_VALID_OR_RETURN(map, 0);
if (!m->count)
return 0;
if (start_at < 0) {
start_at = m->count + start_at;
if (start_at < 0)
start_at = 0;
}
if ((FIO_MAP_SIZE_TYPE)start_at >= m->count)
return m->count;
FIO_NAME(FIO_MAP_NAME, s) *old_map = FIO_NAME(FIO_MAP_NAME, __each_map);
FIO_MAP_SIZE_TYPE old_pos = FIO_NAME(FIO_MAP_NAME, __each_pos);
FIO_NAME(FIO_MAP_NAME, __each_pos) = 0;
FIO_NAME(FIO_MAP_NAME, __each_map) = m;
#if FIO_MAP_EVICT_LRU
if (start_at) {
FIO_INDEXED_LIST_EACH(m->map, node, m->last_used, pos) {
++count;
if (start_at) {
--start_at;
continue;
}
FIO_NAME(FIO_MAP_NAME, __each_pos) = pos;
if (task(FIO_MAP_OBJ2TYPE(m->map[pos].obj), arg) == -1)
goto finish;
}
} else {
FIO_INDEXED_LIST_EACH(m->map, node, m->last_used, pos) {
++count;
FIO_NAME(FIO_MAP_NAME, __each_pos) = pos;
if (task(FIO_MAP_OBJ2TYPE(m->map[pos].obj), arg) == -1)
goto finish;
}
}
#else /* FIO_MAP_EVICT_LRU */
uint8_t *imap = FIO_NAME(FIO_MAP_NAME, __imap)(m);
FIO_MAP_SIZE_TYPE pos = 0;
if (start_at) {
uint64_t *imap64 = (uint64_t *)FIO_NAME(FIO_MAP_NAME, __imap)(m);
/* scan map to arrive at starting point. */
for (FIO_MAP_SIZE_TYPE i = 0; start_at && i < FIO_MAP_CAPA(m->bits);
i += 8) {
/* skip empty groups (test for all bytes == 0 || 255 */
register uint64_t row = imap64[i >> 3];
row = (fio_has_full_byte64(row) | fio_has_zero_byte64(row));
if (row == UINT64_C(0x8080808080808080))
continue;
row ^= UINT64_C(0x8080808080808080);
for (int j = 0; start_at && j < 8; ++j) {
if ((row & UINT64_C(0x80))) {
pos = i + j;
--start_at;
}
row >>= 8;
}
}
}
while (pos + 8 < FIO_MAP_CAPA(m->bits)) {
/* test only groups with valid values (test for all bytes == 0 || 255 */
register uint64_t row = fio_buf2u64_local(imap + pos);
row = (fio_has_full_byte64(row) | fio_has_zero_byte64(row));
if (row != UINT64_C(0x8080808080808080)) {
row ^= UINT64_C(0x8080808080808080);
for (int j = 0; j < 8; ++j) {
if ((row & UINT64_C(0xFF))) {
FIO_NAME(FIO_MAP_NAME, __each_pos) = pos + j;
++count;
if (task(FIO_MAP_OBJ2TYPE(
m->map[FIO_NAME(FIO_MAP_NAME, __each_pos)].obj),
arg) == -1)
goto finish;
}
row >>= 8;
}
}
pos += 8;
}
while (pos < FIO_MAP_CAPA(m->bits)) {
if (FIO_NAME(FIO_MAP_NAME, __imap)(m)[pos] &&
FIO_NAME(FIO_MAP_NAME, __imap)(m)[pos] != 255) {
FIO_NAME(FIO_MAP_NAME, __each_pos) = pos;
++count;
if (task(FIO_MAP_OBJ2TYPE(m->map[FIO_NAME(FIO_MAP_NAME, __each_pos)].obj),
arg) == -1)
goto finish;
}
++pos;
}
#endif /* FIO_MAP_EVICT_LRU */
finish:
FIO_NAME(FIO_MAP_NAME, __each_pos) = old_pos;
FIO_NAME(FIO_MAP_NAME, __each_map) = old_map;
return count;
}
#ifdef FIO_MAP_KEY
SFUNC FIO_MAP_KEY FIO_NAME(FIO_MAP_NAME, each_get_key)(void) {
if (!FIO_NAME(FIO_MAP_NAME, __each_map) ||
!FIO_NAME(FIO_MAP_NAME, __each_map)->count)
return FIO_MAP_KEY_INVALID;
return FIO_NAME(FIO_MAP_NAME, __each_map)
->map[FIO_NAME(FIO_MAP_NAME, __each_pos)]
.obj.key;
}
#else
SFUNC FIO_MAP_HASH FIO_NAME(FIO_MAP_NAME, each_get_key)(void) {
#if FIO_MAP_HASH_CACHED
if (!FIO_NAME(FIO_MAP_NAME, __each_map) ||
!FIO_NAME(FIO_MAP_NAME, __each_map)->count)
return 0;
return FIO_NAME(FIO_MAP_NAME, __each_map)
->map[FIO_NAME(FIO_MAP_NAME, __each_pos)]
.hash;
#else
return 0;
#endif
}
#endif
/* *****************************************************************************
Unordered Map Cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE */
#endif /* FIO_MAP_NAME */
|
janbiedermann/cstl
|
tests/base64.c
|
#define FIO_STR_NAME fio_str
#define FIO_CLI
#define FIO_SOCK
#include "fio-stl.h"
FIO_IFUNC fio_str_info_s fio_str_write_base64enc2(fio_str_s *s,
const void *data,
size_t len) {
return fio_str_write_base64enc(s, data, len, fio_cli_get_bool("-u"));
}
int main(int argc, char const *argv[]) {
fio_cli_start(
argc,
argv,
0,
-1,
"Decode / Encode Base64 from stdin to stdout",
FIO_CLI_STRING(
"--file -f a filename to encode / decode (instead of stdin)."),
FIO_CLI_BOOL("--decode -d run the program in decoding mode instead of "
"encoding mode."),
FIO_CLI_BOOL("--url -u when (if) encoding, use URL mode."),
FIO_CLI_PRINT_HEADER("Notes:"),
FIO_CLI_PRINT_LINE(
"When running NAME in the terminal with manual input, use "
"^D (ctrl+D) to end session."),
FIO_CLI_PRINT_HEADER("Examples:"),
FIO_CLI_PRINT("NAME Hello World"),
FIO_CLI_PRINT("NAME -f my_file.txt > my_file.base64"),
FIO_CLI_PRINT("NAME -d -f my_file.base64 > my_file.txt"),
FIO_CLI_PRINT("NAME -f my_file.base64 > file.txt"),
FIO_CLI_PRINT("echo \"SGVsbG8gV29ybGQ=\" | NAME -d"),
FIO_CLI_PRINT("NAME -d SGVsbG8gV29ybGQ="));
fio_str_s out = FIO_STR_INIT;
;
fio_str_info_s (*fn)(fio_str_s *, const void *, size_t) =
fio_str_write_base64enc2;
if (fio_cli_get_bool("-d"))
fn = fio_str_write_base64dec;
int fd = fileno(stdin);
/* process Base64 as arguments */
if (fio_cli_unnamed_count()) {
for (size_t i = 0; i < fio_cli_unnamed_count(); ++i) {
const char *str = fio_cli_unnamed(i);
size_t len = strlen(str);
fn(&out, str, len);
fio_str_write(&out, "\n", 1);
}
fprintf(stdout, "%s", fio_str2ptr(&out));
fio_str_resize(&out, 0);
/* don't process stdio */
if (!fio_cli_get("-f"))
goto finish;
}
/* process Base64 as file */
if (fio_cli_get("-f")) {
fio_str_s in = FIO_STR_INIT;
if (fio_str_readfile(&in, fio_cli_get("-f"), 0, 0).buf) {
fn(&out, fio_str2ptr(&in), fio_str_len(&in));
fio_str_destroy(&in);
fprintf(stdout, "%s\n", fio_str2ptr(&out));
fio_str_resize(&out, 0);
} else {
fprintf(stderr, "Couldn't load file: %s\n", fio_cli_get("-f"));
}
/* don't process stdio */
goto finish;
}
fflush(stdout);
/* process Base64 from STDIN */
while (!feof(stdin)) {
char buffer[960];
ssize_t l = read(fd, buffer, 960);
if (l <= 0)
break;
if (l && buffer[l - 1] == '\n')
--l;
if (l && buffer[l - 1] == '\r')
--l;
if (l)
fn(&out, buffer, l);
if (fio_str_len(&out)) {
if (l < 960)
fprintf(stdout, "%s\n", fio_str2ptr(&out));
else
fprintf(stdout, "%s", fio_str2ptr(&out));
}
fio_str_resize(&out, 0);
fflush(stdout);
}
finish:
fprintf(stderr, "\n");
fio_cli_end();
fio_str_destroy(&out);
return 0;
}
|
janbiedermann/cstl
|
stl_slices/200 linked lists.h
|
<reponame>janbiedermann/cstl<filename>stl_slices/200 linked lists.h<gh_stars>10-100
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#include "000 header.h" /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
Linked Lists (embeded)
Example:
```c
// initial `include` defines the `FIO_LIST_NODE` macro and type
#include "fio-stl.h"
// list element
typedef struct {
long l;
FIO_LIST_NODE node;
int i;
double d;
} my_list_s;
// create linked list helper functions
#define FIO_LIST_NAME my_list
#include "fio-stl.h"
void example(void) {
FIO_LIST_HEAD FIO_LIST_INIT(list);
for (int i = 0; i < 10; ++i) {
my_list_s *n = malloc(sizeof(*n));
n->i = i;
my_list_push(&list, n);
}
int i = 0;
while (my_list_any(&list)) {
my_list_s *n = my_list_shift(&list);
if (i != n->i) {
fprintf(stderr, "list error - value mismatch\n"), exit(-1);
}
free(n);
++i;
}
if (i != 10) {
fprintf(stderr, "list error - count error\n"), exit(-1);
}
}
```
***************************************************************************** */
/* *****************************************************************************
Linked Lists (embeded) - Type
***************************************************************************** */
#if defined(FIO_LIST_NAME)
#ifndef FIO_LIST_TYPE
/** Name of the list type and function prefix, defaults to FIO_LIST_NAME_s */
#define FIO_LIST_TYPE FIO_NAME(FIO_LIST_NAME, s)
#endif
#ifndef FIO_LIST_NODE_NAME
/** List types must contain at least one node element, defaults to `node`. */
#define FIO_LIST_NODE_NAME node
#endif
#ifdef FIO_PTR_TAG_TYPE
#define FIO_LIST_TYPE_PTR FIO_PTR_TAG_TYPE
#else
#define FIO_LIST_TYPE_PTR FIO_LIST_TYPE *
#endif
/* *****************************************************************************
Linked Lists (embeded) - API
***************************************************************************** */
/** Initialize FIO_LIST_HEAD objects - already defined. */
/* FIO_LIST_INIT(obj) */
/** Returns a non-zero value if there are any linked nodes in the list. */
IFUNC int FIO_NAME(FIO_LIST_NAME, any)(const FIO_LIST_HEAD *head);
/** Returns a non-zero value if the list is empty. */
IFUNC int FIO_NAME_BL(FIO_LIST_NAME, empty)(const FIO_LIST_HEAD *head);
/** Removes a node from the list, Returns NULL if node isn't linked. */
IFUNC FIO_LIST_TYPE_PTR FIO_NAME(FIO_LIST_NAME, remove)(FIO_LIST_TYPE_PTR node);
/** Pushes an existing node to the end of the list. Returns node. */
IFUNC FIO_LIST_TYPE_PTR FIO_NAME(FIO_LIST_NAME,
push)(FIO_LIST_HEAD *restrict head,
FIO_LIST_TYPE_PTR restrict node);
/** Pops a node from the end of the list. Returns NULL if list is empty. */
IFUNC FIO_LIST_TYPE_PTR FIO_NAME(FIO_LIST_NAME, pop)(FIO_LIST_HEAD *head);
/** Adds an existing node to the beginning of the list. Returns node. */
IFUNC FIO_LIST_TYPE_PTR FIO_NAME(FIO_LIST_NAME,
unshift)(FIO_LIST_HEAD *restrict head,
FIO_LIST_TYPE_PTR restrict node);
/** Removed a node from the start of the list. Returns NULL if list is empty. */
IFUNC FIO_LIST_TYPE_PTR FIO_NAME(FIO_LIST_NAME, shift)(FIO_LIST_HEAD *head);
/** Returns a pointer to a list's element, from a pointer to a node. */
IFUNC FIO_LIST_TYPE_PTR FIO_NAME(FIO_LIST_NAME, root)(FIO_LIST_HEAD *ptr);
/* *****************************************************************************
Linked Lists (embeded) - Implementation
***************************************************************************** */
#ifdef FIO_EXTERN_COMPLETE
/** Returns a non-zero value if there are any linked nodes in the list. */
IFUNC int FIO_NAME(FIO_LIST_NAME, any)(const FIO_LIST_HEAD *head) {
FIO_PTR_TAG_VALID_OR_RETURN(head, 0);
head = (FIO_LIST_HEAD *)(FIO_PTR_UNTAG(head));
return head->next != head;
}
/** Returns a non-zero value if the list is empty. */
IFUNC int FIO_NAME_BL(FIO_LIST_NAME, empty)(const FIO_LIST_HEAD *head) {
FIO_PTR_TAG_VALID_OR_RETURN(head, 0);
head = (FIO_LIST_HEAD *)(FIO_PTR_UNTAG(head));
return head->next == head;
}
/** Removes a node from the list, always returning the node. */
IFUNC FIO_LIST_TYPE_PTR FIO_NAME(FIO_LIST_NAME,
remove)(FIO_LIST_TYPE_PTR node_) {
FIO_PTR_TAG_VALID_OR_RETURN(node_, (FIO_LIST_TYPE_PTR)0);
FIO_LIST_TYPE *node = (FIO_LIST_TYPE *)(FIO_PTR_UNTAG(node_));
if (node->FIO_LIST_NODE_NAME.next == &node->FIO_LIST_NODE_NAME)
return NULL;
node->FIO_LIST_NODE_NAME.prev->next = node->FIO_LIST_NODE_NAME.next;
node->FIO_LIST_NODE_NAME.next->prev = node->FIO_LIST_NODE_NAME.prev;
node->FIO_LIST_NODE_NAME.next = node->FIO_LIST_NODE_NAME.prev =
&node->FIO_LIST_NODE_NAME;
return node_;
}
/** Pushes an existing node to the end of the list. Returns node or NULL. */
IFUNC FIO_LIST_TYPE_PTR FIO_NAME(FIO_LIST_NAME,
push)(FIO_LIST_HEAD *restrict head,
FIO_LIST_TYPE_PTR restrict node_) {
FIO_PTR_TAG_VALID_OR_RETURN(head, (FIO_LIST_TYPE_PTR)NULL);
FIO_PTR_TAG_VALID_OR_RETURN(node_, (FIO_LIST_TYPE_PTR)NULL);
head = (FIO_LIST_HEAD *)(FIO_PTR_UNTAG(head));
FIO_LIST_TYPE *restrict node = (FIO_LIST_TYPE *)(FIO_PTR_UNTAG(node_));
node->FIO_LIST_NODE_NAME.prev = head->prev;
node->FIO_LIST_NODE_NAME.next = head;
head->prev->next = &node->FIO_LIST_NODE_NAME;
head->prev = &node->FIO_LIST_NODE_NAME;
return node_;
}
/** Pops a node from the end of the list. Returns NULL if list is empty. */
IFUNC FIO_LIST_TYPE_PTR FIO_NAME(FIO_LIST_NAME, pop)(FIO_LIST_HEAD *head) {
FIO_PTR_TAG_VALID_OR_RETURN(head, (FIO_LIST_TYPE_PTR)NULL);
head = (FIO_LIST_HEAD *)(FIO_PTR_UNTAG(head));
return FIO_NAME(FIO_LIST_NAME, remove)(
FIO_PTR_FROM_FIELD(FIO_LIST_TYPE, FIO_LIST_NODE_NAME, head->prev));
}
/** Adds an existing node to the beginning of the list. Returns node or NULL. */
IFUNC FIO_LIST_TYPE_PTR FIO_NAME(FIO_LIST_NAME,
unshift)(FIO_LIST_HEAD *restrict head,
FIO_LIST_TYPE_PTR restrict node) {
FIO_PTR_TAG_VALID_OR_RETURN(head, (FIO_LIST_TYPE_PTR)NULL);
FIO_PTR_TAG_VALID_OR_RETURN(node, (FIO_LIST_TYPE_PTR)NULL);
head = (FIO_LIST_HEAD *)(FIO_PTR_UNTAG(head));
return FIO_NAME(FIO_LIST_NAME, push)(head->next, node);
}
/** Removed a node from the start of the list. Returns NULL if list is empty. */
IFUNC FIO_LIST_TYPE_PTR FIO_NAME(FIO_LIST_NAME, shift)(FIO_LIST_HEAD *head) {
FIO_PTR_TAG_VALID_OR_RETURN(head, (FIO_LIST_TYPE_PTR)NULL);
head = (FIO_LIST_HEAD *)(FIO_PTR_UNTAG(head));
return FIO_NAME(FIO_LIST_NAME, remove)(
FIO_PTR_FROM_FIELD(FIO_LIST_TYPE, FIO_LIST_NODE_NAME, head->next));
}
/** Removed a node from the start of the list. Returns NULL if list is empty. */
IFUNC FIO_LIST_TYPE_PTR FIO_NAME(FIO_LIST_NAME, root)(FIO_LIST_HEAD *ptr) {
FIO_PTR_TAG_VALID_OR_RETURN(ptr, (FIO_LIST_TYPE_PTR)NULL);
ptr = (FIO_LIST_HEAD *)(FIO_PTR_UNTAG(ptr));
return FIO_PTR_FROM_FIELD(FIO_LIST_TYPE, FIO_LIST_NODE_NAME, ptr);
}
/* *****************************************************************************
Linked Lists (embeded) - cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE */
#undef FIO_LIST_NAME
#undef FIO_LIST_TYPE
#undef FIO_LIST_NODE_NAME
#undef FIO_LIST_TYPE_PTR
#endif
|
janbiedermann/cstl
|
stl_slices/106 signals.h
|
<filename>stl_slices/106 signals.h
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#define FIO_ATOMIC /* Development inclusion - ignore line */
#define FIO_SIGNAL /* Development inclusion - ignore line */
#include "000 header.h" /* Development inclusion - ignore line */
#include "003 atomics.h" /* Development inclusion - ignore line */
#include "100 mem.h" /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
Signal Monitoring
***************************************************************************** */
#if defined(FIO_SIGNAL) && !defined(H___FIO_SIGNAL___H)
#define H___FIO_SIGNAL___H
#ifndef FIO_SIGNAL_MONITOR_MAX
/* The maximum number of signals the implementation will be able to monitor */
#define FIO_SIGNAL_MONITOR_MAX 24
#endif
#if !(FIO_OS_POSIX) && !(FIO_OS_WIN) /* use FIO_HAVE_UNIX_TOOLS instead? */
#error Either POSIX or Windows are required for the fio_signal API.
#endif
#include <signal.h>
/* *****************************************************************************
Signal Monitoring API
***************************************************************************** */
/**
* Starts to monitor for the specified signal, setting an optional callback.
*/
SFUNC int fio_signal_monitor(int sig,
void (*callback)(int sig, void *),
void *udata);
/** Reviews all signals, calling any relevant callbacks. */
SFUNC int fio_signal_review(void);
/** Stops monitoring the specified signal. */
SFUNC int fio_signal_forget(int sig);
/* *****************************************************************************
Signal Monitoring Implementation
***************************************************************************** */
/* *****************************************************************************
Signal Monitoring Implementation - possibly externed functions.
***************************************************************************** */
#ifdef FIO_EXTERN_COMPLETE
/* *****************************************************************************
POSIX implementation
***************************************************************************** */
#ifdef FIO_OS_POSIX
static struct {
int32_t sig;
volatile int32_t flag;
void (*callback)(int sig, void *);
void *udata;
struct sigaction old;
} fio___signal_watchers[FIO_SIGNAL_MONITOR_MAX];
FIO_SFUNC void fio___signal_catcher(int sig) {
for (size_t i = 0; i < FIO_SIGNAL_MONITOR_MAX; ++i) {
if (!fio___signal_watchers[i].sig && !fio___signal_watchers[i].udata)
return; /* initialized list is finishe */
if (fio___signal_watchers[i].sig != sig)
continue;
/* mark flag */
fio_atomic_exchange(&fio___signal_watchers[i].flag, 1);
/* pass-through if exists */
if (fio___signal_watchers[i].old.sa_handler != SIG_IGN &&
fio___signal_watchers[i].old.sa_handler != SIG_DFL)
fio___signal_watchers[i].old.sa_handler(sig);
return;
}
}
/**
* Starts to monitor for the specified signal, setting an optional callback.
*/
SFUNC int fio_signal_monitor(int sig,
void (*callback)(int sig, void *),
void *udata) {
if (!sig)
return -1;
for (size_t i = 0; i < FIO_SIGNAL_MONITOR_MAX; ++i) {
/* updating an existing monitor */
if (fio___signal_watchers[i].sig == sig) {
fio___signal_watchers[i].callback = callback;
fio___signal_watchers[i].udata = udata;
return 0;
}
/* slot busy */
if (fio___signal_watchers[i].sig || fio___signal_watchers[i].callback)
continue;
/* place monitor in this slot */
struct sigaction act;
memset(&act, 0, sizeof(act));
memset(fio___signal_watchers + i, 0, sizeof(fio___signal_watchers[i]));
fio___signal_watchers[i].sig = sig;
fio___signal_watchers[i].callback = callback;
fio___signal_watchers[i].udata = udata;
act.sa_handler = fio___signal_catcher;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_RESTART | SA_NOCLDSTOP;
if (sigaction(sig, &act, &fio___signal_watchers[i].old)) {
FIO_LOG_ERROR("couldn't set signal handler: %s", strerror(errno));
fio___signal_watchers[i].callback = NULL;
fio___signal_watchers[i].udata = (void *)1;
fio___signal_watchers[i].sig = 0;
return -1;
}
return 0;
}
return -1;
}
/** Stops monitoring the specified signal. */
SFUNC int fio_signal_forget(int sig) {
if (!sig)
return -1;
for (size_t i = 0; i < FIO_SIGNAL_MONITOR_MAX; ++i) {
if (!fio___signal_watchers[i].sig && !fio___signal_watchers[i].udata)
return -1; /* initialized list is finishe */
if (fio___signal_watchers[i].sig != sig)
continue;
fio___signal_watchers[i].callback = NULL;
fio___signal_watchers[i].udata = (void *)1;
fio___signal_watchers[i].sig = 0;
struct sigaction act;
memset(&act, 0, sizeof(act));
if (sigaction(sig, &fio___signal_watchers[i].old, &act)) {
FIO_LOG_ERROR("couldn't unset signal handler: %s", strerror(errno));
return -1;
}
return 0;
}
return -1;
}
/* *****************************************************************************
Windows Implementation
***************************************************************************** */
#elif FIO_OS_WIN
static struct {
int32_t sig;
volatile int32_t flag;
void (*callback)(int sig, void *);
void *udata;
void (*old)(int sig);
} fio___signal_watchers[FIO_SIGNAL_MONITOR_MAX];
FIO_SFUNC void fio___signal_catcher(int sig) {
for (size_t i = 0; i < FIO_SIGNAL_MONITOR_MAX; ++i) {
if (!fio___signal_watchers[i].sig && !fio___signal_watchers[i].udata)
return; /* initialized list is finished */
if (fio___signal_watchers[i].sig != sig)
continue;
/* mark flag */
fio___signal_watchers[i].flag = 1;
/* pass-through if exists */
if (fio___signal_watchers[i].old &&
(intptr_t)fio___signal_watchers[i].old != (intptr_t)SIG_IGN &&
(intptr_t)fio___signal_watchers[i].old != (intptr_t)SIG_DFL) {
fio___signal_watchers[i].old(sig);
fio___signal_watchers[i].old = signal(sig, fio___signal_catcher);
} else {
fio___signal_watchers[i].old = signal(sig, fio___signal_catcher);
}
break;
}
}
/**
* Starts to monitor for the specified signal, setting an optional callback.
*/
SFUNC int fio_signal_monitor(int sig,
void (*callback)(int sig, void *),
void *udata) {
if (!sig)
return -1;
for (size_t i = 0; i < FIO_SIGNAL_MONITOR_MAX; ++i) {
/* updating an existing monitor */
if (fio___signal_watchers[i].sig == sig) {
fio___signal_watchers[i].callback = callback;
fio___signal_watchers[i].udata = udata;
return 0;
}
/* slot busy */
if (fio___signal_watchers[i].sig || fio___signal_watchers[i].callback)
continue;
/* place monitor in this slot */
fio___signal_watchers[i].sig = sig;
fio___signal_watchers[i].callback = callback;
fio___signal_watchers[i].udata = udata;
fio___signal_watchers[i].old = signal(sig, fio___signal_catcher);
if ((intptr_t)SIG_ERR == (intptr_t)fio___signal_watchers[i].old) {
fio___signal_watchers[i].sig = 0;
fio___signal_watchers[i].callback = NULL;
fio___signal_watchers[i].udata = (void *)1;
fio___signal_watchers[i].old = NULL;
FIO_LOG_ERROR("couldn't set signal handler: %s", strerror(errno));
return -1;
}
return 0;
}
return -1;
}
/** Stops monitoring the specified signal. */
SFUNC int fio_signal_forget(int sig) {
if (!sig)
return -1;
for (size_t i = 0; i < FIO_SIGNAL_MONITOR_MAX; ++i) {
if (!fio___signal_watchers[i].sig && !fio___signal_watchers[i].udata)
return -1; /* initialized list is finished */
if (fio___signal_watchers[i].sig != sig)
continue;
fio___signal_watchers[i].callback = NULL;
fio___signal_watchers[i].udata = (void *)1;
fio___signal_watchers[i].sig = 0;
if (fio___signal_watchers[i].old) {
if ((intptr_t)signal(sig, fio___signal_watchers[i].old) ==
(intptr_t)SIG_ERR)
goto sig_error;
} else {
if ((intptr_t)signal(sig, SIG_DFL) == (intptr_t)SIG_ERR)
goto sig_error;
}
return 0;
}
return -1;
sig_error:
FIO_LOG_ERROR("couldn't unset signal handler: %s", strerror(errno));
return -1;
}
#endif /* POSIX vs WINDOWS */
/* *****************************************************************************
Common OS implementation
***************************************************************************** */
/** Reviews all signals, calling any relevant callbacks. */
SFUNC int fio_signal_review(void) {
int c = 0;
for (size_t i = 0; i < FIO_SIGNAL_MONITOR_MAX; ++i) {
if (!fio___signal_watchers[i].sig && !fio___signal_watchers[i].udata)
return c;
if (fio___signal_watchers[i].flag) {
fio___signal_watchers[i].flag = 0;
++c;
if (fio___signal_watchers[i].callback)
fio___signal_watchers[i].callback(fio___signal_watchers[i].sig,
fio___signal_watchers[i].udata);
}
}
return c;
}
/* *****************************************************************************
Signal Monitoring Testing?
***************************************************************************** */
#ifdef FIO_TEST_CSTL
FIO_SFUNC void FIO_NAME_TEST(stl, signal)(void) {
#define FIO___SIGNAL_MEMBER(a) \
{ (int)a, #a }
struct {
int sig;
const char *name;
} t[] = {
FIO___SIGNAL_MEMBER(SIGINT),
FIO___SIGNAL_MEMBER(SIGILL),
FIO___SIGNAL_MEMBER(SIGABRT),
FIO___SIGNAL_MEMBER(SIGSEGV),
FIO___SIGNAL_MEMBER(SIGTERM),
#if FIO_OS_POSIX
FIO___SIGNAL_MEMBER(SIGQUIT),
FIO___SIGNAL_MEMBER(SIGHUP),
FIO___SIGNAL_MEMBER(SIGTRAP),
FIO___SIGNAL_MEMBER(SIGBUS),
FIO___SIGNAL_MEMBER(SIGFPE),
FIO___SIGNAL_MEMBER(SIGUSR1),
FIO___SIGNAL_MEMBER(SIGUSR2),
FIO___SIGNAL_MEMBER(SIGPIPE),
FIO___SIGNAL_MEMBER(SIGALRM),
FIO___SIGNAL_MEMBER(SIGCHLD),
FIO___SIGNAL_MEMBER(SIGCONT),
#endif
};
#undef FIO___SIGNAL_MEMBER
size_t e = 0;
fprintf(stderr, "* testing signal monitoring (setup / cleanup only).\n");
for (size_t i = 0; i < sizeof(t) / sizeof(t[0]); ++i) {
if (fio_signal_monitor(t[i].sig, NULL, NULL)) {
FIO_LOG_ERROR("couldn't set signal monitoring for %s (%d)",
t[i].name,
t[i].sig);
e = 1;
}
}
for (size_t i = 0; i < sizeof(t) / sizeof(t[0]); ++i) {
if (fio_signal_forget(t[i].sig)) {
FIO_LOG_ERROR("couldn't stop signal monitoring for %s (%d)",
t[i].name,
t[i].sig);
e = 1;
}
}
FIO_ASSERT(!e, "signal monitoring error");
}
#endif /* FIO_TEST_CSTL */
/* *****************************************************************************
Module Cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE */
#undef FIO_SIGNAL_MONITOR_MAX
#endif /* FIO_SIGNAL */
#undef FIO_SIGNAL
|
janbiedermann/cstl
|
tests/stl.c
|
<reponame>janbiedermann/cstl
#ifndef FIO_TEST_CSTL
#define FIO_TEST_CSTL
#endif
#include "fio-stl.h"
int main(int argc, char const *argv[]) {
fio_test_dynamic_types();
(void)argc;
(void)argv;
return 0;
}
|
janbiedermann/cstl
|
tests/array.c
|
<filename>tests/array.c
#define FIO_LOG
#define FIO_TIME
#include "fio-stl.h"
#define FIO_FIOBJ
#include "fio-stl.h"
#define FIO_ARRAY_NAME ary1
#include "fio-stl.h"
#define FIO_ARRAY_NAME ary2
#define FIO_ARRAY_ENABLE_EMBEDDED 0
#include "fio-stl.h"
#define FIO_ARRAY_NAME ary3
#define FIO_ARRAY_EXPONENTIAL 1
#define FIO_ARRAY_ENABLE_EMBEDDED 0
#include "fio-stl.h"
#define FIO_ARRAY_NAME ary4
#define FIO_ARRAY_ENABLE_EMBEDDED 0
#include "fio-stl.h"
static void *stub_i2v(size_t i) { return (void *)i; }
int main(int argc, char const *argv[]) {
struct {
char *name;
void *(*push)(void *, void *);
int (*pop)(void *, void **);
void (*unshift)(void *, void *);
int (*shift)(void *, void **);
void (*free)(void *);
void *(*new)(void);
void *(*i2v)(size_t);
} t[] = {{
.name = "FIOBJ - tagging, steady growth, embedded",
.push = (void *(*)(void *, void *))fiobj_array_push,
.pop = (int (*)(void *, void **))fiobj_array_pop,
.unshift = (void (*)(void *, void *))fiobj_array_unshift,
.shift = (int (*)(void *, void **))fiobj_array_shift,
.free = (void (*)(void *))fiobj_free,
.new = (void *(*)(void))fiobj_array_new,
.i2v = (void *(*)(size_t))fiobj_num_new,
},
{
.name = "Dynamic - no tagging, steady growth, embedded",
.push = (void *(*)(void *, void *))ary1_push,
.pop = (int (*)(void *, void **))ary1_pop,
.unshift = (void (*)(void *, void *))ary1_unshift,
.shift = (int (*)(void *, void **))ary1_shift,
.free = (void (*)(void *))ary1_free,
.new = (void *(*)(void))ary1_new,
.i2v = stub_i2v,
},
{
.name = "Dynamic - no tagging, steady growth, no embedded",
.push = (void *(*)(void *, void *))ary2_push,
.pop = (int (*)(void *, void **))ary2_pop,
.unshift = (void (*)(void *, void *))ary2_unshift,
.shift = (int (*)(void *, void **))ary2_shift,
.free = (void (*)(void *))ary2_free,
.new = (void *(*)(void))ary2_new,
.i2v = stub_i2v,
},
{
.name = "Dynamic - no tagging, exponential growth, no embedded",
.push = (void *(*)(void *, void *))ary3_push,
.pop = (int (*)(void *, void **))ary3_pop,
.unshift = (void (*)(void *, void *))ary3_unshift,
.shift = (int (*)(void *, void **))ary3_shift,
.free = (void (*)(void *))ary3_free,
.new = (void *(*)(void))ary3_new,
.i2v = stub_i2v,
},
{
.name = NULL,
}};
fprintf(stderr,
"This is a performance test to test the cost of pointer tagging and "
"the embedded array optimizatiion on performance\n");
for (size_t items = 1; items < 64000; items <<= 1) {
fprintf(stderr, "Running push/pop test fo %zu items\n", items);
for (int i = 0; t[i].name; ++i) {
uint64_t start;
uint64_t end;
fprintf(stderr, " * testing %s:\n", t[i].name);
void *a = t[i].new();
start = fio_time_micro();
for (size_t number = 0; number < items; ++number) {
t[i].push(a, t[i].i2v(number));
}
end = fio_time_micro();
fprintf(stderr, "\t - push: %lld us\n", end - start);
start = fio_time_micro();
while (!t[i].pop(a, NULL))
;
end = fio_time_micro();
fprintf(stderr, "\t - pop: %lld us\n", end - start);
t[i].free(a);
a = t[i].new();
start = fio_time_micro();
for (size_t number = 0; number < items; ++number) {
t[i].unshift(a, t[i].i2v(number));
}
end = fio_time_micro();
fprintf(stderr, "\t - unshift: %lld us\n", end - start);
start = fio_time_micro();
while (!t[i].shift(a, NULL))
;
end = fio_time_micro();
fprintf(stderr, "\t - shift: %lld us\n", end - start);
t[i].free(a);
}
}
return 0;
(void)argc;
(void)argv;
}
|
janbiedermann/cstl
|
stl_slices/004 bitwise.h
|
<reponame>janbiedermann/cstl
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#include "000 header.h" /* Development inclusion - ignore line */
#include "003 atomics.h" /* Development inclusion - ignore line */
#define FIO_BITWISE /* Development inclusion - ignore line */
#define FIO_BITMAP /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
Bit-Byte Operations
More joyful ideas at: https://graphics.stanford.edu/~seander/bithacks.html
***************************************************************************** */
#if defined(FIO_BITWISE) && !defined(H___BITWISE___H)
#define H___BITWISE___H
/* *****************************************************************************
Swapping byte's order (`bswap` variations)
***************************************************************************** */
/** Byte swap a 16 bit integer, inlined. */
#if __has_builtin(__builtin_bswap16)
#define fio_bswap16(i) __builtin_bswap16((uint16_t)(i))
#else
FIO_IFUNC uint16_t fio_bswap16(uint16_t i) {
return ((((i)&0xFFU) << 8) | (((i)&0xFF00U) >> 8));
}
#endif
/** Byte swap a 32 bit integer, inlined. */
#if __has_builtin(__builtin_bswap32)
#define fio_bswap32(i) __builtin_bswap32((uint32_t)(i))
#else
FIO_IFUNC uint32_t fio_bswap32(uint32_t i) {
return ((((i)&0xFFUL) << 24) | (((i)&0xFF00UL) << 8) |
(((i)&0xFF0000UL) >> 8) | (((i)&0xFF000000UL) >> 24));
}
#endif
/** Byte swap a 64 bit integer, inlined. */
#if __has_builtin(__builtin_bswap64)
#define fio_bswap64(i) __builtin_bswap64((uint64_t)(i))
#else
FIO_IFUNC uint64_t fio_bswap64(uint64_t i) {
return ((((i)&0xFFULL) << 56) | (((i)&0xFF00ULL) << 40) |
(((i)&0xFF0000ULL) << 24) | (((i)&0xFF000000ULL) << 8) |
(((i)&0xFF00000000ULL) >> 8) | (((i)&0xFF0000000000ULL) >> 24) |
(((i)&0xFF000000000000ULL) >> 40) |
(((i)&0xFF00000000000000ULL) >> 56));
}
#endif
#ifdef __SIZEOF_INT128__
#if __has_builtin(__builtin_bswap128)
#define fio_bswap128(i) __builtin_bswap128((__uint128_t)(i))
#else
FIO_IFUNC __uint128_t fio_bswap128(__uint128_t i) {
return ((__uint128_t)fio_bswap64(i) << 64) | fio_bswap64(i >> 64);
}
#endif
#endif /* __SIZEOF_INT128__ */
/* *****************************************************************************
Big Endian / Small Endian
***************************************************************************** */
#if (defined(__LITTLE_ENDIAN__) && __LITTLE_ENDIAN__) || \
(defined(__BIG_ENDIAN__) && !__BIG_ENDIAN__) || \
(defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
#ifndef __BIG_ENDIAN__
#define __BIG_ENDIAN__ 0
#endif
#ifndef __LITTLE_ENDIAN__
#define __LITTLE_ENDIAN__ 1
#endif
#elif (defined(__BIG_ENDIAN__) && __BIG_ENDIAN__) || \
(defined(__LITTLE_ENDIAN__) && !__LITTLE_ENDIAN__) || \
(defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__))
#ifndef __BIG_ENDIAN__
#define __BIG_ENDIAN__ 1
#endif
#ifndef __LITTLE_ENDIAN__
#define __LITTLE_ENDIAN__ 0
#endif
#elif !defined(__BIG_ENDIAN__) && !defined(__BYTE_ORDER__) && \
!defined(__LITTLE_ENDIAN__)
#define FIO_LITTLE_ENDIAN_TEST 0x31323334UL
#define FIO_BIG_ENDIAN_TEST 0x34333231UL
#define FIO_ENDIAN_ORDER_TEST ('1234')
#if ENDIAN_ORDER_TEST == LITTLE_ENDIAN_TEST
#define __BIG_ENDIAN__ 0
#define __LITTLE_ENDIAN__ 1
#elif ENDIAN_ORDER_TEST == BIG_ENDIAN_TEST
#define __BIG_ENDIAN__ 1
#define __LITTLE_ENDIAN__ 0
#else
#error Could not detect byte order on this system.
#endif
#endif
#if __BIG_ENDIAN__
/** Local byte order to Network byte order, 16 bit integer */
#define fio_lton16(i) (i)
/** Local byte order to Network byte order, 32 bit integer */
#define fio_lton32(i) (i)
/** Local byte order to Network byte order, 62 bit integer */
#define fio_lton64(i) (i)
/** Network byte order to Local byte order, 16 bit integer */
#define fio_ntol16(i) (i)
/** Network byte order to Local byte order, 32 bit integer */
#define fio_ntol32(i) (i)
/** Network byte order to Local byte order, 62 bit integer */
#define fio_ntol64(i) (i)
#ifdef __SIZEOF_INT128__
/** Network byte order to Local byte order, 128 bit integer */
#define fio_ntol128(i) (i)
#endif /* __SIZEOF_INT128__ */
#else /* Little Endian */
/** Local byte order to Network byte order, 16 bit integer */
#define fio_lton16(i) fio_bswap16((i))
/** Local byte order to Network byte order, 32 bit integer */
#define fio_lton32(i) fio_bswap32((i))
/** Local byte order to Network byte order, 62 bit integer */
#define fio_lton64(i) fio_bswap64((i))
/** Network byte order to Local byte order, 16 bit integer */
#define fio_ntol16(i) fio_bswap16((i))
/** Network byte order to Local byte order, 32 bit integer */
#define fio_ntol32(i) fio_bswap32((i))
/** Network byte order to Local byte order, 62 bit integer */
#define fio_ntol64(i) fio_bswap64((i))
#ifdef __SIZEOF_INT128__
/** Local byte order to Network byte order, 128 bit integer */
#define fio_lton128(i) fio_bswap128((i))
/** Network byte order to Local byte order, 128 bit integer */
#define fio_ntol128(i) fio_bswap128((i))
#endif /* __SIZEOF_INT128__ */
#endif /* __BIG_ENDIAN__ */
/* *****************************************************************************
Bit rotation
***************************************************************************** */
/** Left rotation for an unknown size element, inlined. */
#define FIO_LROT(i, bits) \
(((i) << ((bits) & ((sizeof((i)) << 3) - 1))) | \
((i) >> ((-(bits)) & ((sizeof((i)) << 3) - 1))))
/** Right rotation for an unknown size element, inlined. */
#define FIO_RROT(i, bits) \
(((i) >> ((bits) & ((sizeof((i)) << 3) - 1))) | \
((i) << ((-(bits)) & ((sizeof((i)) << 3) - 1))))
#if __has_builtin(__builtin_rotateleft8)
/** 8Bit left rotation, inlined. */
#define fio_lrot8(i, bits) __builtin_rotateleft8(i, bits)
#else
/** 8Bit left rotation, inlined. */
FIO_IFUNC uint8_t fio_lrot8(uint8_t i, uint8_t bits) {
return ((i << (bits & 7UL)) | (i >> ((-(bits)) & 7UL)));
}
#endif
#if __has_builtin(__builtin_rotateleft16)
/** 16Bit left rotation, inlined. */
#define fio_lrot16(i, bits) __builtin_rotateleft16(i, bits)
#else
/** 16Bit left rotation, inlined. */
FIO_IFUNC uint16_t fio_lrot16(uint16_t i, uint8_t bits) {
return ((i << (bits & 15UL)) | (i >> ((-(bits)) & 15UL)));
}
#endif
#if __has_builtin(__builtin_rotateleft32)
/** 32Bit left rotation, inlined. */
#define fio_lrot32(i, bits) __builtin_rotateleft32(i, bits)
#else
/** 32Bit left rotation, inlined. */
FIO_IFUNC uint32_t fio_lrot32(uint32_t i, uint8_t bits) {
return ((i << (bits & 31UL)) | (i >> ((-(bits)) & 31UL)));
}
#endif
#if __has_builtin(__builtin_rotateleft64)
/** 64Bit left rotation, inlined. */
#define fio_lrot64(i, bits) __builtin_rotateleft64(i, bits)
#else
/** 64Bit left rotation, inlined. */
FIO_IFUNC uint64_t fio_lrot64(uint64_t i, uint8_t bits) {
return ((i << ((bits)&63UL)) | (i >> ((-(bits)) & 63UL)));
}
#endif
#if __has_builtin(__builtin_rotatrightt8)
/** 8Bit right rotation, inlined. */
#define fio_rrot8(i, bits) __builtin_rotateright8(i, bits)
#else
/** 8Bit right rotation, inlined. */
FIO_IFUNC uint8_t fio_rrot8(uint8_t i, uint8_t bits) {
return ((i >> (bits & 7UL)) | (i << ((-(bits)) & 7UL)));
}
#endif
#if __has_builtin(__builtin_rotateright16)
/** 16Bit right rotation, inlined. */
#define fio_rrot16(i, bits) __builtin_rotateright16(i, bits)
#else
/** 16Bit right rotation, inlined. */
FIO_IFUNC uint16_t fio_rrot16(uint16_t i, uint8_t bits) {
return ((i >> (bits & 15UL)) | (i << ((-(bits)) & 15UL)));
}
#endif
#if __has_builtin(__builtin_rotateright32)
/** 32Bit right rotation, inlined. */
#define fio_rrot32(i, bits) __builtin_rotateright32(i, bits)
#else
/** 32Bit right rotation, inlined. */
FIO_IFUNC uint32_t fio_rrot32(uint32_t i, uint8_t bits) {
return ((i >> (bits & 31UL)) | (i << ((-(bits)) & 31UL)));
}
#endif
#if __has_builtin(__builtin_rotateright64)
/** 64Bit right rotation, inlined. */
#define fio_rrot64(i, bits) __builtin_rotateright64(i, bits)
#else
/** 64Bit right rotation, inlined. */
FIO_IFUNC uint64_t fio_rrot64(uint64_t i, uint8_t bits) {
return ((i >> ((bits)&63UL)) | (i << ((-(bits)) & 63UL)));
}
#endif
#ifdef __SIZEOF_INT128__
#if __has_builtin(__builtin_rotateright128) && \
__has_builtin(__builtin_rotateleft128)
/** 128Bit left rotation, inlined. */
#define fio_lrot128(i, bits) __builtin_rotateleft128(i, bits)
/** 128Bit right rotation, inlined. */
#define fio_rrot128(i, bits) __builtin_rotateright128(i, bits)
#else
/** 128Bit left rotation, inlined. */
FIO_IFUNC __uint128_t fio_lrot128(__uint128_t i, uint8_t bits) {
return ((i << ((bits)&127UL)) | (i >> ((-(bits)) & 127UL)));
}
/** 128Bit right rotation, inlined. */
FIO_IFUNC __uint128_t fio_rrot128(__uint128_t i, uint8_t bits) {
return ((i >> ((bits)&127UL)) | (i << ((-(bits)) & 127UL)));
}
#endif
#endif /* __SIZEOF_INT128__ */
/* *****************************************************************************
Unaligned memory read / write operations
***************************************************************************** */
#if FIO_UNALIGNED_MEMORY_ACCESS_ENABLED
/** Converts an unaligned byte stream to a 16 bit number (local byte order). */
FIO_IFUNC uint16_t FIO_NAME2(fio_buf, u16_local)(const void *c) {
const uint16_t *tmp = (const uint16_t *)c; /* fio_buf2u16 */
return *tmp;
}
/** Converts an unaligned byte stream to a 32 bit number (local byte order). */
FIO_IFUNC uint32_t FIO_NAME2(fio_buf, u32_local)(const void *c) {
const uint32_t *tmp = (const uint32_t *)c; /* fio_buf2u32 */
return *tmp;
}
/** Converts an unaligned byte stream to a 64 bit number (local byte order). */
FIO_IFUNC uint64_t FIO_NAME2(fio_buf, u64_local)(const void *c) {
const uint64_t *tmp = (const uint64_t *)c; /* fio_buf2u64 */
return *tmp;
}
/** Writes a local 16 bit number to an unaligned buffer. */
FIO_IFUNC void FIO_NAME2(fio_u, buf16_local)(void *buf, uint16_t i) {
*((uint16_t *)buf) = i; /* fio_u2buf16 */
}
/** Writes a local 32 bit number to an unaligned buffer. */
FIO_IFUNC void FIO_NAME2(fio_u, buf32_local)(void *buf, uint32_t i) {
*((uint32_t *)buf) = i; /* fio_u2buf32 */
}
/** Writes a local 64 bit number to an unaligned buffer. */
FIO_IFUNC void FIO_NAME2(fio_u, buf64_local)(void *buf, uint64_t i) {
*((uint64_t *)buf) = i; /* fio_u2buf64 */
}
#ifdef __SIZEOF_INT128__
/** Converts an unaligned byte stream to a 128 bit number (local byte order). */
FIO_IFUNC __uint128_t FIO_NAME2(fio_buf, u128_local)(const void *c) {
const __uint128_t *tmp = (const __uint128_t *)c; /* fio_buf2u64 */
return *tmp;
}
/** Writes a local 128 bit number to an unaligned buffer. */
FIO_IFUNC void FIO_NAME2(fio_u, buf128_local)(void *buf, __uint128_t i) {
*((__uint128_t *)buf) = i; /* fio_u2buf64 */
}
#endif /* __SIZEOF_INT128__ */
#else /* FIO_UNALIGNED_MEMORY_ACCESS_ENABLED */
/** Converts an unaligned byte stream to a 16 bit number (local byte order). */
FIO_IFUNC uint16_t FIO_NAME2(fio_buf, u16_local)(const void *c) {
uint16_t tmp; /* fio_buf2u16 */
FIO_MEMCPY(&tmp, c, sizeof(tmp));
return tmp;
}
/** Converts an unaligned byte stream to a 32 bit number (local byte order). */
FIO_IFUNC uint32_t FIO_NAME2(fio_buf, u32_local)(const void *c) {
uint32_t tmp; /* fio_buf2u32 */
FIO_MEMCPY(&tmp, c, sizeof(tmp));
return tmp;
}
/** Converts an unaligned byte stream to a 64 bit number (local byte order). */
FIO_IFUNC uint64_t FIO_NAME2(fio_buf, u64_local)(const void *c) {
uint64_t tmp; /* fio_buf2u64 */
FIO_MEMCPY(&tmp, c, sizeof(tmp));
return tmp;
}
/** Writes a local 16 bit number to an unaligned buffer. */
FIO_IFUNC void FIO_NAME2(fio_u, buf16_local)(void *buf, uint16_t i) {
FIO_MEMCPY(buf, &i, sizeof(i)); /* fio_u2buf16 */
}
/** Writes a local 32 bit number to an unaligned buffer. */
FIO_IFUNC void FIO_NAME2(fio_u, buf32_local)(void *buf, uint32_t i) {
FIO_MEMCPY(buf, &i, sizeof(i)); /* fio_u2buf32 */
}
/** Writes a local 64 bit number to an unaligned buffer. */
FIO_IFUNC void FIO_NAME2(fio_u, buf64_local)(void *buf, uint64_t i) {
FIO_MEMCPY(buf, &i, sizeof(i)); /* fio_u2buf64 */
}
#ifdef __SIZEOF_INT128__
/** Converts an unaligned byte stream to a 128 bit number (local byte order). */
FIO_IFUNC __uint128_t FIO_NAME2(fio_buf, u128_local)(const void *c) {
__uint128_t tmp; /* fio_buf2u1128 */
FIO_MEMCPY(&tmp, c, sizeof(tmp));
return tmp;
}
/** Writes a local 128 bit number to an unaligned buffer. */
FIO_IFUNC void FIO_NAME2(fio_u, buf128_local)(void *buf, __uint128_t i) {
FIO_MEMCPY(buf, &i, sizeof(i)); /* fio_u2buf128 */
}
#endif /* __SIZEOF_INT128__ */
#endif /* FIO_UNALIGNED_MEMORY_ACCESS_ENABLED */
/** Converts an unaligned byte stream to a 16 bit number (reversed order). */
FIO_IFUNC uint16_t FIO_NAME2(fio_buf, u16_bswap)(const void *c) {
return fio_bswap16(FIO_NAME2(fio_buf, u16_local)(c)); /* fio_buf2u16 */
}
/** Converts an unaligned byte stream to a 32 bit number (reversed order). */
FIO_IFUNC uint32_t FIO_NAME2(fio_buf, u32_bswap)(const void *c) {
return fio_bswap32(FIO_NAME2(fio_buf, u32_local)(c)); /* fio_buf2u32 */
}
/** Converts an unaligned byte stream to a 64 bit number (reversed order). */
FIO_IFUNC uint64_t FIO_NAME2(fio_buf, u64_bswap)(const void *c) {
return fio_bswap64(FIO_NAME2(fio_buf, u64_local)(c)); /* fio_buf2u64 */
}
/** Writes a local 16 bit number to an unaligned buffer in reversed order. */
FIO_IFUNC void FIO_NAME2(fio_u, buf16_bswap)(void *buf, uint16_t i) {
FIO_NAME2(fio_u, buf16_local)(buf, fio_bswap16(i));
}
/** Writes a local 32 bit number to an unaligned buffer in reversed order. */
FIO_IFUNC void FIO_NAME2(fio_u, buf32_bswap)(void *buf, uint32_t i) {
FIO_NAME2(fio_u, buf32_local)(buf, fio_bswap32(i));
}
/** Writes a local 64 bit number to an unaligned buffer in reversed order. */
FIO_IFUNC void FIO_NAME2(fio_u, buf64_bswap)(void *buf, uint64_t i) {
FIO_NAME2(fio_u, buf64_local)(buf, fio_bswap64(i));
}
#ifdef __SIZEOF_INT128__
/** Writes a local 64 bit number to an unaligned buffer in reversed order. */
FIO_IFUNC void FIO_NAME2(fio_u, buf128_bswap)(void *buf, __uint128_t i) {
FIO_NAME2(fio_u, buf128_local)(buf, fio_bswap128(i));
}
#endif /* __SIZEOF_INT128__ */
/** Converts an unaligned byte stream to a 16 bit number (Big Endian). */
FIO_IFUNC uint16_t FIO_NAME2(fio_buf, u16)(const void *c) { /* fio_buf2u16 */
uint16_t i = FIO_NAME2(fio_buf, u16_local)(c);
return fio_lton16(i);
}
/** Converts an unaligned byte stream to a 32 bit number (Big Endian). */
FIO_IFUNC uint32_t FIO_NAME2(fio_buf, u32)(const void *c) { /* fio_buf2u32 */
uint32_t i = FIO_NAME2(fio_buf, u32_local)(c);
return fio_lton32(i);
}
/** Converts an unaligned byte stream to a 64 bit number (Big Endian). */
FIO_IFUNC uint64_t FIO_NAME2(fio_buf, u64)(const void *c) { /* fio_buf2u64 */
uint64_t i = FIO_NAME2(fio_buf, u64_local)(c);
return fio_lton64(i);
}
/** Writes a local 16 bit number to an unaligned buffer in Big Endian. */
FIO_IFUNC void FIO_NAME2(fio_u, buf16)(void *buf, uint16_t i) {
FIO_NAME2(fio_u, buf16_local)(buf, fio_ntol16(i));
}
/** Writes a local 32 bit number to an unaligned buffer in Big Endian. */
FIO_IFUNC void FIO_NAME2(fio_u, buf32)(void *buf, uint32_t i) {
FIO_NAME2(fio_u, buf32_local)(buf, fio_ntol32(i));
}
/** Writes a local 64 bit number to an unaligned buffer in Big Endian. */
FIO_IFUNC void FIO_NAME2(fio_u, buf64)(void *buf, uint64_t i) {
FIO_NAME2(fio_u, buf64_local)(buf, fio_ntol64(i));
}
#ifdef __SIZEOF_INT128__
/** Converts an unaligned byte stream to a 128 bit number (Big Endian). */
FIO_IFUNC __uint128_t FIO_NAME2(fio_buf,
u128)(const void *c) { /* fio_buf2u64 */
__uint128_t i = FIO_NAME2(fio_buf, u128_local)(c);
return fio_lton128(i);
}
/** Writes a local 128 bit number to an unaligned buffer in Big Endian. */
FIO_IFUNC void FIO_NAME2(fio_u, buf128)(void *buf, __uint128_t i) {
FIO_NAME2(fio_u, buf128_local)(buf, fio_ntol128(i));
}
#endif /* __SIZEOF_INT128__ */
#if __LITTLE_ENDIAN__
/** Converts an unaligned byte stream to a 16 bit number (Little Endian). */
FIO_IFUNC uint16_t FIO_NAME2(fio_buf, u16_little)(const void *c) {
return FIO_NAME2(fio_buf, u16_local)(c); /* fio_buf2u16 */
}
/** Converts an unaligned byte stream to a 32 bit number (Little Endian). */
FIO_IFUNC uint32_t FIO_NAME2(fio_buf, u32_little)(const void *c) {
return FIO_NAME2(fio_buf, u32_local)(c); /* fio_buf2u32 */
}
/** Converts an unaligned byte stream to a 64 bit number (Little Endian). */
FIO_IFUNC uint64_t FIO_NAME2(fio_buf, u64_little)(const void *c) {
return FIO_NAME2(fio_buf, u64_local)(c); /* fio_buf2u64 */
}
/** Writes a local 16 bit number to an unaligned buffer in Little Endian. */
FIO_IFUNC void FIO_NAME2(fio_u, buf16_little)(void *buf, uint16_t i) {
FIO_NAME2(fio_u, buf16_local)(buf, i);
}
/** Writes a local 32 bit number to an unaligned buffer in Little Endian. */
FIO_IFUNC void FIO_NAME2(fio_u, buf32_little)(void *buf, uint32_t i) {
FIO_NAME2(fio_u, buf32_local)(buf, i);
}
/** Writes a local 64 bit number to an unaligned buffer in Little Endian. */
FIO_IFUNC void FIO_NAME2(fio_u, buf64_little)(void *buf, uint64_t i) {
FIO_NAME2(fio_u, buf64_local)(buf, i);
}
#ifdef __SIZEOF_INT128__
/** Converts an unaligned byte stream to a 128 bit number (Little Endian). */
FIO_IFUNC __uint128_t FIO_NAME2(fio_buf, u128_little)(const void *c) {
return FIO_NAME2(fio_buf, u128_local)(c); /* fio_buf2u64 */
}
/** Writes a local 128 bit number to an unaligned buffer in Little Endian. */
FIO_IFUNC void FIO_NAME2(fio_u, buf128_little)(void *buf, __uint128_t i) {
FIO_NAME2(fio_u, buf128_local)(buf, i);
}
#endif /* __SIZEOF_INT128__ */
#else
/** Converts an unaligned byte stream to a 16 bit number (Little Endian). */
FIO_IFUNC uint16_t FIO_NAME2(fio_buf, u16_little)(const void *c) {
return FIO_NAME2(fio_buf, u16_bswap)(c); /* fio_buf2u16 */
}
/** Converts an unaligned byte stream to a 32 bit number (Little Endian). */
FIO_IFUNC uint32_t FIO_NAME2(fio_buf, u32_little)(const void *c) {
return FIO_NAME2(fio_buf, u32_bswap)(c); /* fio_buf2u32 */
}
/** Converts an unaligned byte stream to a 64 bit number (Little Endian). */
FIO_IFUNC uint64_t FIO_NAME2(fio_buf, u64_little)(const void *c) {
return FIO_NAME2(fio_buf, u64_bswap)(c); /* fio_buf2u64 */
}
/** Writes a local 16 bit number to an unaligned buffer in Little Endian. */
FIO_IFUNC void FIO_NAME2(fio_u, buf16_little)(void *buf, uint16_t i) {
FIO_NAME2(fio_u, buf16_bswap)(buf, i);
}
/** Writes a local 32 bit number to an unaligned buffer in Little Endian. */
FIO_IFUNC void FIO_NAME2(fio_u, buf32_little)(void *buf, uint32_t i) {
FIO_NAME2(fio_u, buf32_bswap)(buf, i);
}
/** Writes a local 64 bit number to an unaligned buffer in Little Endian. */
FIO_IFUNC void FIO_NAME2(fio_u, buf64_little)(void *buf, uint64_t i) {
FIO_NAME2(fio_u, buf64_bswap)(buf, i);
}
#ifdef __SIZEOF_INT128__
/** Converts an unaligned byte stream to a 128 bit number (Little Endian). */
FIO_IFUNC __uint128_t FIO_NAME2(fio_buf, u128_little)(const void *c) {
return FIO_NAME2(fio_buf, u128_bswap)(c); /* fio_buf2u64 */
}
/** Writes a local 128 bit number to an unaligned buffer in Little Endian. */
FIO_IFUNC void FIO_NAME2(fio_u, buf128_little)(void *buf, __uint128_t i) {
FIO_NAME2(fio_u, buf128_bswap)(buf, i);
}
#endif /* __SIZEOF_INT128__ */
#endif /* __LITTLE_ENDIAN__ */
/** Convinience function for reading 1 byte (8 bit) from a buffer. */
FIO_IFUNC uint8_t FIO_NAME2(fio_buf, u8_local)(const void *c) {
const uint8_t *tmp = (const uint8_t *)c; /* fio_buf2u16 */
return *tmp;
}
/** Convinience function for writing 1 byte (8 bit) to a buffer. */
FIO_IFUNC void FIO_NAME2(fio_u, buf8_local)(void *buf, uint8_t i) {
*((uint8_t *)buf) = i; /* fio_u2buf16 */
}
/** Convinience function for reading 1 byte (8 bit) from a buffer. */
FIO_IFUNC uint8_t FIO_NAME2(fio_buf, u8_bswap)(const void *c) {
const uint8_t *tmp = (const uint8_t *)c; /* fio_buf2u16 */
return *tmp;
}
/** Convinience function for writing 1 byte (8 bit) to a buffer. */
FIO_IFUNC void FIO_NAME2(fio_u, buf8_bswap)(void *buf, uint8_t i) {
*((uint8_t *)buf) = i; /* fio_u2buf16 */
}
/** Convinience function for reading 1 byte (8 bit) from a buffer. */
FIO_IFUNC uint8_t FIO_NAME2(fio_buf, u8_little)(const void *c) {
const uint8_t *tmp = (const uint8_t *)c; /* fio_buf2u16 */
return *tmp;
}
/** Convinience function for writing 1 byte (8 bit) to a buffer. */
FIO_IFUNC void FIO_NAME2(fio_u, buf8_little)(void *buf, uint8_t i) {
*((uint8_t *)buf) = i; /* fio_u2buf16 */
}
/** Convinience function for reading 1 byte (8 bit) from a buffer. */
FIO_IFUNC uint8_t FIO_NAME2(fio_buf, u8)(const void *c) {
const uint8_t *tmp = (const uint8_t *)c; /* fio_buf2u16 */
return *tmp;
}
/** Convinience function for writing 1 byte (8 bit) to a buffer. */
FIO_IFUNC void FIO_NAME2(fio_u, buf8)(void *buf, uint8_t i) {
*((uint8_t *)buf) = i; /* fio_u2buf16 */
}
/* *****************************************************************************
Constant-Time Selectors
***************************************************************************** */
/** Returns 1 if the expression is true (input isn't zero). */
FIO_IFUNC uintptr_t fio_ct_true(uintptr_t cond) {
// promise that the highest bit is set if any bits are set, than shift.
return ((cond | (0 - cond)) >> ((sizeof(cond) << 3) - 1));
}
/** Returns 1 if the expression is false (input is zero). */
FIO_IFUNC uintptr_t fio_ct_false(uintptr_t cond) {
// fio_ct_true returns only one bit, XOR will inverse that bit.
return fio_ct_true(cond) ^ 1;
}
/** Returns `a` if `cond` is boolean and true, returns b otherwise. */
FIO_IFUNC uintptr_t fio_ct_if_bool(uint8_t cond, uintptr_t a, uintptr_t b) {
// b^(a^b) cancels b out. 0-1 => sets all bits.
return (b ^ ((0 - (cond & 1)) & (a ^ b)));
}
/** Returns `a` if `cond` isn't zero (uses fio_ct_true), returns b otherwise. */
FIO_IFUNC uintptr_t fio_ct_if(uintptr_t cond, uintptr_t a, uintptr_t b) {
// b^(a^b) cancels b out. 0-1 => sets all bits.
return fio_ct_if_bool(fio_ct_true(cond), a, b);
}
/* *****************************************************************************
SIMD emulation helpers
***************************************************************************** */
/**
* Detects a byte where all the bits are set (255) within a 4 byte vector.
*
* The full byte will be be set to 0x80, all other bytes will be 0x0.
*/
FIO_IFUNC uint32_t fio_has_full_byte32(uint32_t row) {
return ((row & UINT32_C(0x7F7F7F7F)) + UINT32_C(0x01010101)) &
(row & UINT32_C(0x80808080));
}
/**
* Detects a byte where no bits are set (0) within a 4 byte vector.
*
* The zero byte will be be set to 0x80, all other bytes will be 0x0.
*/
FIO_IFUNC uint32_t fio_has_zero_byte32(uint32_t row) {
return fio_has_full_byte32(~row);
}
/**
* Detects if `byte` exists within a 4 byte vector.
*
* The requested byte will be be set to 0x80, all other bytes will be 0x0.
*/
FIO_IFUNC uint32_t fio_has_byte32(uint32_t row, uint8_t byte) {
return fio_has_full_byte32(~(row ^ (UINT32_C(0x01010101) * byte)));
}
/**
* Detects a byte where all the bits are set (255) within an 8 byte vector.
*
* The full byte will be be set to 0x80, all other bytes will be 0x0.
*/
FIO_IFUNC uint64_t fio_has_full_byte64(uint64_t row) {
return ((row & UINT64_C(0x7F7F7F7F7F7F7F7F)) + UINT64_C(0x0101010101010101)) &
(row & UINT64_C(0x8080808080808080));
}
/**
* Detects a byte where no bits are set (0) within an 8 byte vector.
*
* The zero byte will be be set to 0x80, all other bytes will be 0x0.
*/
FIO_IFUNC uint64_t fio_has_zero_byte64(uint64_t row) {
return fio_has_full_byte64(~row);
}
/**
* Detects if `byte` exists within an 8 byte vector.
*
* The requested byte will be be set to 0x80, all other bytes will be 0x0.
*/
FIO_IFUNC uint64_t fio_has_byte64(uint64_t row, uint8_t byte) {
return fio_has_full_byte64(~(row ^ (UINT64_C(0x0101010101010101) * byte)));
}
#ifdef __SIZEOF_INT128__
/**
* Detects a byte where all the bits are set (255) within an 16 byte vector.
*
* The full byte will be be set to 0x80, all other bytes will be 0x0.
*/
FIO_IFUNC __uint128_t fio_has_full_byte128(__uint128_t row) {
const __uint128_t allF7 = ((__uint128_t)(0x7F7F7F7F7F7F7F7FULL) << 64) |
(__uint128_t)(0x7F7F7F7F7F7F7F7FULL);
const __uint128_t all80 = ((__uint128_t)(0x8080808080808080) << 64) |
(__uint128_t)(0x8080808080808080);
const __uint128_t all01 = ((__uint128_t)(0x0101010101010101) << 64) |
(__uint128_t)(0x0101010101010101);
return ((row & allF7) + all01) & (row & all80);
}
/**
* Detects a byte where no bits are set (0) within an 8 byte vector.
*
* The zero byte will be be set to 0x80, all other bytes will be 0x0.
*/
FIO_IFUNC __uint128_t fio_has_zero_byte128(__uint128_t row) {
return fio_has_full_byte64(~row);
}
/**
* Detects if `byte` exists within an 8 byte vector.
*
* The requested byte will be be set to 0x80, all other bytes will be 0x0.
*/
FIO_IFUNC __uint128_t fio_has_byte128(__uint128_t row, uint8_t byte) {
const __uint128_t all01 = ((__uint128_t)(0x0101010101010101) << 64) |
(__uint128_t)(0x0101010101010101);
return fio_has_full_byte64(~(row ^ (all01 * byte)));
}
#endif /* __SIZEOF_INT128__ */
/** Converts a `fio_has_byteX` result to a bitmap. */
FIO_IFUNC uint8_t fio_has_byte2bitmap(uint64_t result) {
result >>= 7; /* move result to first bit of each byte */
result |= (result >> 7); /* combine 2 bytes of result */
result |= (result >> 14); /* combine 4 bytes of result */
result |= (result >> 28); /* combine 8 bytes of result */
return (((uint8_t)result) & 0xFF);
}
/** Isolated the least significant (lowest) bit. */
FIO_IFUNC uint64_t fio_bits_lsb(uint64_t i) { return (size_t)(i & (0 - i)); }
/** Returns the index of the most significant (highest) bit. */
FIO_IFUNC size_t fio_bits_msb_index(uint64_t i) {
uint64_t r = 0;
if (!i)
goto zero;
#if defined(__has_builtin) && __has_builtin(__builtin_clzll)
return __builtin_clzll(i);
#else
#define fio___bits_msb_index_step(x) \
if (i >= ((uint64_t)1) << x) \
r += x, i >>= x;
fio___bits_msb_index_step(32);
fio___bits_msb_index_step(16);
fio___bits_msb_index_step(8);
fio___bits_msb_index_step(4);
fio___bits_msb_index_step(2);
fio___bits_msb_index_step(1);
#undef fio___bits_msb_index_step
return r;
#endif
zero:
r = (size_t)-1;
return r;
}
/** Returns the index of the least significant (lowest) bit. */
FIO_IFUNC size_t fio_bits_lsb_index(uint64_t i) {
#if defined(__has_builtin) && __has_builtin(__builtin_ctzll)
if (!i)
return (size_t)-1;
return __builtin_ctzll(i);
#elif 0
return fio_bits_msb_index(fio_bits_lsb(i));
#else
// clang-format off
switch (fio_bits_lsb(i)) {
case UINT64_C(0x0): return (size_t)-1;
case UINT64_C(0x1): return 0;
case UINT64_C(0x2): return 1;
case UINT64_C(0x4): return 2;
case UINT64_C(0x8): return 3;
case UINT64_C(0x10): return 4;
case UINT64_C(0x20): return 5;
case UINT64_C(0x40): return 6;
case UINT64_C(0x80): return 7;
case UINT64_C(0x100): return 8;
case UINT64_C(0x200): return 9;
case UINT64_C(0x400): return 10;
case UINT64_C(0x800): return 11;
case UINT64_C(0x1000): return 12;
case UINT64_C(0x2000): return 13;
case UINT64_C(0x4000): return 14;
case UINT64_C(0x8000): return 15;
case UINT64_C(0x10000): return 16;
case UINT64_C(0x20000): return 17;
case UINT64_C(0x40000): return 18;
case UINT64_C(0x80000): return 19;
case UINT64_C(0x100000): return 20;
case UINT64_C(0x200000): return 21;
case UINT64_C(0x400000): return 22;
case UINT64_C(0x800000): return 23;
case UINT64_C(0x1000000): return 24;
case UINT64_C(0x2000000): return 25;
case UINT64_C(0x4000000): return 26;
case UINT64_C(0x8000000): return 27;
case UINT64_C(0x10000000): return 28;
case UINT64_C(0x20000000): return 29;
case UINT64_C(0x40000000): return 30;
case UINT64_C(0x80000000): return 31;
case UINT64_C(0x100000000): return 32;
case UINT64_C(0x200000000): return 33;
case UINT64_C(0x400000000): return 34;
case UINT64_C(0x800000000): return 35;
case UINT64_C(0x1000000000): return 36;
case UINT64_C(0x2000000000): return 37;
case UINT64_C(0x4000000000): return 38;
case UINT64_C(0x8000000000): return 39;
case UINT64_C(0x10000000000): return 40;
case UINT64_C(0x20000000000): return 41;
case UINT64_C(0x40000000000): return 42;
case UINT64_C(0x80000000000): return 43;
case UINT64_C(0x100000000000): return 44;
case UINT64_C(0x200000000000): return 45;
case UINT64_C(0x400000000000): return 46;
case UINT64_C(0x800000000000): return 47;
case UINT64_C(0x1000000000000): return 48;
case UINT64_C(0x2000000000000): return 49;
case UINT64_C(0x4000000000000): return 50;
case UINT64_C(0x8000000000000): return 51;
case UINT64_C(0x10000000000000): return 52;
case UINT64_C(0x20000000000000): return 53;
case UINT64_C(0x40000000000000): return 54;
case UINT64_C(0x80000000000000): return 55;
case UINT64_C(0x100000000000000): return 56;
case UINT64_C(0x200000000000000): return 57;
case UINT64_C(0x400000000000000): return 58;
case UINT64_C(0x800000000000000): return 59;
case UINT64_C(0x1000000000000000): return 60;
case UINT64_C(0x2000000000000000): return 61;
case UINT64_C(0x4000000000000000): return 62;
case UINT64_C(0x8000000000000000): return 63;
}
// clang-format on
return -1;
#endif /* __builtin vs. math vs. map */
}
/* *****************************************************************************
Byte masking (XOR) with nonce (counter mode)
***************************************************************************** */
/**
* Masks 64 bit memory aligned data using a 64 bit mask and a counter mode
* nonce.
*
* Returns the end state of the mask.
*/
FIO_IFUNC uint64_t fio___xmask2_aligned64(uint64_t buf[],
size_t byte_len,
uint64_t mask,
uint64_t nonce) {
register uint64_t m = mask;
for (size_t i = 7; i < byte_len; i += 8) {
*buf ^= m;
m += nonce;
++buf;
}
mask = m;
union { /* type punning */
char *p8;
uint64_t *p64;
} pn, mpn;
pn.p64 = buf;
mpn.p64 = &mask;
switch ((byte_len & 7)) {
case 0:
return mask;
case 7:
pn.p8[6] ^= mpn.p8[6];
/* fallthrough */
case 6:
pn.p8[5] ^= mpn.p8[5];
/* fallthrough */
case 5:
pn.p8[4] ^= mpn.p8[4];
/* fallthrough */
case 4:
pn.p8[3] ^= mpn.p8[3];
/* fallthrough */
case 3:
pn.p8[2] ^= mpn.p8[2];
/* fallthrough */
case 2:
pn.p8[1] ^= mpn.p8[1];
/* fallthrough */
case 1:
pn.p8[0] ^= mpn.p8[0];
/* fallthrough */
}
return mask;
}
/**
* Masks unaligned memory data using a 64 bit mask and a counter mode nonce.
*
* Returns the end state of the mask.
*/
FIO_IFUNC uint64_t fio___xmask2_unaligned_words(void *buf_,
size_t len,
uint64_t mask,
const uint64_t nonce) {
register uint8_t *buf = (uint8_t *)buf_;
register uint64_t m = mask;
for (size_t i = 7; i < len; i += 8) {
uint64_t tmp;
tmp = FIO_NAME2(fio_buf, u64_local)(buf);
tmp ^= m;
FIO_NAME2(fio_u, buf64_local)(buf, tmp);
m += nonce;
buf += 8;
}
mask = m;
switch ((len & 7)) {
case 0:
return mask;
case 7:
buf[6] ^= ((uint8_t *)(&mask))[6];
/* fallthrough */
case 6:
buf[5] ^= ((uint8_t *)(&mask))[5];
/* fallthrough */
case 5:
buf[4] ^= ((uint8_t *)(&mask))[4];
/* fallthrough */
case 4:
buf[3] ^= ((uint8_t *)(&mask))[3];
/* fallthrough */
case 3:
buf[2] ^= ((uint8_t *)(&mask))[2];
/* fallthrough */
case 2:
buf[1] ^= ((uint8_t *)(&mask))[1];
/* fallthrough */
case 1:
buf[0] ^= ((uint8_t *)(&mask))[0];
/* fallthrough */
}
return mask;
}
/**
* Masks data using a 64 bit mask and a counter mode nonce. When the buffer's
* memory is aligned, the function may perform significantly better.
*
* Returns the end state of the mask.
*/
FIO_IFUNC uint64_t fio_xmask2(char *buf,
size_t len,
uint64_t mask,
uint64_t nonce) {
if (!((uintptr_t)buf & 7)) {
union {
char *p8;
uint64_t *p64;
} pn;
pn.p8 = buf;
return fio___xmask2_aligned64(pn.p64, len, mask, nonce);
}
return fio___xmask2_unaligned_words(buf, len, mask, nonce);
}
/* *****************************************************************************
Byte masking (XOR) - no nonce
***************************************************************************** */
/**
* Masks data using a persistent 64 bit mask.
*
* When the buffer's memory is aligned, the function may perform significantly
* better.
*/
FIO_IFUNC void fio_xmask(char *buf_, size_t len, uint64_t mask) {
register uint8_t *buf = (uint8_t *)buf_;
register uint64_t m = mask;
for (size_t i = 7; i < len; i += 8) {
uint64_t tmp;
tmp = FIO_NAME2(fio_buf, u64_local)(buf);
tmp ^= m;
FIO_NAME2(fio_u, buf64_local)(buf, tmp);
buf += 8;
}
uint64_t t = mask;
register union { /* type punning */
uint8_t *restrict p8;
uint64_t *restrict p64;
} pn;
pn.p64 = &t;
switch ((len & 7)) {
case 7:
buf[6] ^= pn.p8[6];
/* fallthrough */
case 6:
buf[5] ^= pn.p8[5];
/* fallthrough */
case 5:
buf[4] ^= pn.p8[4];
/* fallthrough */
case 4:
buf[3] ^= pn.p8[3];
/* fallthrough */
case 3:
buf[2] ^= pn.p8[2];
/* fallthrough */
case 2:
buf[1] ^= pn.p8[1];
/* fallthrough */
case 1:
buf[0] ^= pn.p8[0];
/* fallthrough */
}
}
/* *****************************************************************************
Hemming Distance and bit counting
***************************************************************************** */
#if __has_builtin(__builtin_popcountll)
/** performs a `popcount` operation to count the set bits. */
#define fio_popcount(n) __builtin_popcountll(n)
#else
FIO_IFUNC int fio_popcount(uint64_t n) {
/* for logic, see Wikipedia: https://en.wikipedia.org/wiki/Hamming_weight */
n = n - ((n >> 1) & 0x5555555555555555);
n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333);
n = (n + (n >> 4)) & 0x0f0f0f0f0f0f0f0f;
n = n + (n >> 8);
n = n + (n >> 16);
n = n + (n >> 32);
return n & 0x7f;
}
#endif
#define fio_hemming_dist(n1, n2) fio_popcount(((uint64_t)(n1) ^ (uint64_t)(n2)))
/* *****************************************************************************
Bitewise helpers cleanup
***************************************************************************** */
#endif /* FIO_BITWISE */
#undef FIO_BITWISE
/* *****************************************************************************
Bitmap Helpers
***************************************************************************** */
#if defined(FIO_BITMAP) && !defined(H___FIO_BITMAP_H)
#define H___FIO_BITMAP_H
/* *****************************************************************************
Bitmap access / manipulation
***************************************************************************** */
/** Gets the state of a bit in a bitmap. */
FIO_IFUNC uint8_t fio_bitmap_get(void *map, size_t bit) {
return ((((uint8_t *)(map))[(bit) >> 3] >> ((bit)&7)) & 1);
}
/** Sets the a bit in a bitmap (sets to 1). */
FIO_IFUNC void fio_bitmap_set(void *map, size_t bit) {
fio_atomic_or((uint8_t *)(map) + ((bit) >> 3), (1UL << ((bit)&7)));
}
/** Unsets the a bit in a bitmap (sets to 0). */
FIO_IFUNC void fio_bitmap_unset(void *map, size_t bit) {
fio_atomic_and((uint8_t *)(map) + ((bit) >> 3),
(uint8_t)(~(1UL << ((bit)&7))));
}
/** Flips the a bit in a bitmap (sets to 0 if 1, sets to 1 if 0). */
FIO_IFUNC void fio_bitmap_flip(void *map, size_t bit) {
fio_atomic_xor((uint8_t *)(map) + ((bit) >> 3), (1UL << ((bit)&7)));
}
/* *****************************************************************************
Bit-Byte operations - testing
***************************************************************************** */
#ifdef FIO_TEST_CSTL
/* used in the test, defined later */
SFUNC uint64_t fio_rand64(void);
SFUNC void fio_rand_bytes(void *target, size_t len);
FIO_SFUNC void FIO_NAME_TEST(stl, bitwise)(void) {
fprintf(stderr, "* Testing fio_bswapX macros.\n");
FIO_ASSERT(fio_bswap16(0x0102) == (uint16_t)0x0201, "fio_bswap16 failed");
FIO_ASSERT(fio_bswap32(0x01020304) == (uint32_t)0x04030201,
"fio_bswap32 failed");
FIO_ASSERT(fio_bswap64(0x0102030405060708ULL) == 0x0807060504030201ULL,
"fio_bswap64 failed");
fprintf(stderr, "* Testing fio_lrotX and fio_rrotX macros.\n");
{
uint64_t tmp = 1;
tmp = FIO_RROT(tmp, 1);
FIO_COMPILER_GUARD;
FIO_ASSERT(tmp == ((uint64_t)1 << ((sizeof(uint64_t) << 3) - 1)),
"fio_rrot failed");
tmp = FIO_LROT(tmp, 3);
FIO_COMPILER_GUARD;
FIO_ASSERT(tmp == ((uint64_t)1 << 2), "fio_lrot failed");
tmp = 1;
tmp = fio_rrot32(tmp, 1);
FIO_COMPILER_GUARD;
FIO_ASSERT(tmp == ((uint64_t)1 << 31), "fio_rrot32 failed");
tmp = fio_lrot32(tmp, 3);
FIO_COMPILER_GUARD;
FIO_ASSERT(tmp == ((uint64_t)1 << 2), "fio_lrot32 failed");
tmp = 1;
tmp = fio_rrot64(tmp, 1);
FIO_COMPILER_GUARD;
FIO_ASSERT(tmp == ((uint64_t)1 << 63), "fio_rrot64 failed");
tmp = fio_lrot64(tmp, 3);
FIO_COMPILER_GUARD;
FIO_ASSERT(tmp == ((uint64_t)1 << 2), "fio_lrot64 failed");
}
fprintf(stderr, "* Testing fio_buf2uX and fio_u2bufX helpers.\n");
#define FIO___BITMAP_TEST_BITS(bits) \
for (size_t i = 0; i <= (bits); ++i) { \
char tmp_buf[16]; \
int##bits##_t n = ((uint##bits##_t)1 << i); \
FIO_NAME2(fio_u, buf##bits)(tmp_buf, n); \
int##bits##_t r = FIO_NAME2(fio_buf, u##bits)(tmp_buf); \
FIO_ASSERT(r == n, \
"roundtrip failed for U" #bits " at bit %zu\n\t%zu != %zu", \
i, \
(size_t)n, \
(size_t)r); \
}
FIO___BITMAP_TEST_BITS(8);
FIO___BITMAP_TEST_BITS(16);
FIO___BITMAP_TEST_BITS(32);
FIO___BITMAP_TEST_BITS(64);
#undef FIO___BITMAP_TEST_BITS
fprintf(stderr, "* Testing constant-time helpers.\n");
FIO_ASSERT(fio_ct_true(0) == 0, "fio_ct_true(0) should be zero!");
for (uintptr_t i = 1; i; i <<= 1) {
FIO_ASSERT(fio_ct_true(i) == 1,
"fio_ct_true(%p) should be true!",
(void *)i);
}
for (uintptr_t i = 1; i + 1 != 0; i = (i << 1) | 1) {
FIO_ASSERT(fio_ct_true(i) == 1,
"fio_ct_true(%p) should be true!",
(void *)i);
}
FIO_ASSERT(fio_ct_true(((uintptr_t)~0ULL)) == 1,
"fio_ct_true(%p) should be true!",
(void *)(uintptr_t)(~0ULL));
FIO_ASSERT(fio_ct_false(0) == 1, "fio_ct_false(0) should be true!");
for (uintptr_t i = 1; i; i <<= 1) {
FIO_ASSERT(fio_ct_false(i) == 0,
"fio_ct_false(%p) should be zero!",
(void *)i);
}
for (uintptr_t i = 1; i + 1 != 0; i = (i << 1) | 1) {
FIO_ASSERT(fio_ct_false(i) == 0,
"fio_ct_false(%p) should be zero!",
(void *)i);
}
FIO_ASSERT(fio_ct_false(((uintptr_t)~0ULL)) == 0,
"fio_ct_false(%p) should be zero!",
(void *)(uintptr_t)(~0ULL));
FIO_ASSERT(fio_ct_true(8), "fio_ct_true should be true.");
FIO_ASSERT(!fio_ct_true(0), "fio_ct_true should be false.");
FIO_ASSERT(!fio_ct_false(8), "fio_ct_false should be false.");
FIO_ASSERT(fio_ct_false(0), "fio_ct_false should be true.");
FIO_ASSERT(fio_ct_if_bool(0, 1, 2) == 2,
"fio_ct_if_bool selection error (false).");
FIO_ASSERT(fio_ct_if_bool(1, 1, 2) == 1,
"fio_ct_if_bool selection error (true).");
FIO_ASSERT(fio_ct_if(0, 1, 2) == 2, "fio_ct_if selection error (false).");
FIO_ASSERT(fio_ct_if(8, 1, 2) == 1, "fio_ct_if selection error (true).");
{
uint8_t bitmap[1024];
memset(bitmap, 0, 1024);
fprintf(stderr, "* Testing bitmap helpers.\n");
FIO_ASSERT(!fio_bitmap_get(bitmap, 97), "fio_bitmap_get should be 0.");
fio_bitmap_set(bitmap, 97);
FIO_ASSERT(fio_bitmap_get(bitmap, 97) == 1,
"fio_bitmap_get should be 1 after being set");
FIO_ASSERT(!fio_bitmap_get(bitmap, 96),
"other bits shouldn't be effected by set.");
FIO_ASSERT(!fio_bitmap_get(bitmap, 98),
"other bits shouldn't be effected by set.");
fio_bitmap_flip(bitmap, 96);
fio_bitmap_flip(bitmap, 97);
FIO_ASSERT(!fio_bitmap_get(bitmap, 97),
"fio_bitmap_get should be 0 after flip.");
FIO_ASSERT(fio_bitmap_get(bitmap, 96) == 1,
"other bits shouldn't be effected by flip");
fio_bitmap_unset(bitmap, 96);
fio_bitmap_flip(bitmap, 97);
FIO_ASSERT(!fio_bitmap_get(bitmap, 96),
"fio_bitmap_get should be 0 after unset.");
FIO_ASSERT(fio_bitmap_get(bitmap, 97) == 1,
"other bits shouldn't be effected by unset");
fio_bitmap_unset(bitmap, 96);
}
{
fprintf(stderr, "* Testing popcount and hemming distance calculation.\n");
for (int i = 0; i < 64; ++i) {
FIO_ASSERT(fio_popcount((uint64_t)1 << i) == 1,
"fio_popcount error for 1 bit");
}
for (int i = 0; i < 63; ++i) {
FIO_ASSERT(fio_popcount((uint64_t)3 << i) == 2,
"fio_popcount error for 2 bits");
}
for (int i = 0; i < 62; ++i) {
FIO_ASSERT(fio_popcount((uint64_t)7 << i) == 3,
"fio_popcount error for 3 bits");
}
for (int i = 0; i < 59; ++i) {
FIO_ASSERT(fio_popcount((uint64_t)21 << i) == 3,
"fio_popcount error for 3 alternating bits");
}
for (int i = 0; i < 64; ++i) {
FIO_ASSERT(fio_hemming_dist(((uint64_t)1 << i) - 1, 0) == i,
"fio_hemming_dist error at %d",
i);
}
}
{
struct test_s {
int a;
char force_padding;
int b;
} stst = {.a = 1};
struct test_s *stst_p = FIO_PTR_FROM_FIELD(struct test_s, b, &stst.b);
FIO_ASSERT(stst_p == &stst, "FIO_PTR_FROM_FIELD failed to retrace pointer");
}
{
fprintf(stderr, "* Testing fio_xmask and fio_xmask2.\n");
char data[128], buf[256];
uint64_t mask;
uint64_t counter;
do {
mask = fio_rand64();
counter = fio_rand64();
} while (!mask || !counter);
fio_rand_bytes(data, 128);
for (uint8_t i = 0; i < 16; ++i) {
FIO_MEMCPY(buf + i, data, 128);
fio_xmask(buf + i, 128, mask);
fio_xmask(buf + i, 128, mask);
FIO_ASSERT(!memcmp(buf + i, data, 128), "fio_xmask rountrip error");
fio_xmask(buf + i, 128, mask);
memmove(buf + i + 1, buf + i, 128);
fio_xmask(buf + i + 1, 128, mask);
FIO_ASSERT(!memcmp(buf + i + 1, data, 128),
"fio_xmask rountrip (with move) error");
}
for (uint8_t i = 0; i < 16; ++i) {
FIO_MEMCPY(buf + i, data, 128);
fio_xmask2(buf + i, 128, mask, counter);
fio_xmask2(buf + i, 128, mask, counter);
FIO_ASSERT(!memcmp(buf + i, data, 128), "fio_xmask2 CM rountrip error");
fio_xmask2(buf + i, 128, mask, counter);
memmove(buf + i + 1, buf + i, 128);
fio_xmask2(buf + i + 1, 128, mask, counter);
FIO_ASSERT(!memcmp(buf + i + 1, data, 128),
"fio_xmask2 CM rountrip (with move) error");
}
}
}
#endif /* FIO_TEST_CSTL */
/* *****************************************************************************
Bit-Byte operations - cleanup
***************************************************************************** */
#endif /* FIO_BITMAP */
#undef FIO_BITMAP
|
janbiedermann/cstl
|
tests/client.c
|
/* *****************************************************************************
Copyright: <NAME>, 2019-2020
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
/* *****************************************************************************
This is a simple TCP/IP and Unix Socket client example. UDP is also available
but untested.
This demonstrates simple usage of the facil.io C STL core features for network
applications.
However, the facil.io IO core library might be a better (easier) choice for this
task.
Note that this program uses a single thread, which allows it to ignore some
possible race conditions.
***************************************************************************** */
/* include some of the moduls we use... */
#define FIO_CLI
#define FIO_LOG
#define FIO_URL
#define FIO_SOCK
#define FIO_STREAM
#define FIO_SIGNAL
#define FIO_POLL
#include "fio-stl.h"
/* we use local global variables to make the code easier. */
/** This is used as a user-land buffer in case of partial `write` call. */
fio_stream_s output_stream = FIO_STREAM_INIT(output_stream);
/** A flag telling us when to stop reviewing IO events. */
static volatile uint8_t stop = 0;
/** The client / cconnection socket. */
int client_fd;
/** Called when the socket have available space in the outgoing buffer. */
FIO_SFUNC void on_ready(int fd, void *arg);
/** Called there's incoming data (from STDIN / the client socket. */
FIO_SFUNC void on_data(int fd, void *arg);
/** Called when the monitored IO is closed or has a fatal error. */
FIO_SFUNC void on_close(int fd, void *arg);
/** The IO polling object - it keeps a one-shot list of monitored IOs. */
static fio_poll_s *monitor;
/* facil.io delays signal callbacks so they can safely with no restrictions. */
FIO_SFUNC void on_signal(int sig, void *udata);
/* *****************************************************************************
The main code.
***************************************************************************** */
int main(int argc, char const *argv[]) {
/* initialize the CLI options */
fio_cli_start(
argc,
argv,
1, /* require 1 unnamed argument - the address to connect to */
1,
"A simple TCP/IP, Unix or UDP client application. Requires a URL "
"type address. i.e.\n"
"\tNAME <url>\n\n"
"Unix socket examples:\n"
"\tNAME unix://./my.sock\n"
"\tNAME /full/path/to/my.sock\n"
"\nTCP/IP socket examples:\n"
"\tNAME tcp://localhost:3000/\n"
"\tNAME localhost://3000\n"
"\nUDP socket examples:\n"
"\tNAME udp://localhost:3000/\n",
FIO_CLI_BOOL("--verbose -V -d print out debugging messages."));
/* review CLI for logging */
if (fio_cli_get_bool("-V")) {
FIO_LOG_LEVEL = FIO_LOG_LEVEL_DEBUG;
}
/* review CLI connection address (in URL format) */
size_t url_len = strlen(fio_cli_unnamed(0));
FIO_ASSERT(url_len < 1024, "URL address too long");
fio_url_s a = fio_url_parse(fio_cli_unnamed(0), url_len);
if (!a.host.buf && !a.port.buf) {
#if FIO_OS_WIN
FIO_ASSERT(0, "Unix style sockets are unsupported on Windows.");
#else
/* Unix Socket */
client_fd =
fio_sock_open(a.path.buf,
NULL,
FIO_SOCK_UNIX | FIO_SOCK_CLIENT | FIO_SOCK_NONBLOCK);
FIO_LOG_DEBUG("Opened a Unix Socket (%d).", client_fd);
#endif
} else if (!a.scheme.buf || a.scheme.len != 3 ||
(a.scheme.buf[0] | 32) != 'u' || (a.scheme.buf[1] | 32) != 'd' ||
(a.scheme.buf[2] | 32) != 'p') {
/* TCP/IP Socket */
char buf[1024];
/* copy because we need to add NUL bytes between the address and the port */
memcpy(buf, a.host.buf, a.host.len + a.port.len + 2);
buf[a.host.len + a.port.len + 1] = 0;
buf[a.host.len] = 0;
/* open the socket, passing NUL terminated strings for address and port */
client_fd =
fio_sock_open(buf,
buf + a.host.len + 1,
FIO_SOCK_TCP | FIO_SOCK_CLIENT | FIO_SOCK_NONBLOCK);
/* log */
FIO_LOG_DEBUG("Opened a TCP/IP Socket (%d) to %s port %s.",
client_fd,
buf,
buf + a.host.len + 1);
} else {
/* UDP Socket */
char buf[1024];
/* copy because we need to add NUL bytes between the address and the port */
memcpy(buf, a.host.buf, a.host.len + a.port.len + 2);
buf[a.host.len] = 0;
buf[a.host.len + a.port.len + 1] = 0;
/* open the socket, passing NUL terminated strings for address and port */
client_fd =
fio_sock_open(buf,
buf + a.host.len + 1,
FIO_SOCK_UDP | FIO_SOCK_CLIENT | FIO_SOCK_NONBLOCK);
FIO_LOG_DEBUG("Opened a UDP Socket (%d).", client_fd);
}
/* we're dome with the CLI, release resources */
fio_cli_end();
/* test socket / connection sccess */
if (client_fd == -1) {
FIO_LOG_FATAL("Couldn't open connection");
}
/* select signals to be monitored */
fio_signal_monitor(SIGINT, on_signal, NULL);
fio_signal_monitor(SIGTERM, on_signal, NULL);
fio_signal_monitor(SIGQUIT, on_signal, NULL);
/* select IO objects to be monitored */
monitor = fio_poll_new(.on_data = on_data,
.on_ready = on_ready,
.on_close = on_close);
fio_poll_monitor(monitor, client_fd, NULL, POLLIN | POLLOUT);
fio_poll_monitor(monitor, fileno(stdin), (void *)1, POLLIN); /* mark STDIO */
/* loop until the stop flag is raised */
while (!stop) {
/* review IO events (calls the registered callbacks) */
fio_poll_review(monitor, 1000);
/* review signals (calls the registered callback) */
fio_signal_review();
}
/* cleanup */
fio_sock_close(client_fd);
fio_poll_free(monitor);
return 0;
}
/* *****************************************************************************
Signal callback(s)
***************************************************************************** */
/* facil.io delays signal callbacks so they can safely with no restrictions. */
FIO_SFUNC void on_signal(int sig, void *udata) {
/* since there are no restrictions, we can safely print to the log. */
FIO_LOG_INFO("Exit signal %d detected", sig);
/* If the signal repeats, crash. */
if (fio_atomic_exchange(&stop, 1))
exit(-1);
(void)sig;
(void)udata;
}
/* *****************************************************************************
IO callback(s)
***************************************************************************** */
/** Called when the socket have available space in the outgoing buffer. */
FIO_SFUNC void on_ready(int fd, void *arg) {
FIO_LOG_DEBUG2("on_ready callback called for %d.", fd);
char mem[4080];
size_t len = 4080;
/* send as much data as we can until the system buffer is full */
do {
/* set buffer to copy to, in case a copy is performed */
char *buf = mem;
len = 4080;
/* read from the stream, copy might not be required. updates buf and len. */
fio_stream_read(&output_stream, &buf, &len);
/* write to the IO object */
if (!len || fio_sock_write(fd, buf, len) <= 0)
goto finish;
/* advance the stream by the amount actually written to the IO (partial?) */
fio_stream_advance(&output_stream, len);
/* log */
FIO_LOG_DEBUG2("on_ready send %zu bytes to %d.", len, fd);
} while (len);
finish:
/* if there's data left to write, monitor the outgoing buffer. */
if (fio_stream_any(&output_stream))
fio_poll_monitor(monitor, fd, arg, POLLOUT);
}
/** Called there's incoming data (from STDIN / the client socket. */
FIO_SFUNC void on_data(int fd, void *arg) {
FIO_LOG_DEBUG2("on_data callback called for %d.", fd);
char buf[4080];
/* is this the STDIO file descriptor? (see `main` for details) */
if (arg) {
/* read from STDIO and add data to outgoing stream */
ssize_t l = fio_sock_read(fd, buf, 4080);
if (l > 0) {
fio_stream_add(&output_stream,
fio_stream_pack_data(buf, (size_t)l, 0, 1, NULL));
/* make sure the outgoing buffer is moniitored, so data is written. */
fio_poll_monitor(monitor, client_fd, NULL, POLLOUT);
}
FIO_LOG_DEBUG2("Read %zu bytes from %d", l, fd);
goto done;
}
/* read data until non-blocking read operation fails. */
for (;;) {
ssize_t l = read(fd, buf, 4080);
switch (l + 1) { /* -1 becomes 0 and 0 becomes 1. */
case 0: /* read returned -1, which means there was an error */
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR ||
errno == ENOTCONN) /* desired failures */
goto done;
/* fallthrough */
case 1: /* read returned 0, which means we reached EOF */
FIO_LOG_DEBUG("socket (%d) error / EOF, shutting down: %s",
fd,
strerror(errno));
stop = 1;
return;
}
/* log and print out to STDOUT */
FIO_LOG_DEBUG2("Read %zu bytes from %d", l, fd);
fprintf(stdout, "%.*s", (int)l, buf);
fflush(stdout);
/* if we didn't fill the buffer, the incoming buffer MIGHT be empty. */
if (l < 4080)
goto done;
}
done:
/* remember to reschedule event monitoring (one-shot by design) */
fio_poll_monitor(monitor, fd, arg, POLLIN);
}
/** Called when the monitored IO is closed or has a fatal error. */
FIO_SFUNC void on_close(int fd, void *arg) {
stop = 1;
FIO_LOG_DEBUG2("on_close callback called for %d, stopping.", fd);
(void)arg;
}
|
janbiedermann/cstl
|
stl_slices/700 cleanup.h
|
<gh_stars>10-100
/* *****************************************************************************
Common Cleanup
***************************************************************************** */
/* *****************************************************************************
Common cleanup
***************************************************************************** */
#ifndef FIO_STL_KEEP__
#undef FIO_EXTERN
#undef SFUNC
#undef IFUNC
#undef SFUNC_
#undef IFUNC_
#undef FIO_PTR_TAG
#undef FIO_PTR_UNTAG
#undef FIO_PTR_TAG_TYPE
#undef FIO_PTR_TAG_VALIDATE
#undef FIO_PTR_TAG_VALID_OR_RETURN
#undef FIO_PTR_TAG_VALID_OR_RETURN_VOID
#undef FIO_PTR_TAG_VALID_OR_GOTO
#undef FIO_MALLOC_TMP_USE_SYSTEM
#undef FIO_MEM_REALLOC_
#undef FIO_MEM_FREE_
#undef FIO_MEM_REALLOC_IS_SAFE_
#undef FIO_MEMORY_NAME /* postponed due to possible use in macros */
#undef FIO___LOCK_TYPE
#undef FIO___LOCK_INIT
#undef FIO___LOCK_LOCK
#undef FIO___LOCK_LOCK_TRY
#undef FIO___LOCK_UNLOCK
#undef FIO_USE_THREAD_MUTEX_TMP
/* undefine FIO_EXTERN_COMPLETE only if it was defined locally */
#if defined(FIO_EXTERN_COMPLETE) && FIO_EXTERN_COMPLETE && \
FIO_EXTERN_COMPLETE == 2
#undef FIO_EXTERN_COMPLETE
#endif
#else
#undef SFUNC
#undef IFUNC
#define SFUNC SFUNC_
#define IFUNC IFUNC_
#endif /* !FIO_STL_KEEP__ */
|
janbiedermann/cstl
|
tests/mempool.c
|
#define FIO_MALLOC_TEST_NOTICE \
"Testing FIO_MEMORY_NAME with the default, small allocator, settings."
/* use the fast-setup global allocator shortcut for FIO_MEMORY_NAME */
#define FIO_MEMORY_NAME fio
#define FIO_LOG
#define FIO_TIME
#define FIO_ATOMIC
#include <fio-stl.h>
#define H___FIO_MALLOC___H
#include "malloc.c"
|
janbiedermann/cstl
|
stl_slices/103 cli.h
|
<gh_stars>0
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#include "000 header.h" /* Development inclusion - ignore line */
#include "004 bitwise.h" /* Development inclusion - ignore line */
#include "005 riskyhash.h" /* Development inclusion - ignore line */
#include "006 atol.h" /* Development inclusion - ignore line */
#include "100 mem.h" /* Development inclusion - ignore line */
#include "210 map api.h" /* Development inclusion - ignore line */
#include "211 ordered map.h" /* Development inclusion - ignore line */
#include "211 unordered map.h" /* Development inclusion - ignore line */
#define FIO_CLI /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
CLI helpers - command line interface parsing
***************************************************************************** */
#if defined(FIO_CLI) && !defined(H___FIO_CLI___H) && !defined(FIO_STL_KEEP__)
#define H___FIO_CLI___H 1
/* *****************************************************************************
Internal Macro Implementation
***************************************************************************** */
/** Used internally. */
#define FIO_CLI_STRING__TYPE_I 0x1
#define FIO_CLI_BOOL__TYPE_I 0x2
#define FIO_CLI_INT__TYPE_I 0x3
#define FIO_CLI_PRINT__TYPE_I 0x4
#define FIO_CLI_PRINT_LINE__TYPE_I 0x5
#define FIO_CLI_PRINT_HEADER__TYPE_I 0x6
/** Indicates the CLI argument should be a String (default). */
#define FIO_CLI_STRING(line) (line), ((char *)FIO_CLI_STRING__TYPE_I)
/** Indicates the CLI argument is a Boolean value. */
#define FIO_CLI_BOOL(line) (line), ((char *)FIO_CLI_BOOL__TYPE_I)
/** Indicates the CLI argument should be an Integer (numerical). */
#define FIO_CLI_INT(line) (line), ((char *)FIO_CLI_INT__TYPE_I)
/** Indicates the CLI string should be printed as is with proper offset. */
#define FIO_CLI_PRINT(line) (line), ((char *)FIO_CLI_PRINT__TYPE_I)
/** Indicates the CLI string should be printed as is with no offset. */
#define FIO_CLI_PRINT_LINE(line) (line), ((char *)FIO_CLI_PRINT_LINE__TYPE_I)
/** Indicates the CLI string should be printed as a header. */
#define FIO_CLI_PRINT_HEADER(line) \
(line), ((char *)FIO_CLI_PRINT_HEADER__TYPE_I)
/* *****************************************************************************
CLI API
***************************************************************************** */
/**
* This function parses the Command Line Interface (CLI), creating a temporary
* "dictionary" that allows easy access to the CLI using their names or aliases.
*
* Command line arguments may be typed. If an optional type requirement is
* provided and the provided arument fails to match the required type, execution
* will end and an error message will be printed along with a short "help".
*
* The function / macro accepts the following arguments:
* - `argc`: command line argument count.
* - `argv`: command line argument list (array).
* - `unnamed_min`: the required minimum of un-named arguments.
* - `unnamed_max`: the maximum limit of un-named arguments.
* - `description`: a C string containing the program's description.
* - named arguments list: a list of C strings describing named arguments.
*
* The following optional type requirements are:
*
* * FIO_CLI_STRING(desc_line) - (default) string argument.
* * FIO_CLI_BOOL(desc_line) - boolean argument (no value).
* * FIO_CLI_INT(desc_line) - integer argument.
* * FIO_CLI_PRINT_HEADER(desc_line) - extra header for output.
* * FIO_CLI_PRINT(desc_line) - extra information for output.
*
* Argument names MUST start with the '-' character. The first word starting
* without the '-' character will begin the description for the CLI argument.
*
* The arguments "-?", "-h", "-help" and "--help" are automatically handled
* unless overridden.
*
* Un-named arguments shouldn't be listed in the named arguments list.
*
* Example use:
*
* fio_cli_start(argc, argv, 0, 0, "The NAME example accepts the following:",
* FIO_CLI_PRINT_HREADER("Concurrency:"),
* FIO_CLI_INT("-t -thread number of threads to run."),
* FIO_CLI_INT("-w -workers number of workers to run."),
* FIO_CLI_PRINT_HREADER("Address Binding:"),
* "-b, -address the address to bind to.",
* FIO_CLI_INT("-p,-port the port to bind to."),
* FIO_CLI_PRINT("\t\tset port to zero (0) for Unix s."),
* FIO_CLI_PRINT_HREADER("Logging:"),
* FIO_CLI_BOOL("-v -log enable logging."));
*
*
* This would allow access to the named arguments:
*
* fio_cli_get("-b") == fio_cli_get("-address");
*
*
* Once all the data was accessed, free the parsed data dictionary using:
*
* fio_cli_end();
*
* It should be noted, arguments will be recognized in a number of forms, i.e.:
*
* app -t=1 -p3000 -a localhost
*
* This function is NOT thread safe.
*/
#define fio_cli_start(argc, argv, unnamed_min, unnamed_max, description, ...) \
fio_cli_start((argc), \
(argv), \
(unnamed_min), \
(unnamed_max), \
(description), \
(char const *[]){__VA_ARGS__, (char const *)NULL})
/**
* Never use the function directly, always use the MACRO, because the macro
* attaches a NULL marker at the end of the `names` argument collection.
*/
SFUNC void fio_cli_start FIO_NOOP(int argc,
char const *argv[],
int unnamed_min,
int unnamed_max,
char const *description,
char const **names);
/**
* Clears the memory used by the CLI dictionary, removing all parsed data.
*
* This function is NOT thread safe.
*/
SFUNC void fio_cli_end(void);
/** Returns the argument's value as a NUL terminated C String. */
SFUNC char const *fio_cli_get(char const *name);
/** Returns the argument's value as an integer. */
SFUNC int fio_cli_get_i(char const *name);
/** This MACRO returns the argument's value as a boolean. */
#define fio_cli_get_bool(name) (fio_cli_get((name)) != NULL)
/** Returns the number of unnamed argument. */
SFUNC unsigned int fio_cli_unnamed_count(void);
/** Returns the unnamed argument using a 0 based `index`. */
SFUNC char const *fio_cli_unnamed(unsigned int index);
/**
* Sets the argument's value as a NUL terminated C String (no copy!).
*
* CAREFUL: This does not automatically detect aliases or type violations! it
* will only effect the specific name given, even if invalid. i.e.:
*
* fio_cli_start(argc, argv,
* "this is example accepts the following options:",
* "-p -port the port to bind to", FIO_CLI_INT;
*
* fio_cli_set("-p", "hello"); // fio_cli_get("-p") != fio_cli_get("-port");
*
* Note: this does NOT copy the C strings to memory. Memory should be kept alive
* until `fio_cli_end` is called.
*
* This function is NOT thread safe.
*/
SFUNC void fio_cli_set(char const *name, char const *value);
/**
* This MACRO is the same as:
*
* if(!fio_cli_get(name)) {
* fio_cli_set(name, value)
* }
*
* See fio_cli_set for notes and restrictions.
*/
#define fio_cli_set_default(name, value) \
if (!fio_cli_get((name))) \
fio_cli_set(name, value);
/* *****************************************************************************
CLI Implementation
***************************************************************************** */
#ifdef FIO_EXTERN_COMPLETE
/* *****************************************************************************
CLI Data Stores
***************************************************************************** */
typedef struct {
const char *buf;
size_t len;
} fio___cli_cstr_s;
#define FIO_RISKY_HASH
#define FIO_MAP_TYPE const char *
#define FIO_MAP_KEY fio___cli_cstr_s
#define FIO_MAP_KEY_CMP(o1, o2) \
(o1.len == o2.len && \
(!o1.len || o1.buf == o2.buf || \
(o1.buf && o2.buf && !memcmp(o1.buf, o2.buf, o1.len))))
#define FIO_UMAP_NAME fio___cli_hash
#define FIO_STL_KEEP__
#include __FILE__
#undef FIO_STL_KEEP__
static fio___cli_hash_s fio___cli_aliases = FIO_MAP_INIT;
static fio___cli_hash_s fio___cli_values = FIO_MAP_INIT;
static size_t fio___cli_unnamed_count = 0;
typedef struct {
int unnamed_min;
int unnamed_max;
int pos;
int unnamed_count;
int argc;
char const **argv;
char const *description;
char const **names;
} fio_cli_parser_data_s;
#define FIO_CLI_HASH_VAL(s) \
fio_risky_hash((s).buf, (s).len, (uint64_t)(uintptr_t)fio_cli_start)
/* *****************************************************************************
Default parameter storage
***************************************************************************** */
static fio___cli_cstr_s fio___cli_default_values;
/** extracts the "default" marker from a string's line */
FIO_SFUNC fio___cli_cstr_s fio___cli_map_line2default(char const *line) {
fio___cli_cstr_s n = {.buf = line};
/* skip aliases */
while (n.buf[n.len] == '-') {
while (n.buf[n.len] && n.buf[n.len] != ' ' && n.buf[n.len] != ',')
++n.len;
while (n.buf[n.len] && (n.buf[n.len] == ' ' || n.buf[n.len] == ',')) {
++n.len;
}
n.buf += n.len;
n.len = 0;
}
/* a default is maked with (value) or ("value"), both escapable with '\\' */
if (n.buf[0] != '(')
goto no_default;
++n.buf;
if (n.buf[0] == '"') {
++n.buf;
/* seek default value end with `")` */
while (n.buf[n.len] && !(n.buf[n.len] == '"' && n.buf[n.len + 1] == ')'))
++n.len;
if ((n.buf[n.len] != '"' || n.buf[n.len + 1] != ')'))
goto no_default;
} else {
/* seek default value end with `)` */
while (n.buf[n.len] && n.buf[n.len] != ')')
++n.len;
if (n.buf[n.len] != ')')
goto no_default;
}
return n;
no_default:
n.buf = NULL;
n.len = 0;
return n;
}
FIO_IFUNC fio___cli_cstr_s fio___cli_map_store_default(fio___cli_cstr_s d) {
fio___cli_cstr_s val = {.buf = NULL, .len = 0};
if (!d.len || !d.buf)
return val;
{
void *tmp = FIO_MEM_REALLOC_((void *)fio___cli_default_values.buf,
fio___cli_default_values.len,
fio___cli_default_values.len + d.len + 1,
fio___cli_default_values.len);
if (!tmp)
return val;
fio___cli_default_values.buf = (const char *)tmp;
}
val.buf = fio___cli_default_values.buf + fio___cli_default_values.len;
val.len = d.len;
fio___cli_default_values.len += d.len + 1;
((char *)val.buf)[val.len] = 0;
FIO_MEMCPY((char *)val.buf, d.buf, val.len);
FIO_LOG_DEBUG("CLI stored a string: %s", val.buf);
return val;
}
/* *****************************************************************************
CLI Parsing
***************************************************************************** */
FIO_SFUNC void fio___cli_map_line2alias(char const *line) {
fio___cli_cstr_s n = {.buf = line};
/* if a line contains a default value, store that value with the aliases. */
fio___cli_cstr_s def =
fio___cli_map_store_default(fio___cli_map_line2default(line));
while (n.buf[0] == '-') {
while (n.buf[n.len] && n.buf[n.len] != ' ' && n.buf[n.len] != ',') {
++n.len;
}
const char *old = NULL;
fio___cli_hash_set(&fio___cli_aliases,
FIO_CLI_HASH_VAL(n),
n,
(char const *)line,
&old);
if (def.buf) {
fio___cli_hash_set(&fio___cli_values,
FIO_CLI_HASH_VAL(n),
n,
def.buf,
NULL);
}
#ifdef FIO_LOG_ERROR
if (old) {
FIO_LOG_ERROR("CLI argument name conflict detected\n"
" The following two directives conflict:\n"
"\t%s\n\t%s\n",
old,
line);
}
#endif
while (n.buf[n.len] && (n.buf[n.len] == ' ' || n.buf[n.len] == ',')) {
++n.len;
}
n.buf += n.len;
n.len = 0;
}
}
FIO_SFUNC char const *fio___cli_get_line_type(fio_cli_parser_data_s *parser,
const char *line) {
if (!line) {
return NULL;
}
char const **pos = parser->names;
while (*pos) {
switch ((intptr_t)*pos) {
case FIO_CLI_STRING__TYPE_I: /* fallthrough */
case FIO_CLI_BOOL__TYPE_I: /* fallthrough */
case FIO_CLI_INT__TYPE_I: /* fallthrough */
case FIO_CLI_PRINT__TYPE_I: /* fallthrough */
case FIO_CLI_PRINT_LINE__TYPE_I: /* fallthrough */
case FIO_CLI_PRINT_HEADER__TYPE_I: /* fallthrough */
++pos;
continue;
}
if (line == *pos) {
goto found;
}
++pos;
}
return NULL;
found:
switch ((size_t)pos[1]) {
case FIO_CLI_STRING__TYPE_I: /* fallthrough */
case FIO_CLI_BOOL__TYPE_I: /* fallthrough */
case FIO_CLI_INT__TYPE_I: /* fallthrough */
case FIO_CLI_PRINT__TYPE_I: /* fallthrough */
case FIO_CLI_PRINT_LINE__TYPE_I: /* fallthrough */
case FIO_CLI_PRINT_HEADER__TYPE_I: /* fallthrough */
return pos[1];
}
return NULL;
}
FIO_SFUNC void fio___cli_print_line(char const *desc, char const *name) {
char buf[1024];
size_t pos = 0;
while (name[0] == '.' || name[0] == '/')
++name;
while (*desc) {
if (desc[0] == 'N' && desc[1] == 'A' && desc[2] == 'M' && desc[3] == 'E') {
buf[pos++] = 0;
desc += 4;
fprintf(stderr, "%s%s", buf, name);
pos = 0;
} else {
buf[pos++] = *desc;
++desc;
if (pos >= 980) {
buf[pos++] = 0;
fwrite(buf, pos, sizeof(*buf), stderr);
pos = 0;
}
}
}
if (pos)
fwrite(buf, pos, sizeof(*buf), stderr);
}
FIO_SFUNC void fio___cli_set_arg(fio___cli_cstr_s arg,
char const *value,
char const *line,
fio_cli_parser_data_s *parser) {
char const *type = NULL;
/* handle unnamed argument */
if (!line || !arg.len) {
if (!value) {
goto print_help;
}
if (!strcmp(value, "-?") || !strcasecmp(value, "-h") ||
!strcasecmp(value, "-help") || !strcasecmp(value, "--help")) {
goto print_help;
}
fio___cli_cstr_s n = {.len = (size_t)++parser->unnamed_count};
fio___cli_hash_set(&fio___cli_values, n.len, n, value, NULL);
if (parser->unnamed_max >= 0 &&
parser->unnamed_count > parser->unnamed_max) {
arg.len = 0;
goto error;
}
FIO_LOG_DEBUG2("(CLI) set an unnamed argument: %s", value);
FIO_ASSERT_DEBUG(fio___cli_hash_get(&fio___cli_values, n.len, n) == value,
"(CLI) set argument failed!");
return;
}
/* validate data types */
type = fio___cli_get_line_type(parser, line);
switch ((size_t)type) {
case FIO_CLI_BOOL__TYPE_I:
if (value && value != parser->argv[parser->pos + 1]) {
while (*value) {
/* support grouped boolean flags with one `-`*/
char bf[3] = {'-', *value, 0};
++value;
fio___cli_cstr_s a = {.buf = bf, .len = 2};
const char *l =
fio___cli_hash_get(&fio___cli_aliases, FIO_CLI_HASH_VAL(a), a);
if (!l) {
if (bf[1] == ',')
continue;
value = arg.buf + arg.len;
goto error;
}
const char *t = fio___cli_get_line_type(parser, l);
if (t != (char *)FIO_CLI_BOOL__TYPE_I) {
value = arg.buf + arg.len;
goto error;
}
fio___cli_set_arg(a, parser->argv[parser->pos + 1], l, parser);
}
}
value = "1";
break;
case FIO_CLI_INT__TYPE_I:
if (value) {
char const *tmp = value;
fio_atol((char **)&tmp);
if (*tmp) {
goto error;
}
}
/* fallthrough */
case FIO_CLI_STRING__TYPE_I:
if (!value)
goto error;
if (!value[0])
goto finish;
break;
}
/* add values using all aliases possible */
{
fio___cli_cstr_s n = {.buf = line};
while (n.buf[0] == '-') {
while (n.buf[n.len] && n.buf[n.len] != ' ' && n.buf[n.len] != ',') {
++n.len;
}
fio___cli_hash_set(&fio___cli_values,
FIO_CLI_HASH_VAL(n),
n,
value,
NULL);
FIO_LOG_DEBUG2("(CLI) set argument %.*s = %s", (int)n.len, n.buf, value);
FIO_ASSERT_DEBUG(fio___cli_hash_get(&fio___cli_values,
FIO_CLI_HASH_VAL(n),
n) == value,
"(CLI) set argument failed!");
while (n.buf[n.len] && (n.buf[n.len] == ' ' || n.buf[n.len] == ',')) {
++n.len;
}
n.buf += n.len;
n.len = 0;
}
}
finish:
/* handle additional argv progress (if value is on separate argv) */
if (value && parser->pos < parser->argc &&
value == parser->argv[parser->pos + 1])
++parser->pos;
return;
error: /* handle errors*/
FIO_LOG_DEBUG2("(CLI) error detected, printing help and exiting.");
fprintf(stderr,
"\n\r\x1B[31mError:\x1B[0m invalid argument %.*s %s %s\n\n",
(int)arg.len,
arg.buf,
arg.len ? "with value" : "",
value ? (value[0] ? value : "(empty)") : "(null)");
print_help:
if (parser->description) {
fprintf(stderr, "\n");
fio___cli_print_line(parser->description, parser->argv[0]);
fprintf(stderr, "\n");
} else {
const char *name_tmp = parser->argv[0];
while (name_tmp[0] == '.' || name_tmp[0] == '/')
++name_tmp;
fprintf(stderr,
"\nAvailable command-line options for \x1B[1m%s\x1B[0m:\n",
name_tmp);
}
/* print out each line's arguments */
char const **pos = parser->names;
while (*pos) {
switch ((intptr_t)*pos) {
case FIO_CLI_STRING__TYPE_I: /* fallthrough */
case FIO_CLI_BOOL__TYPE_I: /* fallthrough */
case FIO_CLI_INT__TYPE_I: /* fallthrough */
case FIO_CLI_PRINT__TYPE_I: /* fallthrough */
case FIO_CLI_PRINT_LINE__TYPE_I: /* fallthrough */
case FIO_CLI_PRINT_HEADER__TYPE_I:
++pos;
continue;
}
type = (char *)FIO_CLI_STRING__TYPE_I;
switch ((intptr_t)pos[1]) {
case FIO_CLI_PRINT__TYPE_I:
fprintf(stderr, " \t ");
fio___cli_print_line(pos[0], parser->argv[0]);
fprintf(stderr, "\n");
pos += 2;
continue;
case FIO_CLI_PRINT_LINE__TYPE_I:
fio___cli_print_line(pos[0], parser->argv[0]);
fprintf(stderr, "\n");
pos += 2;
continue;
case FIO_CLI_PRINT_HEADER__TYPE_I:
fprintf(stderr, "\n\x1B[4m");
fio___cli_print_line(pos[0], parser->argv[0]);
fprintf(stderr, "\x1B[0m\n");
pos += 2;
continue;
case FIO_CLI_STRING__TYPE_I: /* fallthrough */
case FIO_CLI_BOOL__TYPE_I: /* fallthrough */
case FIO_CLI_INT__TYPE_I: /* fallthrough */
type = pos[1];
}
/* print line @ pos, starting with main argument name */
int alias_count = 0;
int first_len = 0;
size_t tmp = 0;
char const *const p = *pos;
fio___cli_cstr_s def = fio___cli_map_line2default(p);
while (p[tmp] == '-') {
while (p[tmp] && p[tmp] != ' ' && p[tmp] != ',') {
if (!alias_count)
++first_len;
++tmp;
}
++alias_count;
while (p[tmp] && (p[tmp] == ' ' || p[tmp] == ',')) {
++tmp;
}
}
if (def.len) {
tmp = (size_t)((def.buf + def.len + 1) - p);
tmp += (p[tmp] == ')'); /* in case of `")` */
while (p[tmp] && (p[tmp] == ' ' || p[tmp] == ',')) {
++tmp;
}
}
switch ((size_t)type) {
case FIO_CLI_STRING__TYPE_I:
fprintf(stderr,
" \x1B[1m%-10.*s\x1B[0m\x1B[2m\t\"\" \x1B[0m%s\n",
first_len,
p,
p + tmp);
break;
case FIO_CLI_BOOL__TYPE_I:
fprintf(stderr, " \x1B[1m%-10.*s\x1B[0m\t %s\n", first_len, p, p + tmp);
break;
case FIO_CLI_INT__TYPE_I:
fprintf(stderr,
" \x1B[1m%-10.*s\x1B[0m\x1B[2m\t## \x1B[0m%s\n",
first_len,
p,
p + tmp);
break;
}
/* print alias information */
tmp = first_len;
while (p[tmp] && (p[tmp] == ' ' || p[tmp] == ',')) {
++tmp;
}
while (p[tmp] == '-') {
const size_t start = tmp;
while (p[tmp] && p[tmp] != ' ' && p[tmp] != ',') {
++tmp;
}
int padding = first_len - (tmp - start);
if (padding < 0)
padding = 0;
switch ((size_t)type) {
case FIO_CLI_STRING__TYPE_I:
fprintf(stderr,
" \x1B[1m%-10.*s\x1B[0m\x1B[2m\t\"\" \x1B[0m%.*s\x1B[2msame as "
"%.*s\x1B[0m\n",
(int)(tmp - start),
p + start,
padding,
"",
first_len,
p);
break;
case FIO_CLI_BOOL__TYPE_I:
fprintf(stderr,
" \x1B[1m%-10.*s\x1B[0m\t %.*s\x1B[2msame as %.*s\x1B[0m\n",
(int)(tmp - start),
p + start,
padding,
"",
first_len,
p);
break;
case FIO_CLI_INT__TYPE_I:
fprintf(stderr,
" \x1B[1m%-10.*s\x1B[0m\x1B[2m\t## \x1B[0m%.*s\x1B[2msame as "
"%.*s\x1B[0m\n",
(int)(tmp - start),
p + start,
padding,
"",
first_len,
p);
break;
}
}
/* print default information */
if (def.len)
fprintf(stderr,
" \t\x1B[2mdefault value: %.*s\x1B[0m\n",
(int)def.len,
def.buf);
++pos;
}
fprintf(stderr,
"\nUse any of the following input formats:\n"
"\t-arg <value>\t-arg=<value>\t-arg<value>\n"
"\n"
"Use \x1B[1m-h\x1B[0m , \x1B[1m-help\x1B[0m or "
"\x1B[1m-?\x1B[0m "
"to get this information again.\n"
"\n");
fio_cli_end();
exit(0);
}
/* *****************************************************************************
CLI Initialization
***************************************************************************** */
void fio_cli_start___(void); /* sublime text marker */
SFUNC void fio_cli_start FIO_NOOP(int argc,
char const *argv[],
int unnamed_min,
int unnamed_max,
char const *description,
char const **names) {
if (unnamed_max >= 0 && unnamed_max < unnamed_min)
unnamed_max = unnamed_min;
fio_cli_parser_data_s parser = {
.unnamed_min = unnamed_min,
.unnamed_max = unnamed_max,
.pos = 0,
.argc = argc,
.argv = argv,
.description = description,
.names = names,
};
if (fio___cli_hash_count(&fio___cli_values)) {
fio_cli_end();
}
/* prepare aliases hash map */
char const **line = names;
while (*line) {
switch ((intptr_t)*line) {
case FIO_CLI_STRING__TYPE_I: /* fallthrough */
case FIO_CLI_BOOL__TYPE_I: /* fallthrough */
case FIO_CLI_INT__TYPE_I: /* fallthrough */
case FIO_CLI_PRINT__TYPE_I: /* fallthrough */
case FIO_CLI_PRINT_LINE__TYPE_I: /* fallthrough */
case FIO_CLI_PRINT_HEADER__TYPE_I: /* fallthrough */
++line;
continue;
}
if (line[1] != (char *)FIO_CLI_PRINT__TYPE_I &&
line[1] != (char *)FIO_CLI_PRINT_LINE__TYPE_I &&
line[1] != (char *)FIO_CLI_PRINT_HEADER__TYPE_I)
fio___cli_map_line2alias(*line);
++line;
}
/* parse existing arguments */
while ((++parser.pos) < argc) {
char const *value = NULL;
fio___cli_cstr_s n = {.buf = argv[parser.pos],
.len = strlen(argv[parser.pos])};
if (parser.pos + 1 < argc) {
value = argv[parser.pos + 1];
}
const char *l = NULL;
while (
n.len &&
!(l = fio___cli_hash_get(&fio___cli_aliases, FIO_CLI_HASH_VAL(n), n))) {
--n.len;
value = n.buf + n.len;
}
if (n.len && value && value[0] == '=') {
++value;
}
// fprintf(stderr, "Setting %.*s to %s\n", (int)n.len, n.buf, value);
fio___cli_set_arg(n, value, l, &parser);
}
/* Cleanup and save state for API */
fio___cli_hash_destroy(&fio___cli_aliases);
fio___cli_unnamed_count = parser.unnamed_count;
/* test for required unnamed arguments */
if (parser.unnamed_count < parser.unnamed_min)
fio___cli_set_arg((fio___cli_cstr_s){.len = 0}, NULL, NULL, &parser);
}
/* *****************************************************************************
CLI Destruction
***************************************************************************** */
SFUNC void __attribute__((destructor)) fio_cli_end(void) {
fio___cli_hash_destroy(&fio___cli_values);
fio___cli_hash_destroy(&fio___cli_aliases);
fio___cli_unnamed_count = 0;
if (fio___cli_default_values.buf) {
FIO_MEM_FREE_((void *)fio___cli_default_values.buf,
fio___cli_default_values.len);
fio___cli_default_values.buf = NULL;
fio___cli_default_values.len = 0;
}
}
/* *****************************************************************************
CLI Data Access API
***************************************************************************** */
/** Returns the argument's value as a NUL terminated C String. */
SFUNC char const *fio_cli_get(char const *name) {
fio___cli_cstr_s n = {.buf = name, .len = strlen(name)};
if (!fio___cli_hash_count(&fio___cli_values)) {
return NULL;
}
char const *val =
fio___cli_hash_get(&fio___cli_values, FIO_CLI_HASH_VAL(n), n);
return val;
}
/** Returns the argument's value as an integer. */
SFUNC int fio_cli_get_i(char const *name) {
char const *val = fio_cli_get(name);
return fio_atol((char **)&val);
}
/** Returns the number of unrecognized argument. */
SFUNC unsigned int fio_cli_unnamed_count(void) {
return (unsigned int)fio___cli_unnamed_count;
}
/** Returns the unrecognized argument using a 0 based `index`. */
SFUNC char const *fio_cli_unnamed(unsigned int index) {
if (!fio___cli_hash_count(&fio___cli_values) || !fio___cli_unnamed_count) {
return NULL;
}
fio___cli_cstr_s n = {.buf = NULL, .len = index + 1};
return fio___cli_hash_get(&fio___cli_values, index + 1, n);
}
/**
* Sets the argument's value as a NUL terminated C String (no copy!).
*
* Note: this does NOT copy the C strings to memory. Memory should be kept
* alive until `fio_cli_end` is called.
*/
SFUNC void fio_cli_set(char const *name, char const *value) {
fio___cli_cstr_s n = (fio___cli_cstr_s){.buf = name, .len = strlen(name)};
fio___cli_hash_set(&fio___cli_values, FIO_CLI_HASH_VAL(n), n, value, NULL);
}
/* *****************************************************************************
CLI - test
***************************************************************************** */
#ifdef FIO_TEST_CSTL
FIO_SFUNC void FIO_NAME_TEST(stl, cli)(void) {
const char *argv[] = {
"appname",
"-i11",
"-i2=2",
"-i3",
"3",
"-t,u",
"-s",
"test",
"unnamed",
};
const int argc = sizeof(argv) / sizeof(argv[0]);
fprintf(stderr, "* Testing CLI helpers.\n");
{ /* avoid macro for C++ */
const char *arguments[] = {
FIO_CLI_INT("-integer1 -i1 first integer"),
FIO_CLI_INT("-integer2 -i2 second integer"),
FIO_CLI_INT("-integer3 -i3 third integer"),
FIO_CLI_INT("-integer4 -i4 (4) fourth integer"),
FIO_CLI_INT("-integer5 -i5 (\"5\") fifth integer"),
FIO_CLI_BOOL("-boolean -t boolean"),
FIO_CLI_BOOL("-boolean2 -u boolean"),
FIO_CLI_BOOL("-boolean_false -f boolean"),
FIO_CLI_STRING("-str -s a string"),
FIO_CLI_PRINT_HEADER("Printing stuff"),
FIO_CLI_PRINT_LINE("does nothing, but shouldn't crash either"),
FIO_CLI_PRINT("does nothing, but shouldn't crash either"),
NULL,
};
fio_cli_start FIO_NOOP(argc, argv, 0, -1, NULL, arguments);
}
FIO_ASSERT(fio_cli_get_i("-i2") == 2, "CLI second integer error.");
FIO_ASSERT(fio_cli_get_i("-i3") == 3, "CLI third integer error.");
FIO_ASSERT(fio_cli_get_i("-i4") == 4,
"CLI fourth integer error (%s).",
fio_cli_get("-i4"));
FIO_ASSERT(fio_cli_get_i("-i5") == 5,
"CLI fifth integer error (%s).",
fio_cli_get("-i5"));
FIO_ASSERT(fio_cli_get_i("-i1") == 1, "CLI first integer error.");
FIO_ASSERT(fio_cli_get_i("-i2") == fio_cli_get_i("-integer2"),
"CLI second integer error.");
FIO_ASSERT(fio_cli_get_i("-i3") == fio_cli_get_i("-integer3"),
"CLI third integer error.");
FIO_ASSERT(fio_cli_get_i("-i1") == fio_cli_get_i("-integer1"),
"CLI first integer error.");
FIO_ASSERT(fio_cli_get_i("-t") == 1, "CLI boolean true error.");
FIO_ASSERT(fio_cli_get_i("-u") == 1, "CLI boolean 2 true error.");
FIO_ASSERT(fio_cli_get_i("-f") == 0, "CLI boolean false error.");
FIO_ASSERT(!strcmp(fio_cli_get("-s"), "test"), "CLI string error.");
FIO_ASSERT(fio_cli_unnamed_count() == 1, "CLI unnamed count error.");
FIO_ASSERT(!strcmp(fio_cli_unnamed(0), "unnamed"), "CLI unnamed error.");
fio_cli_set("-manual", "okay");
FIO_ASSERT(!strcmp(fio_cli_get("-manual"), "okay"), "CLI set/get error.");
fio_cli_end();
FIO_ASSERT(fio_cli_get_i("-i1") == 0, "CLI cleanup error.");
}
#endif /* FIO_TEST_CSTL */
/* *****************************************************************************
CLI - cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE*/
#endif /* FIO_CLI */
#undef FIO_CLI
|
janbiedermann/cstl
|
stl_slices/210 map api.h
|
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#define FIO_UMAP_NAME umap /* Development inclusion - ignore line */
#define FIO_MAP_TEST /* Development inclusion - ignore line */
#include "004 bitwise.h" /* Development inclusion - ignore line */
#include "100 mem.h" /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
Common Map Settings (ordered / unordered)
***************************************************************************** */
#if defined(FIO_UMAP_NAME)
#ifndef FIO_MAP_NAME
#define FIO_MAP_NAME FIO_UMAP_NAME
#endif
#ifndef FIO_MAP_ORDERED
#define FIO_MAP_ORDERED 0
#endif
#elif defined(FIO_OMAP_NAME)
#ifndef FIO_MAP_NAME
#define FIO_MAP_NAME FIO_OMAP_NAME
#endif
#ifndef FIO_MAP_ORDERED
#define FIO_MAP_ORDERED 1
#endif
#else
#ifndef FIO_MAP_ORDERED
#define FIO_MAP_ORDERED 1
#endif
#endif
#ifdef FIO_MAP_NAME
/* *****************************************************************************
The following macros are used to customize the map.
***************************************************************************** */
#ifndef FIO_MAP_TYPE
/** The type for the elements in the map */
#define FIO_MAP_TYPE void *
/** An invalid value for that type (if any). */
#define FIO_MAP_TYPE_INVALID NULL
#else
#ifndef FIO_MAP_TYPE_INVALID
/** An invalid value for that type (if any). */
#define FIO_MAP_TYPE_INVALID ((FIO_MAP_TYPE){0})
#endif /* FIO_MAP_TYPE_INVALID */
#endif /* FIO_MAP_TYPE */
#ifndef FIO_MAP_TYPE_COPY
/** Handles a copy operation for an value. */
#define FIO_MAP_TYPE_COPY(dest, src) (dest) = (src)
/* internal flag - do not set */
#define FIO_MAP_TYPE_COPY_SIMPLE 1
#endif
#ifndef FIO_MAP_TYPE_DESTROY
/** Handles a destroy / free operation for a map's value. */
#define FIO_MAP_TYPE_DESTROY(obj)
/** internal flag - set only if the object desctructor is optional */
#define FIO_MAP_TYPE_DESTROY_SIMPLE 1
#else
#ifndef FIO_MAP_TYPE_DESTROY_SIMPLE
#define FIO_MAP_TYPE_DESTROY_SIMPLE 0
#endif
#endif
#ifndef FIO_MAP_TYPE_DISCARD
/** Handles discarded value data (i.e., insert without overwrite). */
#define FIO_MAP_TYPE_DISCARD(obj)
#endif
#ifndef FIO_MAP_TYPE_CMP
/** Handles a comparison operation for a map's value. */
#define FIO_MAP_TYPE_CMP(a, b) 1
#endif
/**
* The FIO_MAP_DESTROY_AFTER_COPY macro should be set if FIO_MAP_TYPE_DESTROY
* should be called after FIO_MAP_TYPE_COPY when an object is removed from the
* array after being copied to an external container (an `old` pointer)
*/
#ifndef FIO_MAP_DESTROY_AFTER_COPY
#if !FIO_MAP_TYPE_DESTROY_SIMPLE && !FIO_MAP_TYPE_COPY_SIMPLE
#define FIO_MAP_DESTROY_AFTER_COPY 1
#else
#define FIO_MAP_DESTROY_AFTER_COPY 0
#endif
#endif /* FIO_MAP_DESTROY_AFTER_COPY */
/* *****************************************************************************
Dictionary / Hash Map - a Hash Map is basically a Set of couplets
***************************************************************************** */
/* Defining a key makes a Hash Map instead of a Set */
#ifdef FIO_MAP_KEY
#ifndef FIO_MAP_KEY_INVALID
/** An invalid value for the hash map key type (if any). */
#define FIO_MAP_KEY_INVALID ((FIO_MAP_KEY){0})
#endif
#ifndef FIO_MAP_KEY_COPY
/** Handles a copy operation for a hash maps key. */
#define FIO_MAP_KEY_COPY(dest, src) (dest) = (src)
#endif
#ifndef FIO_MAP_KEY_DESTROY
/** Handles a destroy / free operation for a hash maps key. */
#define FIO_MAP_KEY_DESTROY(obj)
/** internal flag - set only if the object desctructor is optional */
#define FIO_MAP_KEY_DESTROY_SIMPLE 1
#else
#ifndef FIO_MAP_KEY_DESTROY_SIMPLE
#define FIO_MAP_KEY_DESTROY_SIMPLE 0
#endif
#endif
#ifndef FIO_MAP_KEY_DISCARD
/** Handles discarded element data (i.e., when overwriting only the value). */
#define FIO_MAP_KEY_DISCARD(obj)
#endif
#ifndef FIO_MAP_KEY_CMP
/** Handles a comparison operation for a hash maps key. */
#define FIO_MAP_KEY_CMP(a, b) 1
#endif
typedef struct {
FIO_MAP_KEY key;
FIO_MAP_TYPE value;
} FIO_NAME(FIO_MAP_NAME, couplet_s);
FIO_IFUNC void FIO_NAME(FIO_MAP_NAME, __couplet_copy)(
FIO_NAME(FIO_MAP_NAME, couplet_s) * dest,
FIO_NAME(FIO_MAP_NAME, couplet_s) * src) {
FIO_MAP_KEY_COPY((dest->key), (src->key));
FIO_MAP_TYPE_COPY((dest->value), (src->value));
}
FIO_IFUNC void FIO_NAME(FIO_MAP_NAME,
__couplet_destroy)(FIO_NAME(FIO_MAP_NAME, couplet_s) *
c) {
FIO_MAP_KEY_DESTROY(c->key);
FIO_MAP_TYPE_DESTROY(c->value);
(void)c; /* in case where macros do nothing */
}
/** FIO_MAP_OBJ is either a couplet (for hash maps) or the objet (for sets) */
#define FIO_MAP_OBJ FIO_NAME(FIO_MAP_NAME, couplet_s)
/** FIO_MAP_OBJ_KEY is FIO_MAP_KEY for hash maps or FIO_MAP_TYPE for sets */
#define FIO_MAP_OBJ_KEY FIO_MAP_KEY
#define FIO_MAP_OBJ_INVALID \
((FIO_NAME(FIO_MAP_NAME, couplet_s)){.key = FIO_MAP_KEY_INVALID, \
.value = FIO_MAP_TYPE_INVALID})
#define FIO_MAP_OBJ_COPY(dest, src) \
FIO_NAME(FIO_MAP_NAME, __couplet_copy)(&(dest), &(src))
#define FIO_MAP_OBJ_DESTROY(obj) \
FIO_NAME(FIO_MAP_NAME, __couplet_destroy)(&(obj))
#define FIO_MAP_OBJ_CMP(a, b) FIO_MAP_KEY_CMP((a).key, (b).key)
#define FIO_MAP_OBJ_KEY_CMP(a, key_) FIO_MAP_KEY_CMP((a).key, (key_))
#define FIO_MAP_OBJ2KEY(o) (o).key
#define FIO_MAP_OBJ2TYPE(o) (o).value
#define FIO_MAP_OBJ_DISCARD(o) \
do { \
FIO_MAP_TYPE_DISCARD(((o).value)); \
FIO_MAP_KEY_DISCARD(((o).key)); \
} while (0);
#if FIO_MAP_DESTROY_AFTER_COPY
#define FIO_MAP_OBJ_DESTROY_AFTER FIO_MAP_OBJ_DESTROY
#else
#define FIO_MAP_OBJ_DESTROY_AFTER(obj) FIO_MAP_KEY_DESTROY((obj).key);
#endif /* FIO_MAP_DESTROY_AFTER_COPY */
/* *****************************************************************************
Set Map
***************************************************************************** */
#else /* FIO_MAP_KEY */
#define FIO_MAP_KEY_DESTROY_SIMPLE 1
/** FIO_MAP_OBJ is either a couplet (for hash maps) or the objet (for sets) */
#define FIO_MAP_OBJ FIO_MAP_TYPE
/** FIO_MAP_OBJ_KEY is FIO_MAP_KEY for hash maps or FIO_MAP_TYPE for sets */
#define FIO_MAP_OBJ_KEY FIO_MAP_TYPE
#define FIO_MAP_OBJ_INVALID FIO_MAP_TYPE_INVALID
#define FIO_MAP_OBJ_COPY FIO_MAP_TYPE_COPY
#define FIO_MAP_OBJ_DESTROY FIO_MAP_TYPE_DESTROY
#define FIO_MAP_OBJ_CMP FIO_MAP_TYPE_CMP
#define FIO_MAP_OBJ_KEY_CMP FIO_MAP_TYPE_CMP
#define FIO_MAP_OBJ2KEY(o) (o)
#define FIO_MAP_OBJ2TYPE(o) (o)
#define FIO_MAP_OBJ_DISCARD FIO_MAP_TYPE_DISCARD
#define FIO_MAP_KEY_DISCARD(_ignore)
#define FIO_MAP_KEY_COPY(_ignore, _ignore2)
#if FIO_MAP_DESTROY_AFTER_COPY
#define FIO_MAP_OBJ_DESTROY_AFTER FIO_MAP_TYPE_DESTROY
#else
#define FIO_MAP_OBJ_DESTROY_AFTER(obj)
#endif /* FIO_MAP_DESTROY_AFTER_COPY */
#endif /* FIO_MAP_KEY */
/* *****************************************************************************
Misc Settings (eviction policy, load-factor attempts, etc')
***************************************************************************** */
#ifndef FIO_MAP_MAX_SEEK /* LIMITED to 255 */
#if FIO_MAP_ORDERED
/* The maximum number of bins to rotate when (partial/full) collisions occure */
#define FIO_MAP_MAX_SEEK (13U)
#else
#define FIO_MAP_MAX_SEEK (7U)
#endif
#endif
#ifndef FIO_MAP_MAX_FULL_COLLISIONS /* LIMITED to 255 */
/* The maximum number of full hash collisions that can be consumed */
#define FIO_MAP_MAX_FULL_COLLISIONS (22U)
#endif
#ifndef FIO_MAP_CUCKOO_STEPS
/* Prime numbers are better */
#define FIO_MAP_CUCKOO_STEPS (0x43F82D0BUL) /* should be a high prime */
#endif
#ifndef FIO_MAP_EVICT_LRU
/** Set the `evict` method to evict based on the Least Recently Used object. */
#define FIO_MAP_EVICT_LRU 0
#endif
#ifndef FIO_MAP_SHOULD_OVERWRITE
/** Tests if `older` should be replaced with `newer`. */
#define FIO_MAP_SHOULD_OVERWRITE(older, newer) 1
#endif
#ifndef FIO_MAP_MAX_ELEMENTS
/** The maximum number of elements allowed before removing old data (FIFO) */
#define FIO_MAP_MAX_ELEMENTS 0
#endif
#ifndef FIO_MAP_HASH
/** The type for map hash value (an X bit integer) */
#define FIO_MAP_HASH uint64_t
#endif
#undef FIO_MAP_HASH_FIXED
/** the value to be used when the hash is a reserved value. */
#define FIO_MAP_HASH_FIXED ((FIO_MAP_HASH)-2LL)
#undef FIO_MAP_HASH_FIX
/** Validates the hash value and returns the valid value. */
#define FIO_MAP_HASH_FIX(h) (!h ? FIO_MAP_HASH_FIXED : (h))
/**
* Unordered maps don't have to cache an object's hash.
*
* If the hash is cheap to calculate, it could be recalculated on the fly.
*/
#if defined(FIO_MAP_HASH_FN) && !FIO_MAP_ORDERED
FIO_IFUNC FIO_MAP_HASH FIO_NAME(FIO_MAP_NAME, __get_hash)(FIO_MAP_OBJ_KEY k) {
FIO_MAP_HASH h = FIO_MAP_HASH_FN(k);
h = FIO_MAP_HASH_FIX(h);
return h;
}
#define FIO_MAP_HASH_CACHED 0
#define FIO_MAP_HASH_GET_HASH(map_ptr, index) \
FIO_NAME(FIO_MAP_NAME, __get_hash) \
(FIO_MAP_OBJ2KEY((map_ptr)->map[(index)].obj))
#else
#define FIO_MAP_HASH_GET_HASH(map_ptr, index) (map_ptr)->map[(index)].hash
#define FIO_MAP_HASH_CACHED 1
#endif
#ifndef FIO_MAP_SEEK_AS_ARRAY_LOG_LIMIT
/* Hash to Array optimization limit in log2. MUST be less then 8. */
#define FIO_MAP_SEEK_AS_ARRAY_LOG_LIMIT 3
#endif
/**
* Normally, FIO_MAP uses 32bit internal indexing and types.
*
* This limits the map to approximately 2 billion items (2,147,483,648).
* Depending on possible 32 bit hash collisions, more items may be inserted.
*
* If FIO_MAP_BIG is be defined, 64 bit addressing is used, increasing the
* maximum number of items to... hmm... a lot (1 << 63).
*/
#ifdef FIO_MAP_BIG
#define FIO_MAP_SIZE_TYPE uint64_t
#define FIO_MAP_INDEX_USED_BIT ((uint64_t)1 << 63)
#else
#define FIO_MAP_SIZE_TYPE uint32_t
#define FIO_MAP_INDEX_USED_BIT ((uint32_t)1 << 31)
#endif /* FIO_MAP_BIG */
/* *****************************************************************************
Pointer Tagging Support
***************************************************************************** */
#ifdef FIO_PTR_TAG_TYPE
#define FIO_MAP_PTR FIO_PTR_TAG_TYPE
#else
#define FIO_MAP_PTR FIO_NAME(FIO_MAP_NAME, s) *
#endif
/* *****************************************************************************
Map API
***************************************************************************** */
/* *****************************************************************************
Types
***************************************************************************** */
/** The type for each member in the map. */
typedef struct FIO_NAME(FIO_MAP_NAME, each_s) FIO_NAME(FIO_MAP_NAME, each_s);
/** The Map Type (container) itself. */
typedef struct FIO_NAME(FIO_MAP_NAME, s) FIO_NAME(FIO_MAP_NAME, s);
#ifndef FIO_MAP_INIT
/* Initialization macro. */
#define FIO_MAP_INIT \
{ 0 }
#endif
struct FIO_NAME(FIO_MAP_NAME, each_s) {
/** the data being stored in the Map / key-value pair: obj.key obj.value. */
FIO_MAP_OBJ obj;
#if FIO_MAP_HASH_CACHED
/** a copy of the hash value. */
FIO_MAP_HASH hash;
#endif
#if FIO_MAP_EVICT_LRU
/** LRU evicion monitoring - do not access directly */
struct {
FIO_MAP_SIZE_TYPE next;
FIO_MAP_SIZE_TYPE prev;
} node;
#endif /* FIO_MAP_EVICT_LRU */
};
/* *****************************************************************************
Contruction API
***************************************************************************** */
/* do we have a constructor? */
#ifndef FIO_REF_CONSTRUCTOR_ONLY
/* Allocates a new object on the heap and initializes it's memory. */
FIO_IFUNC FIO_MAP_PTR FIO_NAME(FIO_MAP_NAME, new)(void);
/* Frees any internal data AND the object's container! */
FIO_IFUNC int FIO_NAME(FIO_MAP_NAME, free)(FIO_MAP_PTR map);
#endif /* FIO_REF_CONSTRUCTOR_ONLY */
/** Destroys the object, reinitializing its container. */
SFUNC void FIO_NAME(FIO_MAP_NAME, destroy)(FIO_MAP_PTR map);
/* *****************************************************************************
Get / Set / Remove
***************************************************************************** */
/** Gets a value from the map, returning a temporary pointer. */
SFUNC FIO_MAP_TYPE *FIO_NAME(FIO_MAP_NAME, get_ptr)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
FIO_MAP_OBJ_KEY key);
/** Sets a value in the map, returning a temporary pointer. */
SFUNC FIO_MAP_TYPE *FIO_NAME(FIO_MAP_NAME, set_ptr)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
#ifdef FIO_MAP_KEY
FIO_MAP_KEY key,
#endif /* FIO_MAP_KEY */
FIO_MAP_TYPE obj,
FIO_MAP_TYPE *old,
uint8_t overwrite);
/** Gets a value from the map, if exists. */
FIO_IFUNC FIO_MAP_TYPE FIO_NAME(FIO_MAP_NAME, get)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
FIO_MAP_OBJ_KEY key);
/** Sets a value in the map, overwriting existing data if any. */
FIO_IFUNC FIO_MAP_TYPE FIO_NAME(FIO_MAP_NAME, set)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
#ifdef FIO_MAP_KEY
FIO_MAP_KEY key,
#endif /* FIO_MAP_KEY */
FIO_MAP_TYPE obj,
FIO_MAP_TYPE *old);
/** Removes a value from the map. */
SFUNC int FIO_NAME(FIO_MAP_NAME, remove)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
FIO_MAP_OBJ_KEY key,
FIO_MAP_TYPE *old);
/** Sets the object only if missing. Otherwise keeps existing value. */
FIO_IFUNC FIO_MAP_TYPE FIO_NAME(FIO_MAP_NAME, set_if_missing)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
#ifdef FIO_MAP_KEY
FIO_MAP_KEY key,
#endif /* FIO_MAP_KEY */
FIO_MAP_TYPE obj);
/** Removes all objects from the map. */
SFUNC void FIO_NAME(FIO_MAP_NAME, clear)(FIO_MAP_PTR map);
/**
* If `FIO_MAP_EVICT_LRU` is defined, evicts `number_of_elements` least
* recently accessed.
*
* Otherwise, eviction is somewhat random and undefined.
*/
SFUNC int FIO_NAME(FIO_MAP_NAME, evict)(FIO_MAP_PTR map,
size_t number_of_elements);
/* *****************************************************************************
Object state information
***************************************************************************** */
/** Returns the maps current object count. */
FIO_IFUNC size_t FIO_NAME(FIO_MAP_NAME, count)(FIO_MAP_PTR map);
/** Returns the maps current theoretical capacity. */
FIO_IFUNC size_t FIO_NAME(FIO_MAP_NAME, capa)(FIO_MAP_PTR map);
/** Reservse enough space for a theoretical capacity of `capa` objects. */
SFUNC size_t FIO_NAME(FIO_MAP_NAME, reserve)(FIO_MAP_PTR map,
FIO_MAP_SIZE_TYPE capa);
/** Attempts to minimize memory use. */
SFUNC void FIO_NAME(FIO_MAP_NAME, compact)(FIO_MAP_PTR map);
/** Rehashes the map. No need to call this, rehashing is automatic. */
SFUNC int FIO_NAME(FIO_MAP_NAME, rehash)(FIO_MAP_PTR map);
/* *****************************************************************************
Iteration
***************************************************************************** */
/** Takes a previous (or NULL) item's position and returns the next. */
FIO_IFUNC FIO_NAME(FIO_MAP_NAME, each_s) *
FIO_NAME(FIO_MAP_NAME, each_next)(FIO_MAP_PTR map,
FIO_NAME(FIO_MAP_NAME, each_s) * *first,
FIO_NAME(FIO_MAP_NAME, each_s) * pos);
/**
* Iteration using a callback for each element in the map.
*
* The callback task function must accept an element variable as well as an
* opaque user pointer.
*
* If the callback returns -1, the loop is broken. Any other value is ignored.
*
* Returns the relative "stop" position, i.e., the number of items processed +
* the starting point.
*/
SFUNC FIO_MAP_SIZE_TYPE FIO_NAME(FIO_MAP_NAME,
each)(FIO_MAP_PTR map,
ssize_t start_at,
int (*task)(FIO_MAP_TYPE obj, void *arg),
void *arg);
#ifdef FIO_MAP_KEY
/** Returns an object's key while in an iteration callback. */
SFUNC FIO_MAP_KEY FIO_NAME(FIO_MAP_NAME, each_get_key)(void);
#else
/** Returns an object's key while in an iteration callback. */
SFUNC FIO_MAP_HASH FIO_NAME(FIO_MAP_NAME, each_get_key)(void);
#endif
/* *****************************************************************************
Common Map Implementation - inlined static functions
***************************************************************************** */
FIO_IFUNC FIO_MAP_TYPE FIO_NAME(FIO_MAP_NAME, get)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
FIO_MAP_OBJ_KEY key) {
FIO_MAP_TYPE *r = FIO_NAME(FIO_MAP_NAME, get_ptr)(map, hash, key);
if (!r)
return FIO_MAP_TYPE_INVALID;
return *r;
}
FIO_IFUNC FIO_MAP_TYPE FIO_NAME(FIO_MAP_NAME, set)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
#ifdef FIO_MAP_KEY
FIO_MAP_KEY key,
#endif /* FIO_MAP_KEY */
FIO_MAP_TYPE obj,
FIO_MAP_TYPE *old) {
FIO_MAP_TYPE *r = FIO_NAME(FIO_MAP_NAME, set_ptr)(map,
hash,
#ifdef FIO_MAP_KEY
key,
#endif /* FIO_MAP_KEY */
obj,
old,
1);
if (!r)
return FIO_MAP_TYPE_INVALID;
return *r;
}
FIO_IFUNC FIO_MAP_TYPE FIO_NAME(FIO_MAP_NAME,
set_if_missing)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
#ifdef FIO_MAP_KEY
FIO_MAP_KEY key,
#endif /* FIO_MAP_KEY */
FIO_MAP_TYPE obj) {
FIO_MAP_TYPE *r = FIO_NAME(FIO_MAP_NAME, set_ptr)(map,
hash,
#ifdef FIO_MAP_KEY
key,
#endif /* FIO_MAP_KEY */
obj,
NULL,
0);
if (!r)
return FIO_MAP_TYPE_INVALID;
return *r;
}
/* *****************************************************************************
Iteration Macro
***************************************************************************** */
#ifndef FIO_MAP_EACH
/**
* A macro for a `for` loop that iterates over all the Map's objects (in
* order).
*
* Use this macro for small Hash Maps / Sets.
*
* - `map_name` is the Map's type name / function prefix, same as FIO_MAP_NAME.
*
* - `map_p` is a pointer to the Hash Map / Set variable.
*
* - `pos` is a temporary variable name to be created for iteration. This
* variable may SHADOW external variables, be aware.
*
* To access the object information, use:
*
* - `pos->hash` to access the hash value.
*
* - `pos->obj` to access the object's data.
*
* For Hash Maps, use `pos->obj.key` and `pos->obj.value`.
*/
#define FIO_MAP_EACH(map_name, map_p, pos) \
for (FIO_NAME(map_name, \
each_s) *first___ = NULL, \
*pos = FIO_NAME(map_name, \
each_next)(map_p, &first___, NULL); \
pos; \
pos = FIO_NAME(map_name, each_next)(map_p, &first___, pos))
#endif
/* *****************************************************************************
Common Map Settings - Finish
***************************************************************************** */
#endif
|
janbiedermann/cstl
|
stl_slices/005 riskyhash.h
|
<filename>stl_slices/005 riskyhash.h
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#include "004 bitwise.h" /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
Risky Hash - a fast and simple hash
***************************************************************************** */
#if defined(FIO_RISKY_HASH) && !defined(H___FIO_RISKY_HASH_H)
#define H___FIO_RISKY_HASH_H
/* *****************************************************************************
Risky Hash - API
***************************************************************************** */
/** Computes a facil.io Risky Hash (Risky v.3). */
SFUNC uint64_t fio_risky_hash(const void *buf, size_t len, uint64_t seed);
/** Adds bit of entropy to pointer values. Designed to be unsafe. */
FIO_IFUNC uint64_t fio_risky_ptr(void *ptr);
/**
* Masks data using a Risky Hash and a counter mode nonce.
*
* Used for mitigating memory access attacks when storing "secret" information
* in memory.
*
* Keep the nonce information in a different memory address then the secret. For
* example, if the secret is on the stack, store the nonce on the heap or using
* a static variable.
*
* Don't use the same nonce-secret combination for other data.
*
* This is NOT a cryptographically secure encryption. Even if the algorithm was
* secure, it would provide no more then a 32bit level encryption, which isn't
* strong enough for any cryptographic use-case.
*
* However, this could be used to mitigate memory probing attacks. Secrets
* stored in the memory might remain accessible after the program exists or
* through core dump information. By storing "secret" information masked in this
* way, it mitigates the risk of secret information being recognized or
* deciphered.
*/
IFUNC void fio_risky_mask(char *buf, size_t len, uint64_t key, uint64_t nonce);
/* *****************************************************************************
Risky Hash - Implementation
Note: I don't remember what information I used when designing this, but Risky
Hash is probably NOT cryptographically safe (though I wanted it to be).
Here's a few resources about hashes that might explain more:
- https://komodoplatform.com/cryptographic-hash-function/
- https://en.wikipedia.org/wiki/Avalanche_effect
- http://ticki.github.io/blog/designing-a-good-non-cryptographic-hash-function/
***************************************************************************** */
/* Risky Hash primes */
#define FIO_RISKY3_PRIME0 0xCAEF89D1E9A5EB21ULL
#define FIO_RISKY3_PRIME1 0xAB137439982B86C9ULL
#define FIO_RISKY3_PRIME2 0xD9FDC73ABE9EDECDULL
#define FIO_RISKY3_PRIME3 0x3532D520F9511B13ULL
#define FIO_RISKY3_PRIME4 0x038720DDEB5A8415ULL
/** Adds bit entropy to a pointer values. Designed to be unsafe. */
FIO_IFUNC uint64_t fio_risky_ptr(void *ptr) {
uint64_t n = (uint64_t)(uintptr_t)ptr;
n ^= ((n >> 3) ^ FIO_RISKY3_PRIME0) * FIO_RISKY3_PRIME2;
return n;
}
#ifdef FIO_EXTERN_COMPLETE
/* Risky Hash initialization constants */
#define FIO_RISKY3_IV0 0x0000001000000001ULL
#define FIO_RISKY3_IV1 0x0000010000000010ULL
#define FIO_RISKY3_IV2 0x0000100000000100ULL
#define FIO_RISKY3_IV3 0x0001000000001000ULL
/* read u64 in little endian */
#define FIO_RISKY_BUF2U64 fio_buf2u64_little
/* switch to 0 if the compiler's optimizer prefers arrays... */
#if 0
/* Computes a facil.io Risky Hash. */
SFUNC uint64_t fio_risky_hash(const void *data_, size_t len, uint64_t seed) {
register uint64_t v0 = FIO_RISKY3_IV0;
register uint64_t v1 = FIO_RISKY3_IV1;
register uint64_t v2 = FIO_RISKY3_IV2;
register uint64_t v3 = FIO_RISKY3_IV3;
register uint64_t w0;
register uint64_t w1;
register uint64_t w2;
register uint64_t w3;
register const uint8_t *data = (const uint8_t *)data_;
#define FIO_RISKY3_ROUND64(vi, w_) \
w##vi = w_; \
v##vi += w##vi; \
v##vi = fio_lrot64(v##vi, 29); \
v##vi += w##vi; \
v##vi *= FIO_RISKY3_PRIME##vi;
#define FIO_RISKY3_ROUND256(w0, w1, w2, w3) \
FIO_RISKY3_ROUND64(0, w0); \
FIO_RISKY3_ROUND64(1, w1); \
FIO_RISKY3_ROUND64(2, w2); \
FIO_RISKY3_ROUND64(3, w3);
if (seed) {
/* process the seed as if it was a prepended 8 Byte string. */
v0 *= seed;
v1 *= seed;
v2 *= seed;
v3 *= seed;
v1 ^= seed;
v2 ^= seed;
v3 ^= seed;
}
for (size_t i = 31; i < len; i += 32) {
/* vectorized 32 bytes / 256 bit access */
FIO_RISKY3_ROUND256(FIO_RISKY_BUF2U64(data),
FIO_RISKY_BUF2U64(data + 8),
FIO_RISKY_BUF2U64(data + 16),
FIO_RISKY_BUF2U64(data + 24));
data += 32;
}
switch (len & 24) {
case 24:
FIO_RISKY3_ROUND64(2, FIO_RISKY_BUF2U64(data + 16));
/* fallthrough */
case 16:
FIO_RISKY3_ROUND64(1, FIO_RISKY_BUF2U64(data + 8));
/* fallthrough */
case 8:
FIO_RISKY3_ROUND64(0, FIO_RISKY_BUF2U64(data + 0));
data += len & 24;
}
/* add offset information to padding */
uint64_t tmp = ((uint64_t)len & 0xFF) << 56;
/* leftover bytes */
switch ((len & 7)) {
case 7:
tmp |= ((uint64_t)data[6]) << 48; /* fallthrough */
case 6:
tmp |= ((uint64_t)data[5]) << 40; /* fallthrough */
case 5:
tmp |= ((uint64_t)data[4]) << 32; /* fallthrough */
case 4:
tmp |= ((uint64_t)data[3]) << 24; /* fallthrough */
case 3:
tmp |= ((uint64_t)data[2]) << 16; /* fallthrough */
case 2:
tmp |= ((uint64_t)data[1]) << 8; /* fallthrough */
case 1:
tmp |= ((uint64_t)data[0]);
/* the last (now padded) byte's position */
switch ((len & 24)) {
case 24: /* offset 24 in 32 byte segment */
FIO_RISKY3_ROUND64(3, tmp);
break;
case 16: /* offset 16 in 32 byte segment */
FIO_RISKY3_ROUND64(2, tmp);
break;
case 8: /* offset 8 in 32 byte segment */
FIO_RISKY3_ROUND64(1, tmp);
break;
case 0: /* offset 0 in 32 byte segment */
FIO_RISKY3_ROUND64(0, tmp);
break;
}
}
/* irreversible avalanche... I think */
uint64_t r = (len) ^ ((uint64_t)len << 36);
r += fio_lrot64(v0, 17) + fio_lrot64(v1, 13) + fio_lrot64(v2, 47) +
fio_lrot64(v3, 57);
r += v0 ^ v1;
r ^= fio_lrot64(r, 13);
r += v1 ^ v2;
r ^= fio_lrot64(r, 29);
r += v2 ^ v3;
r += fio_lrot64(r, 33);
r += v3 ^ v0;
r ^= fio_lrot64(r, 51);
r ^= (r >> 29) * FIO_RISKY3_PRIME4;
return r;
}
#else
/* Computes a facil.io Risky Hash. */
SFUNC uint64_t fio_risky_hash(const void *data_, size_t len, uint64_t seed) {
FIO_ALIGN(16)
uint64_t v[4] = {FIO_RISKY3_IV0,
FIO_RISKY3_IV1,
FIO_RISKY3_IV2,
FIO_RISKY3_IV3};
FIO_ALIGN(16) uint64_t w[4];
const uint8_t *data = (const uint8_t *)data_;
#define FIO_RISKY3_ROUND64(vi, w_) \
w[vi] = w_; \
v[vi] += w[vi]; \
v[vi] = fio_lrot64(v[vi], 29); \
v[vi] += w[vi]; \
v[vi] *= FIO_RISKY3_PRIME##vi;
#define FIO_RISKY3_ROUND256(w0, w1, w2, w3) \
FIO_RISKY3_ROUND64(0, w0); \
FIO_RISKY3_ROUND64(1, w1); \
FIO_RISKY3_ROUND64(2, w2); \
FIO_RISKY3_ROUND64(3, w3);
if (seed) {
/* process the seed as if it was a prepended 8 Byte string. */
v[0] *= seed;
v[1] *= seed;
v[2] *= seed;
v[3] *= seed;
v[1] ^= seed;
v[2] ^= seed;
v[3] ^= seed;
}
for (size_t i = 31; i < len; i += 32) {
/* vectorized 32 bytes / 256 bit access */
FIO_RISKY3_ROUND256(FIO_RISKY_BUF2U64(data),
FIO_RISKY_BUF2U64(data + 8),
FIO_RISKY_BUF2U64(data + 16),
FIO_RISKY_BUF2U64(data + 24));
data += 32;
}
switch (len & 24) {
case 24:
FIO_RISKY3_ROUND64(2, FIO_RISKY_BUF2U64(data + 16));
/* fallthrough */
case 16:
FIO_RISKY3_ROUND64(1, FIO_RISKY_BUF2U64(data + 8));
/* fallthrough */
case 8:
FIO_RISKY3_ROUND64(0, FIO_RISKY_BUF2U64(data + 0));
data += len & 24;
}
/* add offset information to padding */
uint64_t tmp = ((uint64_t)len & 0xFF) << 56;
/* leftover bytes */
switch ((len & 7)) {
case 7:
tmp |= ((uint64_t)data[6]) << 48; /* fallthrough */
case 6:
tmp |= ((uint64_t)data[5]) << 40; /* fallthrough */
case 5:
tmp |= ((uint64_t)data[4]) << 32; /* fallthrough */
case 4:
tmp |= ((uint64_t)data[3]) << 24; /* fallthrough */
case 3:
tmp |= ((uint64_t)data[2]) << 16; /* fallthrough */
case 2:
tmp |= ((uint64_t)data[1]) << 8; /* fallthrough */
case 1:
tmp |= ((uint64_t)data[0]);
/* the last (now padded) byte's position */
switch ((len & 24)) {
case 24: /* offset 24 in 32 byte segment */
FIO_RISKY3_ROUND64(3, tmp);
break;
case 16: /* offset 16 in 32 byte segment */
FIO_RISKY3_ROUND64(2, tmp);
break;
case 8: /* offset 8 in 32 byte segment */
FIO_RISKY3_ROUND64(1, tmp);
break;
case 0: /* offset 0 in 32 byte segment */
FIO_RISKY3_ROUND64(0, tmp);
break;
}
}
/* irreversible avalanche... I think */
uint64_t r = (len) ^ ((uint64_t)len << 36);
r += fio_lrot64(v[0], 17) + fio_lrot64(v[1], 13) + fio_lrot64(v[2], 47) +
fio_lrot64(v[3], 57);
r += v[0] ^ v[1];
r ^= fio_lrot64(r, 13);
r += v[1] ^ v[2];
r ^= fio_lrot64(r, 29);
r += v[2] ^ v[3];
r += fio_lrot64(r, 33);
r += v[3] ^ v[0];
r ^= fio_lrot64(r, 51);
r ^= (r >> 29) * FIO_RISKY3_PRIME4;
return r;
}
#endif
/**
* Masks data using a Risky Hash and a counter mode nonce.
*/
IFUNC void fio_risky_mask(char *buf, size_t len, uint64_t key, uint64_t nonce) {
{ /* avoid zero nonce, make sure nonce is effective and odd */
nonce |= 1;
nonce *= 0xDB1DD478B9E93B1ULL;
nonce ^= ((nonce << 24) | (nonce >> 40));
nonce |= 1;
}
uint64_t hash = fio_risky_hash(&key, sizeof(key), nonce);
fio_xmask2(buf, len, hash, nonce);
}
/* *****************************************************************************
Risky Hash - Cleanup
***************************************************************************** */
#undef FIO_RISKY3_ROUND64
#undef FIO_RISKY3_ROUND256
#undef FIO_RISKY_BUF2U64
#endif /* FIO_EXTERN_COMPLETE */
#endif
#undef FIO_RISKY_HASH
/* *****************************************************************************
Psedo-Random Generator Functions
***************************************************************************** */
#if defined(FIO_RAND) && !defined(H___FIO_RAND_H)
#define H___FIO_RAND_H
/* *****************************************************************************
Random - API
***************************************************************************** */
/** Returns 64 psedo-random bits. Probably not cryptographically safe. */
SFUNC uint64_t fio_rand64(void);
/** Writes `len` bytes of psedo-random bits to the target buffer. */
SFUNC void fio_rand_bytes(void *target, size_t len);
/** Feeds up to 1023 bytes of entropy to the random state. */
IFUNC void fio_rand_feed2seed(void *buf_, size_t len);
/** Reseeds the random engin using system state (rusage / jitter). */
IFUNC void fio_rand_reseed(void);
/* *****************************************************************************
Random - Implementation
***************************************************************************** */
#ifdef FIO_EXTERN_COMPLETE
#if FIO_OS_POSIX || \
(__has_include("sys/resource.h") && __has_include("sys/time.h"))
#include <sys/resource.h>
#include <sys/time.h>
#endif
static __thread uint64_t fio___rand_state[4]; /* random state */
static __thread size_t fio___rand_counter; /* seed counter */
/* feeds random data to the algorithm through this 256 bit feed. */
static __thread uint64_t fio___rand_buffer[4] = {0x9c65875be1fce7b9ULL,
0x7cc568e838f6a40d,
0x4bb8d885a0fe47d5,
0x95561f0927ad7ecd};
IFUNC void fio_rand_feed2seed(void *buf_, size_t len) {
len &= 1023;
uint8_t *buf = (uint8_t *)buf_;
uint8_t offset = (fio___rand_counter & 3);
uint64_t tmp = 0;
for (size_t i = 0; i < (len >> 3); ++i) {
tmp = FIO_NAME2(fio_buf, u64_local)(buf);
fio___rand_buffer[(offset++ & 3)] ^= tmp;
buf += 8;
}
switch (len & 7) {
case 7:
tmp <<= 8;
tmp |= buf[6];
/* fallthrough */
case 6:
tmp <<= 8;
tmp |= buf[5];
/* fallthrough */
case 5:
tmp <<= 8;
tmp |= buf[4];
/* fallthrough */
case 4:
tmp <<= 8;
tmp |= buf[3];
/* fallthrough */
case 3:
tmp <<= 8;
tmp |= buf[2];
/* fallthrough */
case 2:
tmp <<= 8;
tmp |= buf[1];
/* fallthrough */
case 1:
tmp <<= 8;
tmp |= buf[1];
fio___rand_buffer[(offset & 3)] ^= tmp;
break;
}
}
/* used here, defined later */
FIO_IFUNC int64_t fio_time_nano();
IFUNC void fio_rand_reseed(void) {
const size_t jitter_samples = 16 | (fio___rand_state[0] & 15);
#if defined(RUSAGE_SELF)
{
struct rusage rusage;
getrusage(RUSAGE_SELF, &rusage);
fio___rand_state[0] =
fio_risky_hash(&rusage, sizeof(rusage), fio___rand_state[0]);
}
#endif
for (size_t i = 0; i < jitter_samples; ++i) {
uint64_t clk = (uint64_t)fio_time_nano();
fio___rand_state[0] =
fio_risky_hash(&clk, sizeof(clk), fio___rand_state[0] + i);
clk = fio_time_nano();
fio___rand_state[1] =
fio_risky_hash(&clk,
sizeof(clk),
fio___rand_state[1] + fio___rand_counter);
}
fio___rand_state[2] =
fio_risky_hash(fio___rand_buffer,
sizeof(fio___rand_buffer),
fio___rand_counter + fio___rand_state[0]);
fio___rand_state[3] = fio_risky_hash(fio___rand_state,
sizeof(fio___rand_state),
fio___rand_state[1] + jitter_samples);
fio___rand_buffer[0] = fio_lrot64(fio___rand_buffer[0], 31);
fio___rand_buffer[1] = fio_lrot64(fio___rand_buffer[1], 29);
fio___rand_buffer[2] ^= fio___rand_buffer[0];
fio___rand_buffer[3] ^= fio___rand_buffer[1];
fio___rand_counter += jitter_samples;
}
/* tested for randomness using code from: http://xoshiro.di.unimi.it/hwd.php */
SFUNC uint64_t fio_rand64(void) {
/* modeled after xoroshiro128+, by <NAME> and <NAME> */
const uint64_t P[] = {0x37701261ED6C16C7ULL, 0x764DBBB75F3B3E0DULL};
if (((fio___rand_counter++) & (((size_t)1 << 19) - 1)) == 0) {
/* re-seed state every 524,288 requests / 2^19-1 attempts */
fio_rand_reseed();
}
fio___rand_state[0] +=
(fio_lrot64(fio___rand_state[0], 33) + fio___rand_counter) * P[0];
fio___rand_state[1] += fio_lrot64(fio___rand_state[1], 33) * P[1];
fio___rand_state[2] +=
(fio_lrot64(fio___rand_state[2], 33) + fio___rand_counter) * (~P[0]);
fio___rand_state[3] += fio_lrot64(fio___rand_state[3], 33) * (~P[1]);
return fio_lrot64(fio___rand_state[0], 31) +
fio_lrot64(fio___rand_state[1], 29) +
fio_lrot64(fio___rand_state[2], 27) +
fio_lrot64(fio___rand_state[3], 30);
}
/* copies 64 bits of randomness (8 bytes) repeatedly. */
SFUNC void fio_rand_bytes(void *data_, size_t len) {
if (!data_ || !len)
return;
uint8_t *data = (uint8_t *)data_;
if (len < 8)
goto small_random;
if ((uintptr_t)data & 7) {
/* align pointer to 64 bit word */
size_t offset = 8 - ((uintptr_t)data & 7);
fio_rand_bytes(data_, offset); /* perform small_random */
data += offset;
len -= offset;
}
/* 128 random bits at a time */
for (size_t i = (len >> 4); i; --i) {
uint64_t t0 = fio_rand64();
uint64_t t1 = fio_rand64();
FIO_NAME2(fio_u, buf64_local)(data, t0);
FIO_NAME2(fio_u, buf64_local)(data + 8, t1);
data += 16;
}
/* 64 random bits at tail */
if ((len & 8)) {
uint64_t t0 = fio_rand64();
FIO_NAME2(fio_u, buf64_local)(data, t0);
}
small_random:
if ((len & 7)) {
/* leftover bits */
uint64_t tmp = fio_rand64();
/* leftover bytes */
switch ((len & 7)) {
case 7:
data[6] = (tmp >> 8) & 0xFF;
/* fallthrough */
case 6:
data[5] = (tmp >> 16) & 0xFF;
/* fallthrough */
case 5:
data[4] = (tmp >> 24) & 0xFF;
/* fallthrough */
case 4:
data[3] = (tmp >> 32) & 0xFF;
/* fallthrough */
case 3:
data[2] = (tmp >> 40) & 0xFF;
/* fallthrough */
case 2:
data[1] = (tmp >> 48) & 0xFF;
/* fallthrough */
case 1:
data[0] = (tmp >> 56) & 0xFF;
}
}
}
/* *****************************************************************************
Hashing speed test
***************************************************************************** */
#ifdef FIO_TEST_CSTL
#include <math.h>
typedef uintptr_t (*fio__hashing_func_fn)(char *, size_t);
FIO_SFUNC void fio_test_hash_function(fio__hashing_func_fn h,
char *name,
uint8_t size_log,
uint8_t mem_alignment_ofset,
uint8_t fast) {
/* test based on code from BearSSL with credit to <NAME> */
if (size_log >= 21 || ((sizeof(uint64_t) - 1) >> size_log)) {
FIO_LOG_ERROR("fio_test_hash_function called with a log size too big.");
return;
}
mem_alignment_ofset &= 7;
size_t const buffer_len = (1ULL << size_log);
uint64_t cycles_start_at = (1ULL << (16 + (fast * 2)));
if (size_log < 13)
cycles_start_at <<= (13 - size_log);
else if (size_log > 13)
cycles_start_at >>= (size_log - 13);
#ifdef DEBUG
fprintf(stderr,
"* Testing %s speed with %zu byte blocks"
"(DEBUG mode detected - speed may be affected).\n",
name,
buffer_len);
#else
fprintf(stderr,
"* Testing %s speed with %zu byte blocks.\n",
name,
buffer_len);
#endif
uint8_t *buffer_mem = (uint8_t *)
FIO_MEM_REALLOC(NULL, 0, (buffer_len + mem_alignment_ofset) + 64, 0);
uint8_t *buffer = buffer_mem + mem_alignment_ofset;
memset(buffer, 'T', buffer_len);
/* warmup */
uint64_t hash = 0;
for (size_t i = 0; i < 4; i++) {
hash += h((char *)buffer, buffer_len);
FIO_MEMCPY(buffer, &hash, sizeof(hash));
}
/* loop until test runs for more than 2 seconds */
for (uint64_t cycles = cycles_start_at;;) {
clock_t start, end;
start = clock();
for (size_t i = cycles; i > 0; i--) {
hash += h((char *)buffer, buffer_len);
FIO_COMPILER_GUARD;
}
end = clock();
FIO_MEMCPY(buffer, &hash, sizeof(hash));
if ((end - start) >= (2 * CLOCKS_PER_SEC) ||
cycles >= ((uint64_t)1 << 62)) {
fprintf(stderr,
"\t%-40s %8.2f MB/s\n",
name,
(double)(buffer_len * cycles) /
(((end - start) * (1000000.0 / CLOCKS_PER_SEC))));
break;
}
cycles <<= 1;
}
FIO_MEM_FREE(buffer_mem, (buffer_len + mem_alignment_ofset) + 64);
}
FIO_SFUNC uintptr_t FIO_NAME_TEST(stl, risky_wrapper)(char *buf, size_t len) {
return fio_risky_hash(buf, len, 1);
}
FIO_SFUNC uintptr_t FIO_NAME_TEST(stl, risky_mask_wrapper)(char *buf,
size_t len) {
fio_risky_mask(buf, len, 0, 0);
return len;
}
FIO_SFUNC uintptr_t FIO_NAME_TEST(stl, xmask_wrapper)(char *buf, size_t len) {
fio_xmask(buf, len, fio_rand64());
return len;
}
FIO_SFUNC void FIO_NAME_TEST(stl, risky)(void) {
for (int i = 0; i < 8; ++i) {
char buf[128];
uint64_t nonce = fio_rand64();
const char *str = "this is a short text, to test risky masking";
char *tmp = buf + i;
FIO_MEMCPY(tmp, str, strlen(str));
fio_risky_mask(tmp, strlen(str), (uint64_t)(uintptr_t)tmp, nonce);
FIO_ASSERT(memcmp(tmp, str, strlen(str)), "Risky Hash masking failed");
size_t err = 0;
for (size_t b = 0; b < strlen(str); ++b) {
FIO_ASSERT(tmp[b] != str[b] || (err < 2),
"Risky Hash masking didn't mask buf[%zu] on offset "
"%d (statistical deviation?)",
b,
i);
err += (tmp[b] == str[b]);
}
fio_risky_mask(tmp, strlen(str), (uint64_t)(uintptr_t)tmp, nonce);
FIO_ASSERT(!memcmp(tmp, str, strlen(str)), "Risky Hash masking RT failed");
}
const uint8_t alignment_test_offset = 0;
if (alignment_test_offset)
fprintf(stderr,
"The following speed tests use a memory alignment offset of %d "
"bytes.\n",
(int)(alignment_test_offset & 7));
#if !DEBUG
fio_test_hash_function(FIO_NAME_TEST(stl, risky_wrapper),
(char *)"fio_risky_hash",
7,
alignment_test_offset,
3);
fio_test_hash_function(FIO_NAME_TEST(stl, risky_wrapper),
(char *)"fio_risky_hash",
13,
alignment_test_offset,
2);
fio_test_hash_function(FIO_NAME_TEST(stl, risky_mask_wrapper),
(char *)"fio_risky_mask (Risky XOR + counter)",
13,
alignment_test_offset,
4);
fio_test_hash_function(FIO_NAME_TEST(stl, risky_mask_wrapper),
(char *)"fio_risky_mask (unaligned)",
13,
1,
4);
if (0) {
fio_test_hash_function(FIO_NAME_TEST(stl, xmask_wrapper),
(char *)"fio_xmask (XOR, NO counter)",
13,
alignment_test_offset,
4);
fio_test_hash_function(FIO_NAME_TEST(stl, xmask_wrapper),
(char *)"fio_xmask (unaligned)",
13,
1,
4);
}
#endif
}
FIO_SFUNC void FIO_NAME_TEST(stl, random_buffer)(uint64_t *stream,
size_t len,
const char *name,
size_t clk) {
size_t totals[2] = {0};
size_t freq[256] = {0};
const size_t total_bits = (len * sizeof(*stream) * 8);
uint64_t hemming = 0;
/* collect data */
for (size_t i = 1; i < len; i += 2) {
hemming += fio_hemming_dist(stream[i], stream[i - 1]);
for (size_t byte = 0; byte < (sizeof(*stream) << 1); ++byte) {
uint8_t val = ((uint8_t *)(stream + (i - 1)))[byte];
++freq[val];
for (int bit = 0; bit < 8; ++bit) {
++totals[(val >> bit) & 1];
}
}
}
hemming /= len;
fprintf(stderr, "\n");
#if DEBUG
fprintf(stderr,
"\t- \x1B[1m%s\x1B[0m (%zu CPU cycles NOT OPTIMIZED):\n",
name,
clk);
#else
fprintf(stderr, "\t- \x1B[1m%s\x1B[0m (%zu CPU cycles):\n", name, clk);
#endif
fprintf(stderr,
"\t zeros / ones (bit frequency)\t%.05f\n",
((float)1.0 * totals[0]) / totals[1]);
if (!(totals[0] < totals[1] + (total_bits / 20) &&
totals[1] < totals[0] + (total_bits / 20)))
FIO_LOG_ERROR("randomness isn't random?");
fprintf(stderr,
"\t avarage hemming distance\t%zu (should be: 14-18)\n",
(size_t)hemming);
/* expect avarage hemming distance of 25% == 16 bits */
if (!(hemming >= 14 && hemming <= 18))
FIO_LOG_ERROR("randomness isn't random (hemming distance failed)?");
/* test chi-square ... I think */
if (len * sizeof(*stream) > 2560) {
double n_r = (double)1.0 * ((len * sizeof(*stream)) / 256);
double chi_square = 0;
for (unsigned int i = 0; i < 256; ++i) {
double f = freq[i] - n_r;
chi_square += (f * f);
}
chi_square /= n_r;
double chi_square_r_abs =
(chi_square - 256 >= 0) ? chi_square - 256 : (256 - chi_square);
fprintf(
stderr,
"\t chi-sq. variation\t\t%.02lf - %s (expect <= %0.2lf)\n",
chi_square_r_abs,
((chi_square_r_abs <= 2 * (sqrt(n_r)))
? "good"
: ((chi_square_r_abs <= 3 * (sqrt(n_r))) ? "not amazing"
: "\x1B[1mBAD\x1B[0m")),
2 * (sqrt(n_r)));
}
}
FIO_SFUNC void FIO_NAME_TEST(stl, random)(void) {
fprintf(stderr,
"* Testing randomness "
"- bit frequency / hemming distance / chi-square.\n");
const size_t test_len = (TEST_REPEAT << 7);
uint64_t *rs =
(uint64_t *)FIO_MEM_REALLOC(NULL, 0, sizeof(*rs) * test_len, 0);
clock_t start, end;
FIO_ASSERT_ALLOC(rs);
rand(); /* warmup */
if (sizeof(int) < sizeof(uint64_t)) {
start = clock();
for (size_t i = 0; i < test_len; ++i) {
rs[i] = ((uint64_t)rand() << 32) | (uint64_t)rand();
}
end = clock();
} else {
start = clock();
for (size_t i = 0; i < test_len; ++i) {
rs[i] = (uint64_t)rand();
}
end = clock();
}
FIO_NAME_TEST(stl, random_buffer)
(rs, test_len, "rand (system - naive, ignoring missing bits)", end - start);
memset(rs, 0, sizeof(*rs) * test_len);
{
if (RAND_MAX == ~(uint64_t)0ULL) {
/* RAND_MAX fills all bits */
start = clock();
for (size_t i = 0; i < test_len; ++i) {
rs[i] = (uint64_t)rand();
}
end = clock();
} else if (RAND_MAX >= (~(uint32_t)0UL)) {
/* RAND_MAX fill at least 32 bits per call */
uint32_t *rs_adjusted = (uint32_t *)rs;
start = clock();
for (size_t i = 0; i < (test_len << 1); ++i) {
rs_adjusted[i] = (uint32_t)rand();
}
end = clock();
} else if (RAND_MAX >= (~(uint16_t)0U)) {
/* RAND_MAX fill at least 16 bits per call */
uint16_t *rs_adjusted = (uint16_t *)rs;
start = clock();
for (size_t i = 0; i < (test_len << 2); ++i) {
rs_adjusted[i] = (uint16_t)rand();
}
end = clock();
} else {
/* assume RAND_MAX fill at least 8 bits per call */
uint8_t *rs_adjusted = (uint8_t *)rs;
start = clock();
for (size_t i = 0; i < (test_len << 2); ++i) {
rs_adjusted[i] = (uint8_t)rand();
}
end = clock();
}
/* test RAND_MAX value */
uint8_t rand_bits = 63;
while (rand_bits) {
if (RAND_MAX <= (~(0ULL)) >> rand_bits)
break;
--rand_bits;
}
rand_bits = 64 - rand_bits;
char buffer[128] = {0};
snprintf(buffer,
128 - 14,
"rand (system - fixed, testing %d random bits)",
(int)rand_bits);
FIO_NAME_TEST(stl, random_buffer)(rs, test_len, buffer, end - start);
}
memset(rs, 0, sizeof(*rs) * test_len);
fio_rand64(); /* warmup */
start = clock();
for (size_t i = 0; i < test_len; ++i) {
rs[i] = fio_rand64();
}
end = clock();
FIO_NAME_TEST(stl, random_buffer)(rs, test_len, "fio_rand64", end - start);
memset(rs, 0, sizeof(*rs) * test_len);
start = clock();
fio_rand_bytes(rs, test_len * sizeof(*rs));
end = clock();
FIO_NAME_TEST(stl, random_buffer)
(rs, test_len, "fio_rand_bytes", end - start);
fio_rand_feed2seed(rs, sizeof(*rs) * test_len);
FIO_MEM_FREE(rs, sizeof(*rs) * test_len);
fprintf(stderr, "\n");
#if DEBUG
fprintf(stderr,
"\t- to compare CPU cycles, test randomness with optimization.\n\n");
#endif /* DEBUG */
}
#endif /* FIO_TEST_CSTL */
/* *****************************************************************************
Random - Cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE */
#endif /* FIO_RAND */
#undef FIO_RAND
|
janbiedermann/cstl
|
stl_slices/699 empty module.h
|
<gh_stars>10-100
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#define FIO_MODULE_NAME module /* Development inclusion - ignore line */
#include "000 header.h" /* Development inclusion - ignore line */
#include "100 mem.h" /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
A Template for New Types / Modules
***************************************************************************** */
#ifdef FIO_MODULE_NAME
/* *****************************************************************************
Module Settings
At this point, define any MACROs and customaizable settings avsailable to the
developer.
***************************************************************************** */
/* *****************************************************************************
Pointer Tagging Support
***************************************************************************** */
#ifdef FIO_PTR_TAG_TYPE
#define FIO_MODULE_PTR FIO_PTR_TAG_TYPE
#else
#define FIO_MODULE_PTR FIO_NAME(FIO_MODULE_NAME, s) *
#endif
/* *****************************************************************************
Module API
***************************************************************************** */
typedef struct {
/* module's type(s) if any */
void *data;
} FIO_NAME(FIO_MODULE_NAME, s);
/* at this point publish (declare only) the public API */
#ifndef FIO_MODULE_INIT
/* Initialization macro. */
#define FIO_MODULE_INIT \
{ 0 }
#endif
/* do we have a constructor? */
#ifndef FIO_REF_CONSTRUCTOR_ONLY
/* Allocates a new object on the heap and initializes it's memory. */
FIO_IFUNC FIO_MODULE_PTR FIO_NAME(FIO_MODULE_NAME, new)(void);
/* Frees any internal data AND the object's container! */
FIO_IFUNC int FIO_NAME(FIO_MODULE_NAME, free)(FIO_MODULE_PTR obj);
#endif /* FIO_REF_CONSTRUCTOR_ONLY */
/** Destroys the object, reinitializing its container. */
SFUNC void FIO_NAME(FIO_MODULE_NAME, destroy)(FIO_MODULE_PTR obj);
/* *****************************************************************************
Module Implementation - inlined static functions
***************************************************************************** */
/*
REMEMBER:
========
All memory allocations should use:
* FIO_MEM_REALLOC_(ptr, old_size, new_size, copy_len)
* FIO_MEM_FREE_(ptr, size) fio_free((ptr))
*/
/* do we have a constructor? */
#ifndef FIO_REF_CONSTRUCTOR_ONLY
/* Allocates a new object on the heap and initializes it's memory. */
FIO_IFUNC FIO_MODULE_PTR FIO_NAME(FIO_MODULE_NAME, new)(void) {
FIO_NAME(FIO_MODULE_NAME, s) *o =
(FIO_NAME(FIO_MODULE_NAME, s) *)FIO_MEM_REALLOC_(NULL, 0, sizeof(*o), 0);
if (!o)
return (FIO_MODULE_PTR)NULL;
*o = (FIO_NAME(FIO_MODULE_NAME, s))FIO_MODULE_INIT;
return (FIO_MODULE_PTR)FIO_PTR_TAG(o);
}
/* Frees any internal data AND the object's container! */
FIO_IFUNC int FIO_NAME(FIO_MODULE_NAME, free)(FIO_MODULE_PTR obj) {
FIO_PTR_TAG_VALID_OR_RETURN(obj, 0);
FIO_NAME(FIO_MODULE_NAME, destroy)(obj);
FIO_NAME(FIO_MODULE_NAME, s) *o =
(FIO_NAME(FIO_MODULE_NAME, s) *)FIO_PTR_UNTAG(obj);
FIO_MEM_FREE_(o, sizeof(*o));
return 0;
}
#endif /* FIO_REF_CONSTRUCTOR_ONLY */
/* *****************************************************************************
Module Implementation - possibly externed functions.
***************************************************************************** */
#ifdef FIO_EXTERN_COMPLETE
/*
REMEMBER:
========
All memory allocations should use:
* FIO_MEM_REALLOC_(ptr, old_size, new_size, copy_len)
* FIO_MEM_FREE_(ptr, size) fio_free((ptr))
*/
/* Frees any internal data AND the object's container! */
SFUNC void FIO_NAME(FIO_MODULE_NAME, destroy)(FIO_MODULE_PTR obj) {
FIO_NAME(FIO_MODULE_NAME, s) *o =
(FIO_NAME(FIO_MODULE_NAME, s) *)FIO_PTR_UNTAG(obj);
if (!o)
return;
FIO_PTR_TAG_VALID_OR_RETURN_VOID(obj);
/* add destruction logic */
*o = (FIO_NAME(FIO_MODULE_NAME, s))FIO_MODULE_INIT;
return;
}
/* *****************************************************************************
Module Testing
***************************************************************************** */
#ifdef FIO_TEST_CSTL
FIO_SFUNC void FIO_NAME_TEST(stl, FIO_MODULE_NAME)(void) {
/*
* test module here
*/
}
#endif /* FIO_TEST_CSTL */
/* *****************************************************************************
Module Cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE */
#undef FIO_MODULE_PTR
#endif /* FIO_MODULE_NAME */
#undef FIO_MODULE_NAME
|
janbiedermann/cstl
|
stl_slices/050 url.h
|
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#include "000 header.h" /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
URI Parsing
***************************************************************************** */
#if (defined(FIO_URL) || defined(FIO_URI)) && !defined(H___FIO_URL___H)
#define H___FIO_URL___H
/** the result returned by `fio_url_parse` */
typedef struct {
fio_str_info_s scheme;
fio_str_info_s user;
fio_str_info_s password;
fio_str_info_s host;
fio_str_info_s port;
fio_str_info_s path;
fio_str_info_s query;
fio_str_info_s target;
} fio_url_s;
/**
* Parses the URI returning it's components and their lengths (no decoding
* performed, doesn't accept decoded URIs).
*
* The returned string are NOT NUL terminated, they are merely locations within
* the original string.
*
* This function attempts to accept many different formats, including any of the
* following:
*
* * `/complete_path?query#target`
*
* i.e.: /index.html?page=1#list
*
* * `host:port/complete_path?query#target`
*
* i.e.:
* example.com
* example.com:8080
* example.com/index.html
* example.com:8080/index.html
* example.com:8080/index.html?key=val#target
*
* * `user:password@host:port/path?query#target`
*
* i.e.: user:1234@example.com:8080/index.html
*
* * `username[:password]@host[:port][...]`
*
* i.e.: john:<EMAIL>
*
* * `schema://user:password@host:port/path?query#target`
*
* i.e.: http://example.com/index.html?page=1#list
*
* Invalid formats might produce unexpected results. No error testing performed.
*/
SFUNC fio_url_s fio_url_parse(const char *url, size_t len);
/* *****************************************************************************
FIO_URL - Implementation
***************************************************************************** */
#if defined(FIO_EXTERN_COMPLETE)
/**
* Parses the URI returning it's components and their lengths (no decoding
* performed, doesn't accept decoded URIs).
*
* The returned string are NOT NUL terminated, they are merely locations within
* the original string.
*
* This function expects any of the following formats:
*
* * `/complete_path?query#target`
*
* i.e.: /index.html?page=1#list
*
* * `host:port/complete_path?query#target`
*
* i.e.:
* example.com/index.html
* example.com:8080/index.html
*
* * `schema://user:password@host:port/path?query#target`
*
* i.e.: http://example.com/index.html?page=1#list
*
* Invalid formats might produce unexpected results. No error testing performed.
*/
SFUNC fio_url_s fio_url_parse(const char *url, size_t len) {
/*
Intention:
[schema://][user[:]][password[@]][host.com[:/]][:port/][/path][?quary][#target]
*/
const char *end = url + len;
const char *pos = url;
fio_url_s r = {.scheme = {.buf = (char *)url}};
if (len == 0) {
goto finish;
}
if (pos[0] == '/') {
/* start at path */
goto start_path;
}
while (pos < end && pos[0] != ':' && pos[0] != '/' && pos[0] != '@' &&
pos[0] != '#' && pos[0] != '?')
++pos;
if (pos == end) {
/* was only host (path starts with '/') */
r.host = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
goto finish;
}
switch (pos[0]) {
case '@':
/* username@[host] */
r.user = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
++pos;
goto start_host;
case '/':
/* host[/path] */
r.host = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
goto start_path;
case '?':
/* host?[query] */
r.host = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
++pos;
goto start_query;
case '#':
/* host#[target] */
r.host = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
++pos;
goto start_target;
case ':':
if (pos + 2 <= end && pos[1] == '/' && pos[2] == '/') {
/* scheme:// */
r.scheme.len = pos - url;
pos += 3;
} else {
/* username:[password] OR */
/* host:[port] */
r.user = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
++pos;
goto start_password;
}
break;
}
// start_username:
url = pos;
while (pos < end && pos[0] != ':' && pos[0] != '/' && pos[0] != '@'
/* && pos[0] != '#' && pos[0] != '?' */)
++pos;
if (pos >= end) { /* scheme://host */
r.host = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
goto finish;
}
switch (pos[0]) {
case '/':
/* scheme://host[/path] */
r.host = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
goto start_path;
case '@':
/* scheme://username@[host]... */
r.user = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
++pos;
goto start_host;
case ':':
/* scheme://username:[password]@[host]... OR */
/* scheme://host:[port][/...] */
r.user = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
++pos;
break;
}
start_password:
url = pos;
while (pos < end && pos[0] != '/' && pos[0] != '@')
++pos;
if (pos >= end) {
/* was host:port */
r.port = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
r.host = r.user;
r.user.len = 0;
goto finish;
;
}
switch (pos[0]) {
case '/':
r.port = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
r.host = r.user;
r.user.len = 0;
goto start_path;
case '@':
r.password =
(fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
++pos;
break;
}
start_host:
url = pos;
while (pos < end && pos[0] != '/' && pos[0] != ':' && pos[0] != '#' &&
pos[0] != '?')
++pos;
r.host = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
if (pos >= end) {
goto finish;
}
switch (pos[0]) {
case '/':
/* scheme://[...@]host[/path] */
goto start_path;
case '?':
/* scheme://[...@]host?[query] (bad)*/
++pos;
goto start_query;
case '#':
/* scheme://[...@]host#[target] (bad)*/
++pos;
goto start_target;
// case ':':
/* scheme://[...@]host:[port] */
}
++pos;
// start_port:
url = pos;
while (pos < end && pos[0] != '/' && pos[0] != '#' && pos[0] != '?')
++pos;
r.port = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
if (pos >= end) {
/* scheme://[...@]host:port */
goto finish;
}
switch (pos[0]) {
case '?':
/* scheme://[...@]host:port?[query] (bad)*/
++pos;
goto start_query;
case '#':
/* scheme://[...@]host:port#[target] (bad)*/
++pos;
goto start_target;
// case '/':
/* scheme://[...@]host:port[/path] */
}
start_path:
url = pos;
while (pos < end && pos[0] != '#' && pos[0] != '?')
++pos;
r.path = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
if (pos >= end) {
goto finish;
}
++pos;
if (pos[-1] == '#')
goto start_target;
start_query:
url = pos;
while (pos < end && pos[0] != '#')
++pos;
r.query = (fio_str_info_s){.buf = (char *)url, .len = (size_t)(pos - url)};
++pos;
if (pos >= end)
goto finish;
start_target:
r.target = (fio_str_info_s){.buf = (char *)pos, .len = (size_t)(end - pos)};
finish:
if (r.scheme.len == 4 && r.host.buf &&
(((r.scheme.buf[0] | 32) == 'f' && (r.scheme.buf[1] | 32) == 'i' &&
(r.scheme.buf[2] | 32) == 'l' && (r.scheme.buf[3] | 32) == 'e') ||
((r.scheme.buf[0] | 32) == 'u' && (r.scheme.buf[1] | 32) == 'n' &&
(r.scheme.buf[2] | 32) == 'i' && (r.scheme.buf[3] | 32) == 'x'))) {
r.path.len += (r.path.buf - (r.scheme.buf + 7));
r.path.buf = r.scheme.buf + 7;
r.user.len = r.password.len = r.port.len = r.host.len = 0;
}
/* set any empty values to NULL */
if (!r.scheme.len)
r.scheme.buf = NULL;
if (!r.user.len)
r.user.buf = NULL;
if (!r.password.len)
r.password.buf = NULL;
if (!r.host.len)
r.host.buf = NULL;
if (!r.port.len)
r.port.buf = NULL;
if (!r.path.len)
r.path.buf = NULL;
if (!r.query.len)
r.query.buf = NULL;
if (!r.target.len)
r.target.buf = NULL;
return r;
}
/* *****************************************************************************
URL parsing - Test
***************************************************************************** */
#ifdef FIO_TEST_CSTL
/* Test for URI variations:
*
* * `/complete_path?query#target`
*
* i.e.: /index.html?page=1#list
*
* * `host:port/complete_path?query#target`
*
* i.e.:
* example.com
* example.com:8080
* example.com/index.html
* example.com:8080/index.html
* example.com:8080/index.html?key=val#target
*
* * `user:password@host:port/path?query#target`
*
* i.e.: user:<EMAIL>:8080/index.html
*
* * `username[:password]@host[:port][...]`
*
* i.e.: john:<EMAIL>
*
* * `schema://user:password@host:port/path?query#target`
*
* i.e.: http://example.com/index.html?page=1#list
*/
FIO_SFUNC void FIO_NAME_TEST(stl, url)(void) {
fprintf(stderr, "* Testing URL (URI) parser.\n");
struct {
char *url;
size_t len;
fio_url_s expected;
} tests[] = {
{
.url = (char *)"file://go/home/",
.len = 15,
.expected =
{
.scheme = {.buf = (char *)"file", .len = 4},
.path = {.buf = (char *)"go/home/", .len = 8},
},
},
{
.url = (char *)"unix:///go/home/",
.len = 16,
.expected =
{
.scheme = {.buf = (char *)"unix", .len = 4},
.path = {.buf = (char *)"/go/home/", .len = 9},
},
},
{
.url = (char *)"schema://user:password@host:port/path?query#target",
.len = 50,
.expected =
{
.scheme = {.buf = (char *)"schema", .len = 6},
.user = {.buf = (char *)"user", .len = 4},
.password = {.buf = (char *)"password", .len = 8},
.host = {.buf = (char *)"host", .len = 4},
.port = {.buf = (char *)"port", .len = 4},
.path = {.buf = (char *)"/path", .len = 5},
.query = {.buf = (char *)"query", .len = 5},
.target = {.buf = (char *)"target", .len = 6},
},
},
{
.url = (char *)"schema://user@host:port/path?query#target",
.len = 41,
.expected =
{
.scheme = {.buf = (char *)"schema", .len = 6},
.user = {.buf = (char *)"user", .len = 4},
.host = {.buf = (char *)"host", .len = 4},
.port = {.buf = (char *)"port", .len = 4},
.path = {.buf = (char *)"/path", .len = 5},
.query = {.buf = (char *)"query", .len = 5},
.target = {.buf = (char *)"target", .len = 6},
},
},
{
.url = (char *)"http://localhost.com:3000/home?is=1",
.len = 35,
.expected =
{
.scheme = {.buf = (char *)"http", .len = 4},
.host = {.buf = (char *)"localhost.com", .len = 13},
.port = {.buf = (char *)"3000", .len = 4},
.path = {.buf = (char *)"/home", .len = 5},
.query = {.buf = (char *)"is=1", .len = 4},
},
},
{
.url = (char *)"/complete_path?query#target",
.len = 27,
.expected =
{
.path = {.buf = (char *)"/complete_path", .len = 14},
.query = {.buf = (char *)"query", .len = 5},
.target = {.buf = (char *)"target", .len = 6},
},
},
{
.url = (char *)"/index.html?page=1#list",
.len = 23,
.expected =
{
.path = {.buf = (char *)"/index.html", .len = 11},
.query = {.buf = (char *)"page=1", .len = 6},
.target = {.buf = (char *)"list", .len = 4},
},
},
{
.url = (char *)"example.com",
.len = 11,
.expected =
{
.host = {.buf = (char *)"example.com", .len = 11},
},
},
{
.url = (char *)"example.com:8080",
.len = 16,
.expected =
{
.host = {.buf = (char *)"example.com", .len = 11},
.port = {.buf = (char *)"8080", .len = 4},
},
},
{
.url = (char *)"example.com/index.html",
.len = 22,
.expected =
{
.host = {.buf = (char *)"example.com", .len = 11},
.path = {.buf = (char *)"/index.html", .len = 11},
},
},
{
.url = (char *)"example.com:8080/index.html",
.len = 27,
.expected =
{
.host = {.buf = (char *)"example.com", .len = 11},
.port = {.buf = (char *)"8080", .len = 4},
.path = {.buf = (char *)"/index.html", .len = 11},
},
},
{
.url = (char *)"example.com:8080/index.html?key=val#target",
.len = 42,
.expected =
{
.host = {.buf = (char *)"example.com", .len = 11},
.port = {.buf = (char *)"8080", .len = 4},
.path = {.buf = (char *)"/index.html", .len = 11},
.query = {.buf = (char *)"key=val", .len = 7},
.target = {.buf = (char *)"target", .len = 6},
},
},
{
.url = (char *)"user:1<PASSWORD>@<EMAIL>:8080/index.html",
.len = 37,
.expected =
{
.user = {.buf = (char *)"user", .len = 4},
.password = {.buf = (char *)"<PASSWORD>", .len = 4},
.host = {.buf = (char *)"example.com", .len = 11},
.port = {.buf = (char *)"8080", .len = 4},
.path = {.buf = (char *)"/index.html", .len = 11},
},
},
{
.url = (char *)"user@<EMAIL>:8080/index.html",
.len = 32,
.expected =
{
.user = {.buf = (char *)"user", .len = 4},
.host = {.buf = (char *)"example.com", .len = 11},
.port = {.buf = (char *)"8080", .len = 4},
.path = {.buf = (char *)"/index.html", .len = 11},
},
},
{.url = NULL},
};
for (size_t i = 0; tests[i].url; ++i) {
fio_url_s result = fio_url_parse(tests[i].url, tests[i].len);
FIO_LOG_DEBUG2("Result for: %s"
"\n\t scheme (%zu bytes): %.*s"
"\n\t user (%zu bytes): %.*s"
"\n\t password (%zu bytes): %.*s"
"\n\t host (%zu bytes): %.*s"
"\n\t port (%zu bytes): %.*s"
"\n\t path (%zu bytes): %.*s"
"\n\t query (%zu bytes): %.*s"
"\n\t target (%zu bytes): %.*s\n",
tests[i].url,
result.scheme.len,
(int)result.scheme.len,
result.scheme.buf,
result.user.len,
(int)result.user.len,
result.user.buf,
result.password.len,
(int)result.password.len,
result.password.buf,
result.host.len,
(int)result.host.len,
result.host.buf,
result.port.len,
(int)result.port.len,
result.port.buf,
result.path.len,
(int)result.path.len,
result.path.buf,
result.query.len,
(int)result.query.len,
result.query.buf,
result.target.len,
(int)result.target.len,
result.target.buf);
FIO_ASSERT(
result.scheme.len == tests[i].expected.scheme.len &&
(!result.scheme.len || !memcmp(result.scheme.buf,
tests[i].expected.scheme.buf,
tests[i].expected.scheme.len)),
"scheme result failed for:\n\ttest[%zu]: %s\n\texpected: "
"%s\n\tgot: %.*s",
i,
tests[i].url,
tests[i].expected.scheme.buf,
(int)result.scheme.len,
result.scheme.buf);
FIO_ASSERT(
result.user.len == tests[i].expected.user.len &&
(!result.user.len || !memcmp(result.user.buf,
tests[i].expected.user.buf,
tests[i].expected.user.len)),
"user result failed for:\n\ttest[%zu]: %s\n\texpected: %s\n\tgot: %.*s",
i,
tests[i].url,
tests[i].expected.user.buf,
(int)result.user.len,
result.user.buf);
FIO_ASSERT(
result.password.len == tests[i].expected.password.len &&
(!result.password.len || !memcmp(result.password.buf,
tests[i].expected.password.buf,
tests[i].expected.password.len)),
"password result failed for:\n\ttest[%zu]: %s\n\texpected: %s\n\tgot: "
"%.*s",
i,
tests[i].url,
tests[i].expected.password.buf,
(int)result.password.len,
result.password.buf);
FIO_ASSERT(
result.host.len == tests[i].expected.host.len &&
(!result.host.len || !memcmp(result.host.buf,
tests[i].expected.host.buf,
tests[i].expected.host.len)),
"host result failed for:\n\ttest[%zu]: %s\n\texpected: %s\n\tgot: %.*s",
i,
tests[i].url,
tests[i].expected.host.buf,
(int)result.host.len,
result.host.buf);
FIO_ASSERT(
result.port.len == tests[i].expected.port.len &&
(!result.port.len || !memcmp(result.port.buf,
tests[i].expected.port.buf,
tests[i].expected.port.len)),
"port result failed for:\n\ttest[%zu]: %s\n\texpected: %s\n\tgot: %.*s",
i,
tests[i].url,
tests[i].expected.port.buf,
(int)result.port.len,
result.port.buf);
FIO_ASSERT(
result.path.len == tests[i].expected.path.len &&
(!result.path.len || !memcmp(result.path.buf,
tests[i].expected.path.buf,
tests[i].expected.path.len)),
"path result failed for:\n\ttest[%zu]: %s\n\texpected: %s\n\tgot: %.*s",
i,
tests[i].url,
tests[i].expected.path.buf,
(int)result.path.len,
result.path.buf);
FIO_ASSERT(result.query.len == tests[i].expected.query.len &&
(!result.query.len || !memcmp(result.query.buf,
tests[i].expected.query.buf,
tests[i].expected.query.len)),
"query result failed for:\n\ttest[%zu]: %s\n\texpected: "
"%s\n\tgot: %.*s",
i,
tests[i].url,
tests[i].expected.query.buf,
(int)result.query.len,
result.query.buf);
FIO_ASSERT(
result.target.len == tests[i].expected.target.len &&
(!result.target.len || !memcmp(result.target.buf,
tests[i].expected.target.buf,
tests[i].expected.target.len)),
"target result failed for:\n\ttest[%zu]: %s\n\texpected: "
"%s\n\tgot: %.*s",
i,
tests[i].url,
tests[i].expected.target.buf,
(int)result.target.len,
result.target.buf);
}
}
#endif /* FIO_TEST_CSTL */
/* *****************************************************************************
FIO_URL - Cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE */
#endif /* FIO_URL || FIO_URI */
#undef FIO_URL
#undef FIO_URI
|
janbiedermann/cstl
|
tests/json.c
|
<reponame>janbiedermann/cstl<gh_stars>10-100
#define FIO_CLI
#define FIO_LOG
#include "fio-stl.h"
#define FIO_FIOBJ
#include "fio-stl.h"
// Prettyfy JSON? this is passed as an argument to `fiobj2json`
#define PRETTY 0
int main(int argc, char const *argv[]) {
// a default string to demo
const char *json_cstr =
u8"{\n\t\"id\":1,\n"
"\t// comments are ignored.\n"
"\t\"number\":42,\n"
"\t\"float\":42.42,\n"
"\t\"string\":\"\\uD834\\uDD1E oh yeah...\",\n"
"\t\"hash\":{\n"
"\t\t\"nested\":true\n"
"\t},\n"
"\t\"symbols\":[\"id\","
"\"number\",\"float\",\"string\",\"hash\",\"symbols\"]\n}";
FIOBJ_STR_TEMP_VAR_STATIC(json, (char *)json_cstr, strlen(json_cstr));
fio_cli_start(
argc,
argv,
0,
1,
"This program runs a JSON roundtrip test. Use:\n\n\tNAME [-d] [-f "
"<filename>]\n\tNAME [-d] [JSON string]",
FIO_CLI_STRING("--file -f a file to load for JSON roundtrip testing."),
FIO_CLI_BOOL("--pretty -p -b test Beautify / Prettify roundtrip."),
FIO_CLI_BOOL("--verbose -v enable debugging mode logging."));
if (fio_cli_get_bool("-v")) {
FIO_LOG_LEVEL = FIO_LOG_LEVEL_DEBUG;
}
if (fio_cli_unnamed_count()) {
fiobj_str_destroy(json);
fiobj_str_write(json, fio_cli_unnamed(0), strlen(fio_cli_unnamed(0)));
}
if (fio_cli_get("-f")) {
fiobj_str_destroy(json);
if (!fiobj_str_readfile(json, fio_cli_get("-f"), 0, 0).buf) {
FIO_LOG_FATAL("File missing: %s", fio_cli_get("-f"));
exit(-1);
}
}
FIO_LOG_DEBUG2("attempting to parse:\n%s\n", fiobj_str2cstr(json).buf);
// Parsing the JSON
size_t consumed = 0;
FIOBJ obj1 = fiobj_json_parse2(
(char *)fiobj_str2cstr(json).buf, fiobj_str2cstr(json).len, &consumed);
// test for errors
FIO_ASSERT(obj1, "couldn't parse data.");
// formatting the JSON
size_t consumed2 = 0;
FIOBJ json2 = fiobj2json(FIOBJ_INVALID, obj1, fio_cli_get_bool("-b"));
FIOBJ obj2 = fiobj_json_parse2(
(char *)fiobj_str2cstr(json2).buf, fiobj_str2cstr(json2).len, &consumed2);
FIO_LOG_DEBUG2("JSON reprtinted:\n%s", fiobj_str2cstr(json2).buf);
FIO_ASSERT(obj2, "JSON roundtrip parsing failed");
FIO_LOG_DEBUG2("JSON re-parsed:\n%s", fiobj2cstr(obj2).buf);
FIO_ASSERT(consumed2 == fiobj_str2cstr(json2).len,
"Should have consumed all the stringified data");
FIO_ASSERT(fiobj_is_eq(obj1, obj2),
"roundtrip objects should have been equal:\n%s\n\t----VS----\n%s",
fiobj2cstr(obj1).buf,
fiobj2cstr(obj2).buf);
if (FIOBJ_TYPE(obj2) == FIOBJ_T_HASH &&
fiobj_hash_get3(obj2, "___sanity_test____ ____ ____ ", 29) !=
fiobj_true()) {
/* sanity test */
fiobj_hash_set3(obj2, "___sanity_test____ ____ ____ ", 29, fiobj_true());
FIO_ASSERT(
!fiobj_is_eq(obj1, obj2),
"Sanity test failed - objects shouldn't be equal after being updated");
}
// Formatting the JSON back to a String object and printing it up
fprintf(
stderr,
"-----PASSED-----\nJSON input was %zu bytes\nJSON output is %zu bytes.\n",
consumed,
(size_t)fiobj_str_len(json2));
// cleanup
FIOBJ_STR_TEMP_DESTROY(json);
fiobj_free(obj1);
fiobj_free(obj2);
fiobj_free(json2);
return 0;
}
|
janbiedermann/cstl
|
tests/http1_parser.h
|
/*
Copyright: <NAME>, 2017-2020
License: MIT
Feel free to copy, use and enjoy according to the license provided.
*/
/**
This is a callback based parser. It parses the skeleton of the HTTP/1.x protocol
and leaves most of the work (validation, error checks, etc') to the callbacks.
This is an attempt to replace the existing HTTP/1.x parser with something easier
to maintain and that could be used for an HTTP/1.x client as well.
*/
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
/* *****************************************************************************
Parser Settings
***************************************************************************** */
#ifndef HTTP_HEADERS_LOWERCASE
/**
* When defined, HTTP headers will be converted to lowercase and header
* searches will be case sensitive.
*
* This is highly recommended, required by facil.io and helps with HTTP/2
* compatibility.
*/
#define HTTP_HEADERS_LOWERCASE 1
#endif
#ifndef HTTP_ADD_CONTENT_LENGTH_HEADER_IF_MISSING
#define HTTP_ADD_CONTENT_LENGTH_HEADER_IF_MISSING 1
#endif
#ifndef FIO_MEMCHAR
/** Prefer a custom memchr implementation. Usualy memchr is better. */
#define FIO_MEMCHAR 0
#endif
#if FIO_UNALIGNED_MEMORY_ACCESS_ENABLED
#define HTTP1_UNALIGNED_MEMORY_ACCESS_ENABLED 1
#endif
#ifndef HTTP1_UNALIGNED_MEMORY_ACCESS_ENABLED
/** Peforms some optimizations assuming unaligned memory access is okay. */
#define HTTP1_UNALIGNED_MEMORY_ACCESS_ENABLED 0
#endif
/* *****************************************************************************
Parser API
***************************************************************************** */
/** this struct contains the state of the parser. */
typedef struct http1_parser_s {
struct http1_parser_protected_read_only_state_s {
long long content_length; /* negative values indicate chuncked data state */
ssize_t read; /* total number of bytes read so far (body only) */
uint8_t *next; /* the known position for the end of request/response */
uint8_t reserved; /* for internal use */
} state;
} http1_parser_s;
#define HTTP1_PARSER_INIT \
{ \
{ 0 } \
}
/**
* Returns the amount of data actually consumed by the parser.
*
* The value 0 indicates there wasn't enough data to be parsed and the same
* buffer (with more data) should be resubmitted.
*
* A value smaller than the buffer size indicates that EITHER a request /
* response was detected OR that the leftover could not be consumed because more
* data was required.
*
* Simply resubmit the reminder of the data to continue parsing.
*
* A request / response callback automatically stops the parsing process,
* allowing the user to adjust or refresh the state of the data.
*/
static size_t http1_parse(http1_parser_s *parser, void *buffer, size_t length);
/** Returns true if the parsing stopped after a complete request / response. */
inline static int http1_complete(http1_parser_s *parser);
/* *****************************************************************************
Required Callbacks (MUST be implemented by including file)
***************************************************************************** */
// clang-format off
/** called when a request was received. */
static int http1_on_request(http1_parser_s *parser);
/** called when a response was received. */
static int http1_on_response(http1_parser_s *parser);
/** called when a request method is parsed. */
static int
http1_on_method(http1_parser_s *parser, char *method, size_t method_len);
/** called when a response status is parsed. the status_str is the string
* without the prefixed numerical status indicator.*/
static int http1_on_status(http1_parser_s *parser, size_t status, char *status_str, size_t len);
/** called when a request path (excluding query) is parsed. */
static int http1_on_path(http1_parser_s *parser, char *path, size_t path_len);
/** called when a request path (excluding query) is parsed. */
static int
http1_on_query(http1_parser_s *parser, char *query, size_t query_len);
/** called when a the HTTP/1.x version is parsed. */
static int http1_on_version(http1_parser_s *parser, char *version, size_t len);
/** called when a header is parsed. */
static int http1_on_header(http1_parser_s *parser, char *name, size_t name_len, char *data, size_t data_len);
/** called when a body chunk is parsed. */
static int
http1_on_body_chunk(http1_parser_s *parser, char *data, size_t data_len);
/** called when a protocol error occurred. */
static int http1_on_error(http1_parser_s *parser);
// clang-format on
/* *****************************************************************************
Implementation Details
***************************************************************************** */
#if HTTP_HEADERS_LOWERCASE
#define HEADER_NAME_IS_EQ(var_name, const_name, len) \
(!memcmp((var_name), (const_name), (len)))
#else
#define HEADER_NAME_IS_EQ(var_name, const_name, len) \
(!strncasecmp((var_name), (const_name), (len)))
#endif
#define HTTP1_P_FLAG_STATUS_LINE 1
#define HTTP1_P_FLAG_HEADER_COMPLETE 2
#define HTTP1_P_FLAG_COMPLETE 4
#define HTTP1_P_FLAG_CLENGTH 8
#define HTTP1_PARSER_BIT_16 16
#define HTTP1_PARSER_BIT_32 32
#define HTTP1_P_FLAG_CHUNKED 64
#define HTTP1_P_FLAG_RESPONSE 128
/* *****************************************************************************
Seeking for characters in a string
***************************************************************************** */
#if FIO_MEMCHAR
/**
* This seems to be faster on some systems, especially for smaller distances.
*
* On newer systems, `memchr` should be faster.
*/
static int seek2ch(uint8_t **buffer,
register uint8_t *const limit,
const uint8_t c) {
if (*buffer >= limit)
return 0;
if (**buffer == c) {
return 1;
}
#if !HTTP1_UNALIGNED_MEMORY_ACCESS_ENABLED
/* too short for this mess */
if ((uintptr_t)limit <= 16 + ((uintptr_t)*buffer & (~(uintptr_t)7)))
goto finish;
/* align memory */
{
const uint8_t *alignment =
(uint8_t *)(((uintptr_t)(*buffer) & (~(uintptr_t)7)) + 8);
if (*buffer < alignment)
*buffer += 1; /* we already tested this char */
if (limit >= alignment) {
while (*buffer < alignment) {
if (**buffer == c) {
return 1;
}
*buffer += 1;
}
}
}
const uint8_t *limit64 = (uint8_t *)((uintptr_t)limit & (~(uintptr_t)7));
#else
const uint8_t *limit64 = (uint8_t *)limit - 7;
#endif
uint64_t wanted1 = 0x0101010101010101ULL * c;
for (; *buffer < limit64; *buffer += 8) {
const uint64_t eq1 = ~((*((uint64_t *)*buffer)) ^ wanted1);
const uint64_t t0 = (eq1 & 0x7f7f7f7f7f7f7f7fllu) + 0x0101010101010101llu;
const uint64_t t1 = (eq1 & 0x8080808080808080llu);
if ((t0 & t1)) {
break;
}
}
#if !HTTP1_UNALIGNED_MEMORY_ACCESS_ENABLED
finish:
#endif
while (*buffer < limit) {
if (**buffer == c) {
return 1;
}
(*buffer)++;
}
return 0;
}
#else
/* a helper that seeks any char, converts it to NUL and returns 1 if found. */
inline static uint8_t seek2ch(uint8_t **pos, uint8_t *const limit, uint8_t ch) {
/* This is library based alternative that is sometimes slower */
if (*pos >= limit)
return 0;
if (**pos == ch) {
return 1;
}
uint8_t *tmp = memchr(*pos, ch, limit - (*pos));
if (tmp) {
*pos = tmp;
return 1;
}
*pos = limit;
return 0;
}
#endif
/* a helper that seeks the EOL, converts it to NUL and returns it's length */
inline static uint8_t seek2eol(uint8_t **pos, uint8_t *const limit) {
/* single char lookup using memchr might be better when target is far... */
if (!seek2ch(pos, limit, '\n'))
return 0;
if ((*pos)[-1] == '\r') {
return 2;
}
return 1;
}
/* *****************************************************************************
Change a letter to lower case (latin only)
***************************************************************************** */
static uint8_t http_tolower(uint8_t c) {
if (c >= 'A' && c <= 'Z')
c |= 32;
return c;
}
/* *****************************************************************************
String to Number
***************************************************************************** */
/** Converts a String to a number using base 10 */
static long long http1_atol(const uint8_t *buf, const uint8_t **end) {
register unsigned long long i = 0;
uint8_t inv = 0;
while (*buf == ' ' || *buf == '\t' || *buf == '\f')
++buf;
while (*buf == '-' || *buf == '+')
inv ^= (*(buf++) == '-');
while (i <= ((((~0ULL) >> 1) / 10)) && *buf >= '0' && *buf <= '9') {
i = i * 10;
i += *buf - '0';
++buf;
}
/* test for overflow */
if (i >= (~((~0ULL) >> 1)) || (*buf >= '0' && *buf <= '9'))
i = (~0ULL >> 1);
if (inv)
i = 0ULL - i;
if (end)
*end = buf;
return i;
}
/** Converts a String to a number using base 16, overflow limited to 113bytes */
static long long http1_atol16(const uint8_t *buf, const uint8_t **end) {
register unsigned long long i = 0;
uint8_t inv = 0;
for (int limit_ = 0;
(*buf == ' ' || *buf == '\t' || *buf == '\f') && limit_ < 32;
++limit_)
++buf;
for (int limit_ = 0; (*buf == '-' || *buf == '+') && limit_ < 32; ++limit_)
inv ^= (*(buf++) == '-');
if (*buf == '0')
++buf;
if ((*buf | 32) == 'x')
++buf;
for (int limit_ = 0; (*buf == '0') && limit_ < 32; ++limit_)
++buf;
while (!(i & (~((~(0ULL)) >> 4)))) {
if (*buf >= '0' && *buf <= '9') {
i <<= 4;
i |= *buf - '0';
} else if ((*buf | 32) >= 'a' && (*buf | 32) <= 'f') {
i <<= 4;
i |= (*buf | 32) - ('a' - 10);
} else
break;
++buf;
}
if (inv)
i = 0ULL - i;
if (end)
*end = buf;
return i;
}
/* *****************************************************************************
HTTP/1.1 parsre stages
***************************************************************************** */
inline static int http1_consume_response_line(http1_parser_s *parser,
uint8_t *start,
uint8_t *end) {
parser->state.reserved |= HTTP1_P_FLAG_RESPONSE;
uint8_t *tmp = start;
if (!seek2ch(&tmp, end, ' '))
return -1;
if (http1_on_version(parser, (char *)start, tmp - start))
return -1;
tmp = start = tmp + 1;
if (!seek2ch(&tmp, end, ' '))
return -1;
if (http1_on_status(parser,
http1_atol(start, NULL),
(char *)(tmp + 1),
end - tmp))
return -1;
return 0;
}
inline static int http1_consume_request_line(http1_parser_s *parser,
uint8_t *start,
uint8_t *end) {
uint8_t *tmp = start;
uint8_t *host_start = NULL;
uint8_t *host_end = NULL;
if (!seek2ch(&tmp, end, ' '))
return -1;
if (http1_on_method(parser, (char *)start, tmp - start))
return -1;
tmp = start = tmp + 1;
if (start[0] == 'h' && start[1] == 't' && start[2] == 't' &&
start[3] == 'p') {
if (start[4] == ':' && start[5] == '/' && start[6] == '/') {
/* Request URI is in long form... emulate Host header instead. */
tmp = host_end = host_start = (start += 7);
} else if (start[4] == 's' && start[5] == ':' && start[6] == '/' &&
start[7] == '/') {
/* Secure request is in long form... emulate Host header instead. */
tmp = host_end = host_start = (start += 8);
} else
goto review_path;
if (!seek2ch(&tmp, end, ' '))
return -1;
*tmp = ' ';
if (!seek2ch(&host_end, tmp, '/')) {
if (http1_on_path(parser, (char *)"/", 1))
return -1;
goto start_version;
}
host_end[0] = '/';
start = host_end;
}
review_path:
tmp = start;
if (seek2ch(&tmp, end, '?')) {
if (http1_on_path(parser, (char *)start, tmp - start))
return -1;
tmp = start = tmp + 1;
if (!seek2ch(&tmp, end, ' '))
return -1;
if (tmp - start > 0 && http1_on_query(parser, (char *)start, tmp - start))
return -1;
} else {
tmp = start;
if (!seek2ch(&tmp, end, ' '))
return -1;
if (http1_on_path(parser, (char *)start, tmp - start))
return -1;
}
start_version:
start = tmp + 1;
if (start + 5 >= end) /* require "HTTP/" */
return -1;
if (http1_on_version(parser, (char *)start, end - start))
return -1;
/* */
if (host_start && http1_on_header(parser,
(char *)"host",
4,
(char *)host_start,
host_end - host_start))
return -1;
return 0;
}
#ifndef HTTP1_ALLOW_CHUNKED_IN_MIDDLE_OF_HEADER
inline /* inline the function of it's short enough */
#endif
static int
http1_consume_header_transfer_encoding(http1_parser_s *parser,
uint8_t *start,
uint8_t *end_name,
uint8_t *start_value,
uint8_t *end) {
/* this removes the `chunked` marker and prepares to "unchunk" the data */
while (start_value < end && (end[-1] == ',' || end[-1] == ' '))
--end;
if ((end - start_value) == 7 &&
#if HTTP1_UNALIGNED_MEMORY_ACCESS_ENABLED
(((uint32_t *)(start_value))[0] | 0x20202020) ==
((uint32_t *)"chun")[0] &&
(((uint32_t *)(start_value + 3))[0] | 0x20202020) ==
((uint32_t *)"nked")[0]
#else
((start_value[0] | 32) == 'c' && (start_value[1] | 32) == 'h' &&
(start_value[2] | 32) == 'u' && (start_value[3] | 32) == 'n' &&
(start_value[4] | 32) == 'k' && (start_value[5] | 32) == 'e' &&
(start_value[6] | 32) == 'd')
#endif
) {
/* simple case,only `chunked` as a value */
parser->state.reserved |= HTTP1_P_FLAG_CHUNKED;
parser->state.content_length = 0;
start_value += 7;
while (start_value < end && (*start_value == ',' || *start_value == ' '))
++start_value;
if (!(end - start_value))
return 0;
} else if ((end - start_value) > 7 &&
((end[(-7 + 0)] | 32) == 'c' && (end[(-7 + 1)] | 32) == 'h' &&
(end[(-7 + 2)] | 32) == 'u' && (end[(-7 + 3)] | 32) == 'n' &&
(end[(-7 + 4)] | 32) == 'k' && (end[(-7 + 5)] | 32) == 'e' &&
(end[(-7 + 6)] | 32) == 'd')) {
/* simple case,`chunked` at the end of list (RFC required) */
parser->state.reserved |= HTTP1_P_FLAG_CHUNKED;
parser->state.content_length = 0;
end -= 7;
while (start_value < end && (end[-1] == ',' || end[-1] == ' '))
--end;
if (!(end - start_value))
return 0;
}
#ifdef HTTP1_ALLOW_CHUNKED_IN_MIDDLE_OF_HEADER /* RFC diisallows this */
else if ((end - start_value) > 7 && (end - start_value) < 256) {
/* complex case, `the, chunked, marker, is in the middle of list */
uint8_t val[256];
size_t val_len = 0;
while (start_value < end && val_len < 256) {
if ((end - start_value) >= 7) {
if (
#if HTTP1_UNALIGNED_MEMORY_ACCESS_ENABLED
(((uint32_t *)(start_value))[0] | 0x20202020) ==
((uint32_t *)"chun")[0] &&
(((uint32_t *)(start_value + 3))[0] | 0x20202020) ==
((uint32_t *)"nked")[0]
#else
((start_value[0] | 32) == 'c' && (start_value[1] | 32) == 'h' &&
(start_value[2] | 32) == 'u' && (start_value[3] | 32) == 'n' &&
(start_value[4] | 32) == 'k' && (start_value[5] | 32) == 'e' &&
(start_value[6] | 32) == 'd')
#endif
) {
parser->state.reserved |= HTTP1_P_FLAG_CHUNKED;
parser->state.content_length = 0;
start_value += 7;
/* skip comma / white space */
while (start_value < end &&
(*start_value == ',' || *start_value == ' '))
++start_value;
continue;
}
}
/* copy value */
while (start_value < end && val_len < 256 && start_value[0] != ',') {
val[val_len++] = *start_value;
++start_value;
}
/* copy comma */
if (start_value[0] == ',' && val_len < 256) {
val[val_len++] = *start_value;
++start_value;
}
/* skip spaces */
while (start_value < end && start_value[0] == ' ') {
++start_value;
}
}
if (val_len < 256) {
while (start_value < end && val_len < 256) {
val[val_len++] = *start_value;
++start_value;
}
if (val_len < 255)
val[val_len] = 0;
}
/* perform callback with `val` or indicate error */
if (val_len == 256 || (val_len && http1_on_header(parser,
(char *)start,
(end_name - start),
(char *)val,
val_len)))
return -1;
return 0;
}
#endif /* HTTP1_ALLOW_CHUNKED_IN_MIDDLE_OF_HEADER */
/* perform callback */
if (http1_on_header(parser,
(char *)start,
(end_name - start),
(char *)start_value,
end - start_value))
return -1;
return 0;
}
inline static int http1_consume_header_top(http1_parser_s *parser,
uint8_t *start,
uint8_t *end_name,
uint8_t *start_value,
uint8_t *end) {
if ((end_name - start) == 14 &&
#if HTTP1_UNALIGNED_MEMORY_ACCESS_ENABLED && HTTP_HEADERS_LOWERCASE
*((uint64_t *)start) == *((uint64_t *)"content-") &&
*((uint64_t *)(start + 6)) == *((uint64_t *)"t-length")
#else
HEADER_NAME_IS_EQ((char *)start, "content-length", 14)
#endif
) {
/* handle the special `content-length` header */
if ((parser->state.reserved & HTTP1_P_FLAG_CHUNKED))
return 0; /* ignore if `chunked` */
long long old_clen = parser->state.content_length;
parser->state.content_length = http1_atol(start_value, NULL);
if ((parser->state.reserved & HTTP1_P_FLAG_CLENGTH) &&
old_clen != parser->state.content_length) {
/* content-length header repeated with conflict */
return -1;
}
parser->state.reserved |= HTTP1_P_FLAG_CLENGTH;
} else if ((end_name - start) == 17 && (end - start_value) >= 7 &&
!parser->state.content_length &&
#if HTTP1_UNALIGNED_MEMORY_ACCESS_ENABLED && HTTP_HEADERS_LOWERCASE
*((uint64_t *)start) == *((uint64_t *)"transfer") &&
*((uint64_t *)(start + 8)) == *((uint64_t *)"-encodin")
#else
HEADER_NAME_IS_EQ((char *)start, "transfer-encoding", 17)
#endif
) {
/* handle the special `transfer-encoding: chunked` header */
return http1_consume_header_transfer_encoding(parser,
start,
end_name,
start_value,
end);
}
/* perform callback */
if (http1_on_header(parser,
(char *)start,
(end_name - start),
(char *)start_value,
end - start_value))
return -1;
return 0;
}
inline static int http1_consume_header_trailer(http1_parser_s *parser,
uint8_t *start,
uint8_t *end_name,
uint8_t *start_value,
uint8_t *end) {
if ((end_name - start) > 1 && start[0] == 'x') {
/* X- headers are allowed */
goto white_listed;
}
/* white listed trailer names */
const struct {
char *name;
long len;
} http1_trailer_white_list[] = {
{"server-timing", 13}, /* specific for client data... */
{NULL, 0}, /* end of list marker */
};
for (size_t i = 0; http1_trailer_white_list[i].name; ++i) {
if ((long)(end_name - start) == http1_trailer_white_list[i].len &&
HEADER_NAME_IS_EQ((char *)start,
http1_trailer_white_list[i].name,
http1_trailer_white_list[i].len)) {
/* header disallowed here */
goto white_listed;
}
}
return 0;
white_listed:
/* perform callback */
if (http1_on_header(parser,
(char *)start,
(end_name - start),
(char *)start_value,
end - start_value))
return -1;
return 0;
}
inline static int http1_consume_header(http1_parser_s *parser,
uint8_t *start,
uint8_t *end) {
uint8_t *end_name = start;
/* divide header name from data */
if (!seek2ch(&end_name, end, ':'))
return -1;
if (end_name[-1] == ' ' || end_name[-1] == '\t')
return -1;
#if HTTP_HEADERS_LOWERCASE
for (uint8_t *t = start; t < end_name; t++) {
*t = http_tolower(*t);
}
#endif
uint8_t *start_value = end_name + 1;
// clear away leading white space from value.
while (start_value < end &&
(start_value[0] == ' ' || start_value[0] == '\t')) {
start_value++;
};
return (parser->state.read ? http1_consume_header_trailer
: http1_consume_header_top)(parser,
start,
end_name,
start_value,
end);
}
/* *****************************************************************************
HTTP/1.1 Body handling
***************************************************************************** */
inline static int http1_consume_body_streamed(http1_parser_s *parser,
void *buffer,
size_t length,
uint8_t **start) {
uint8_t *end = *start + parser->state.content_length - parser->state.read;
uint8_t *const stop = ((uint8_t *)buffer) + length;
if (end > stop)
end = stop;
if (end > *start &&
http1_on_body_chunk(parser, (char *)(*start), end - *start))
return -1;
parser->state.read += (end - *start);
*start = end;
if (parser->state.content_length <= parser->state.read)
parser->state.reserved |= HTTP1_P_FLAG_COMPLETE;
return 0;
}
inline static int http1_consume_body_chunked(http1_parser_s *parser,
void *buffer,
size_t length,
uint8_t **start) {
uint8_t *const stop = ((uint8_t *)buffer) + length;
uint8_t *end = *start;
while (*start < stop) {
if (parser->state.content_length == 0) {
if (end + 2 >= stop)
return 0;
if ((end[0] == '\r' && end[1] == '\n')) {
/* remove tailing EOL that wasn't processed and retest */
end += 2;
*start = end;
if (end + 2 >= stop)
return 0;
}
long long chunk_len = http1_atol16(end, (const uint8_t **)&end);
if (end + 2 > stop) /* overflowed? */
return 0;
if ((end[0] != '\r' || end[1] != '\n'))
return -1; /* required EOL after content length */
end += 2;
parser->state.content_length = 0 - chunk_len;
*start = end;
if (parser->state.content_length == 0) {
/* all chunked data was parsed */
/* update content-length */
parser->state.content_length = parser->state.read;
#ifdef HTTP_ADD_CONTENT_LENGTH_HEADER_IF_MISSING
{ /* add virtual header ... ? */
char buf[512];
size_t buf_len = 512;
size_t tmp_len = parser->state.read;
buf[--buf_len] = 0;
while (tmp_len) {
size_t mod = tmp_len / 10;
buf[--buf_len] = '0' + (tmp_len - (mod * 10));
tmp_len = mod;
}
if (!(parser->state.reserved & HTTP1_P_FLAG_CLENGTH) &&
http1_on_header(parser,
(char *)"content-length",
14,
(char *)buf + buf_len,
511 - buf_len)) {
return -1;
}
}
#endif
/* consume trailing EOL */
if (*start + 2 <= stop && (start[0][0] == '\r' || start[0][0] == '\n'))
*start += 1 + (start[0][1] == '\r' || start[0][1] == '\n');
else {
/* remove the "headers complete" and "trailer" flags */
parser->state.reserved =
HTTP1_P_FLAG_STATUS_LINE | HTTP1_P_FLAG_CLENGTH;
return -2;
}
/* the parsing complete flag */
parser->state.reserved |= HTTP1_P_FLAG_COMPLETE;
return 0;
}
}
end = *start + (0 - parser->state.content_length);
if (end > stop)
end = stop;
if (end > *start &&
http1_on_body_chunk(parser, (char *)(*start), end - *start)) {
return -1;
}
parser->state.read += (end - *start);
parser->state.content_length += (end - *start);
*start = end;
}
return 0;
}
inline static int http1_consume_body(http1_parser_s *parser,
void *buffer,
size_t length,
uint8_t **start) {
if (parser->state.content_length > 0 &&
parser->state.content_length > parser->state.read) {
/* normal, streamed data */
return http1_consume_body_streamed(parser, buffer, length, start);
} else if (parser->state.content_length <= 0 &&
(parser->state.reserved & HTTP1_P_FLAG_CHUNKED)) {
/* chuncked encoding */
return http1_consume_body_chunked(parser, buffer, length, start);
} else {
/* nothing to do - parsing complete */
parser->state.reserved |= HTTP1_P_FLAG_COMPLETE;
}
return 0;
}
/* *****************************************************************************
HTTP/1.1 parsre function
***************************************************************************** */
#if DEBUG
#include <assert.h>
#define HTTP1_ASSERT assert
#else
#define HTTP1_ASSERT(...)
#endif
/**
* Returns the amount of data actually consumed by the parser.
*
* The value 0 indicates there wasn't enough data to be parsed and the same
* buffer (with more data) should be resubmitted.
*
* A value smaller than the buffer size indicates that EITHER a request /
* response was detected OR that the leftover could not be consumed because more
* data was required.
*
* Simply resubmit the reminder of the data to continue parsing.
*
* A request / response callback automatically stops the parsing process,
* allowing the user to adjust or refresh the state of the data.
*/
static size_t http1_parse(http1_parser_s *parser, void *buffer, size_t length) {
if (!length)
return 0;
HTTP1_ASSERT(parser && buffer);
parser->state.next = NULL;
uint8_t *start = (uint8_t *)buffer;
uint8_t *end = start;
uint8_t *const stop = start + length;
uint8_t eol_len = 0;
#define HTTP1_CONSUMED ((size_t)((uintptr_t)start - (uintptr_t)buffer))
re_eval:
switch ((parser->state.reserved & 7)) {
case 0: /* request / response line */
/* clear out any leading white space */
while ((start < stop) &&
(*start == '\r' || *start == '\n' || *start == ' ' || *start == 0)) {
++start;
}
end = start;
/* make sure the whole line is available*/
if (!(eol_len = seek2eol(&end, stop)))
return HTTP1_CONSUMED;
if (start[0] == 'H' && start[1] == 'T' && start[2] == 'T' &&
start[3] == 'P') {
/* HTTP response */
if (http1_consume_response_line(parser, start, end - eol_len + 1))
goto error;
} else if (http_tolower(start[0]) >= 'a' && http_tolower(start[0]) <= 'z') {
/* HTTP request */
if (http1_consume_request_line(parser, start, end - eol_len + 1))
goto error;
} else
goto error;
end = start = end + 1;
parser->state.reserved |= HTTP1_P_FLAG_STATUS_LINE;
/* fallthrough */
case 1: /* headers */
do {
if (start >= stop)
return HTTP1_CONSUMED; /* buffer ended on header line */
if (*start == '\r' || *start == '\n') {
goto finished_headers; /* empty line, end of headers */
}
end = start;
if (!(eol_len = seek2eol(&end, stop)))
return HTTP1_CONSUMED;
if (http1_consume_header(parser, start, end - eol_len + 1))
goto error;
end = start = end + 1;
} while ((parser->state.reserved & HTTP1_P_FLAG_HEADER_COMPLETE) == 0);
finished_headers:
++start;
if (*start == '\n')
++start;
end = start;
parser->state.reserved |= HTTP1_P_FLAG_HEADER_COMPLETE;
/* fallthrough */
case (HTTP1_P_FLAG_HEADER_COMPLETE | HTTP1_P_FLAG_STATUS_LINE):
/* request body */
{
int t3 = http1_consume_body(parser, buffer, length, &start);
switch (t3) {
case -1:
goto error;
case -2:
goto re_eval;
}
break;
}
}
/* are we done ? */
if (parser->state.reserved & HTTP1_P_FLAG_COMPLETE) {
parser->state.next = start;
if (((parser->state.reserved & HTTP1_P_FLAG_RESPONSE)
? http1_on_response
: http1_on_request)(parser))
goto error;
parser->state = (struct http1_parser_protected_read_only_state_s){0};
}
return HTTP1_CONSUMED;
error:
http1_on_error(parser);
parser->state = (struct http1_parser_protected_read_only_state_s){0};
return length;
#undef HTTP1_CONSUMED
}
/** Returns true if the parsing stopped after a complete request / response. */
inline static int http1_complete(http1_parser_s *parser) {
return !parser->state.reserved;
}
/* *****************************************************************************
HTTP/1.1 TESTING
***************************************************************************** */
#ifdef HTTP1_TEST_PARSER
#include "signal.h"
#define HTTP1_TEST_ASSERT(cond, ...) \
if (!(cond)) { \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n"); \
kill(0, SIGINT); \
exit(-1); \
}
static size_t http1_test_pos;
static char http1_test_temp_buf[8092];
static size_t http1_test_temp_buf_pos;
static struct {
char *test_name;
char *request[16];
struct {
char body[1024];
size_t body_len;
const char *method;
ssize_t status;
const char *path;
const char *query;
const char *version;
struct http1_test_header_s {
const char *name;
size_t name_len;
const char *val;
size_t val_len;
} headers[12];
} result, expect;
} http1_test_data[] = {
{
.test_name = "simple empty request",
.request = {"GET / HTTP/1.1\r\nHost:localhost\r\n\r\n"},
.expect =
{
.body = "",
.body_len = 0,
.method = "GET",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{.name = "host",
.name_len = 4,
.val = "localhost",
.val_len = 9},
},
},
},
{
.test_name = "space before header data",
.request = {"POST /my/path HTTP/1.2\r\nHost: localhost\r\n\r\n"},
.expect =
{
.body = "",
.body_len = 0,
.method = "POST",
.path = "/my/path",
.query = NULL,
.version = "HTTP/1.2",
.headers =
{
{.name = "host",
.name_len = 4,
.val = "localhost",
.val_len = 9},
},
},
},
{
.test_name = "simple request, fragmented header (in new line)",
.request = {"GET / HTTP/1.1\r\n", "Host:localhost\r\n\r\n"},
.expect =
{
.body = "",
.body_len = 0,
.method = "GET",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{.name = "host",
.name_len = 4,
.val = "localhost",
.val_len = 9},
},
},
},
{
.test_name = "request with query",
.request = {"METHOD /path?q=query HTTP/1.3\r\nHost:localhost\r\n\r\n"},
.expect =
{
.body = "",
.body_len = 0,
.method = "METHOD",
.path = "/path",
.query = "q=query",
.version = "HTTP/1.3",
.headers =
{
{.name = "host",
.name_len = 4,
.val = "localhost",
.val_len = 9},
},
},
},
{
.test_name = "mid-fragmented header",
.request = {"GET / HTTP/1.1\r\nHost: loca", "lhost\r\n\r\n"},
.expect =
{
.body = "",
.body_len = 0,
.method = "GET",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{.name = "host",
.name_len = 4,
.val = "localhost",
.val_len = 9},
},
},
},
{
.test_name = "simple with body",
.request = {"GET / HTTP/1.1\r\nHost:with body\r\n"
"Content-lEnGth: 5\r\n\r\nHello"},
.expect =
{
.body = "Hello",
.body_len = 5,
.method = "GET",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{
.name = "host",
.name_len = 4,
.val = "with body",
.val_len = 9,
},
{
.name = "content-length",
.name_len = 14,
.val = "5",
.val_len = 1,
},
},
},
},
{
.test_name = "fragmented body",
.request = {"GET / HTTP/1.1\r\nHost:with body\r\n",
"Content-lEnGth: 5\r\n\r\nHe",
"llo"},
.expect =
{
.body = "Hello",
.body_len = 5,
.method = "GET",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{
.name = "host",
.name_len = 4,
.val = "with body",
.val_len = 9,
},
{
.name = "content-length",
.name_len = 14,
.val = "5",
.val_len = 1,
},
},
},
},
{
.test_name = "fragmented body 2 (cuts EOL)",
.request = {"POST / HTTP/1.1\r\nHost:with body\r\n",
"Content-lEnGth: 5\r\n",
"\r\n",
"He",
"llo"},
.expect =
{
.body = "Hello",
.body_len = 5,
.method = "POST",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{
.name = "host",
.name_len = 4,
.val = "with body",
.val_len = 9,
},
{
.name = "content-length",
.name_len = 14,
.val = "5",
.val_len = 1,
},
},
},
},
{
.test_name = "chunked body (simple)",
.request = {"POST / HTTP/1.1\r\nHost:with body\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"5\r\n"
"Hello"
"\r\n0\r\n\r\n"},
.expect =
{
.body = "Hello",
.body_len = 5,
.method = "POST",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{
.name = "host",
.name_len = 4,
.val = "with body",
.val_len = 9,
},
#ifdef HTTP_ADD_CONTENT_LENGTH_HEADER_IF_MISSING
{
.name = "content-length",
.name_len = 14,
.val = "5",
.val_len = 1,
},
#endif
},
},
},
{
.test_name = "chunked body (end of list)",
.request = {"POST / HTTP/1.1\r\nHost:with body\r\n"
"Transfer-Encoding: gzip, foo, chunked\r\n"
"\r\n"
"5\r\n"
"Hello"
"\r\n0\r\n\r\n"},
.expect =
{
.body = "Hello",
.body_len = 5,
.method = "POST",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{
.name = "host",
.name_len = 4,
.val = "with body",
.val_len = 9,
},
{
.name = "transfer-encoding",
.name_len = 17,
.val = "gzip, foo",
.val_len = 9,
},
#ifdef HTTP_ADD_CONTENT_LENGTH_HEADER_IF_MISSING
{
.name = "content-length",
.name_len = 14,
.val = "5",
.val_len = 1,
},
#endif
},
},
},
#ifdef HTTP1_ALLOW_CHUNKED_IN_MIDDLE_OF_HEADER
{
.test_name = "chunked body (middle of list)",
.request = {"POST / HTTP/1.1\r\nHost:with body\r\n"
"Transfer-Encoding: gzip, chunked, foo\r\n"
"\r\n",
"5\r\n"
"Hello"
"\r\n0\r\n\r\n"},
.expect =
{
.body = "Hello",
.body_len = 5,
.method = "POST",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{
.name = "host",
.name_len = 4,
.val = "with body",
.val_len = 9,
},
{
.name = "transfer-encoding",
.name_len = 17,
.val = "gzip,foo",
.val_len = 8,
},
#ifdef HTTP_ADD_CONTENT_LENGTH_HEADER_IF_MISSING
{
.name = "content-length",
.name_len = 14,
.val = "5",
.val_len = 1,
},
#endif
},
},
},
#endif /* HTTP1_ALLOW_CHUNKED_IN_MIDDLE_OF_HEADER */
{
.test_name = "chunked body (fragmented)",
.request =
{
"POST / HTTP/1.1\r\nHost:with body\r\n",
"Transfer-Encoding: chunked\r\n",
"\r\n"
"5\r\n",
"He",
"llo",
"\r\n0\r\n\r\n",
},
.expect =
{
.body = "Hello",
.body_len = 5,
.method = "POST",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{
.name = "host",
.name_len = 4,
.val = "with body",
.val_len = 9,
},
#ifdef HTTP_ADD_CONTENT_LENGTH_HEADER_IF_MISSING
{
.name = "content-length",
.name_len = 14,
.val = "5",
.val_len = 1,
},
#endif
},
},
},
{
.test_name = "chunked body (fragmented + multi-message)",
.request =
{
"POST / HTTP/1.1\r\nHost:with body\r\n",
"Transfer-Encoding: chunked\r\n",
"\r\n"
"2\r\n",
"He",
"3\r\nl",
"lo",
"\r\n0\r\n\r\n",
},
.expect =
{
.body = "Hello",
.body_len = 5,
.method = "POST",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{
.name = "host",
.name_len = 4,
.val = "with body",
.val_len = 9,
},
#ifdef HTTP_ADD_CONTENT_LENGTH_HEADER_IF_MISSING
{
.name = "content-length",
.name_len = 14,
.val = "5",
.val_len = 1,
},
#endif
},
},
},
{
.test_name = "chunked body (fragmented + broken-multi-message)",
.request =
{
"POST / HTTP/1.1\r\nHost:with body\r\n",
"Transfer-Encoding: chunked\r\n",
"\r\n",
"2\r\n",
"H",
"e",
"3\r\nl",
"l"
"o",
"\r\n0\r\n\r\n",
},
.expect =
{
.body = "Hello",
.body_len = 5,
.method = "POST",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{
.name = "host",
.name_len = 4,
.val = "with body",
.val_len = 9,
},
#ifdef HTTP_ADD_CONTENT_LENGTH_HEADER_IF_MISSING
{
.name = "content-length",
.name_len = 14,
.val = "5",
.val_len = 1,
},
#endif
},
},
},
{
.test_name = "chunked body (...longer + trailer + empty value...)",
.request =
{
"POST / HTTP/1.1\r\nHost:with body\r\n",
"Transfer-Encoding: chunked\r\n",
"\r\n",
"4\r\n",
"Wiki\r\n",
"5\r\n",
"pedia\r\n",
"E\r\n",
" in\r\n",
"\r\n",
"chunks.\r\n",
"0\r\n",
"X-Foo: trailer\r\n",
"sErvEr-tiMing: \r\n",
"\r\n",
},
.expect =
{
.body = "Wikipedia in\r\n\r\nchunks.",
.body_len = 23,
.method = "POST",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{
.name = "host",
.name_len = 4,
.val = "with body",
.val_len = 9,
},
#ifdef HTTP_ADD_CONTENT_LENGTH_HEADER_IF_MISSING
{
.name = "content-length",
.name_len = 14,
.val = "23",
.val_len = 2,
},
#endif
{
.name = "x-foo",
.name_len = 5,
.val = "trailer",
.val_len = 7,
},
{
.name = "server-timing",
.name_len = 13,
.val = "",
.val_len = 0,
},
},
},
},
{
.test_name = "chunked body (fragmented + surprize trailer)",
.request =
{
"POST / HTTP/1.1\r\nHost:with body\r\n",
"Transfer-Encoding: chunked\r\n",
"\r\n"
"5\r\n",
"He",
"llo",
"\r\n0\r\nX-Foo: trailer\r\n\r\n",
},
.expect =
{
.body = "Hello",
.body_len = 5,
.method = "POST",
.path = "/",
.query = NULL,
.version = "HTTP/1.1",
.headers =
{
{
.name = "host",
.name_len = 4,
.val = "with body",
.val_len = 9,
},
#ifdef HTTP_ADD_CONTENT_LENGTH_HEADER_IF_MISSING
{
.name = "content-length",
.name_len = 14,
.val = "5",
.val_len = 1,
},
#endif
{
.name = "x-foo",
.name_len = 5,
.val = "trailer",
.val_len = 7,
},
},
},
},
/* stop marker */
{
.request = {NULL},
},
};
/** called when a request was received. */
static int http1_on_request(http1_parser_s *parser) {
(void)parser;
return 0;
}
/** called when a response was received. */
static int http1_on_response(http1_parser_s *parser) {
(void)parser;
return 0;
}
/** called when a request method is parsed. */
static int http1_on_method(http1_parser_s *parser,
char *method,
size_t method_len) {
(void)parser;
http1_test_data[http1_test_pos].result.method = method;
HTTP1_TEST_ASSERT(method_len ==
strlen(http1_test_data[http1_test_pos].expect.method),
"method_len test error for: %s",
http1_test_data[http1_test_pos].test_name);
return 0;
}
/** called when a response status is parsed. the status_str is the string
* without the prefixed numerical status indicator.*/
static int http1_on_status(http1_parser_s *parser,
size_t status,
char *status_str,
size_t len) {
(void)parser;
http1_test_data[http1_test_pos].result.status = status;
http1_test_data[http1_test_pos].result.method = status_str;
HTTP1_TEST_ASSERT(len ==
strlen(http1_test_data[http1_test_pos].expect.method),
"status length test error for: %s",
http1_test_data[http1_test_pos].test_name);
return 0;
}
/** called when a request path (excluding query) is parsed. */
static int http1_on_path(http1_parser_s *parser, char *path, size_t len) {
(void)parser;
http1_test_data[http1_test_pos].result.path = path;
HTTP1_TEST_ASSERT(len == strlen(http1_test_data[http1_test_pos].expect.path),
"path length test error for: %s",
http1_test_data[http1_test_pos].test_name);
return 0;
}
/** called when a request path (excluding query) is parsed. */
static int http1_on_query(http1_parser_s *parser, char *query, size_t len) {
(void)parser;
http1_test_data[http1_test_pos].result.query = query;
HTTP1_TEST_ASSERT(len == strlen(http1_test_data[http1_test_pos].expect.query),
"query length test error for: %s",
http1_test_data[http1_test_pos].test_name);
return 0;
}
/** called when a the HTTP/1.x version is parsed. */
static int http1_on_version(http1_parser_s *parser, char *version, size_t len) {
(void)parser;
http1_test_data[http1_test_pos].result.version = version;
HTTP1_TEST_ASSERT(len ==
strlen(http1_test_data[http1_test_pos].expect.version),
"version length test error for: %s",
http1_test_data[http1_test_pos].test_name);
return 0;
}
/** called when a header is parsed. */
static int http1_on_header(http1_parser_s *parser,
char *name,
size_t name_len,
char *val,
size_t val_len) {
(void)parser;
size_t pos = 0;
while (pos < 12 && http1_test_data[http1_test_pos].result.headers[pos].name)
++pos;
HTTP1_TEST_ASSERT(pos < 12,
"header result overflow for: %s",
http1_test_data[http1_test_pos].test_name);
memcpy(http1_test_temp_buf + http1_test_temp_buf_pos, name, name_len);
name = http1_test_temp_buf + http1_test_temp_buf_pos;
http1_test_temp_buf_pos += name_len;
http1_test_temp_buf[http1_test_temp_buf_pos++] = 0;
memcpy(http1_test_temp_buf + http1_test_temp_buf_pos, val, val_len);
val = http1_test_temp_buf + http1_test_temp_buf_pos;
http1_test_temp_buf_pos += val_len;
http1_test_temp_buf[http1_test_temp_buf_pos++] = 0;
http1_test_data[http1_test_pos].result.headers[pos].name = name;
http1_test_data[http1_test_pos].result.headers[pos].name_len = name_len;
http1_test_data[http1_test_pos].result.headers[pos].val = val;
http1_test_data[http1_test_pos].result.headers[pos].val_len = val_len;
return 0;
}
/** called when a body chunk is parsed. */
static int http1_on_body_chunk(http1_parser_s *parser,
char *data,
size_t data_len) {
(void)parser;
http1_test_data[http1_test_pos]
.result.body[http1_test_data[http1_test_pos].result.body_len] = 0;
HTTP1_TEST_ASSERT(data_len +
http1_test_data[http1_test_pos].result.body_len <=
http1_test_data[http1_test_pos].expect.body_len,
"body overflow for: %s"
"\r\n Expect:\n%s\nGot:\n%s%s\n",
http1_test_data[http1_test_pos].test_name,
http1_test_data[http1_test_pos].expect.body,
http1_test_data[http1_test_pos].result.body,
data);
memcpy(http1_test_data[http1_test_pos].result.body +
http1_test_data[http1_test_pos].result.body_len,
data,
data_len);
http1_test_data[http1_test_pos].result.body_len += data_len;
http1_test_data[http1_test_pos]
.result.body[http1_test_data[http1_test_pos].result.body_len] = 0;
return 0;
}
/** called when a protocol error occurred. */
static int http1_on_error(http1_parser_s *parser) {
(void)parser;
http1_test_data[http1_test_pos].result.status = -1;
return 0;
}
#define HTTP1_TEST_STRING_FIELD(field, i) \
HTTP1_TEST_ASSERT((!http1_test_data[i].expect.field && \
!http1_test_data[i].result.field) || \
http1_test_data[i].expect.field && \
http1_test_data[i].result.field && \
!memcmp(http1_test_data[i].expect.field, \
http1_test_data[i].result.field, \
strlen(http1_test_data[i].expect.field)), \
"string field error for %s\n%s\n%s", \
http1_test_data[i].test_name, \
http1_test_data[i].expect.field, \
http1_test_data[i].result.field);
static void http1_parser_test(void) {
http1_test_pos = 0;
struct {
const char *str;
long long num;
long long (*fn)(const uint8_t *, const uint8_t **);
} atol_test[] = {
{
.str = "0",
.num = 0,
.fn = http1_atol,
},
{
.str = "-0",
.num = 0,
.fn = http1_atol,
},
{
.str = "1",
.num = 1,
.fn = http1_atol,
},
{
.str = "-1",
.num = -1,
.fn = http1_atol,
},
{
.str = "123456789",
.num = 123456789,
.fn = http1_atol,
},
{
.str = "-123456789",
.num = -123456789,
.fn = http1_atol,
},
{
.str = "0x0",
.num = 0,
.fn = http1_atol16,
},
{
.str = "-0x0",
.num = 0,
.fn = http1_atol16,
},
{
.str = "-0x1",
.num = -1,
.fn = http1_atol16,
},
{
.str = "-f",
.num = -15,
.fn = http1_atol16,
},
{
.str = "-20",
.num = -32,
.fn = http1_atol16,
},
{
.str = "0xf0EAf9ff",
.num = 0xf0eaf9ff,
.fn = http1_atol16,
},
/* stop marker */
{
.str = NULL,
},
};
fprintf(stderr, "* testing string=>number conversion\n");
for (size_t i = 0; atol_test[i].str; ++i) {
const uint8_t *end;
fprintf(stderr, " %s", atol_test[i].str);
HTTP1_TEST_ASSERT(atol_test[i].fn((const uint8_t *)atol_test[i].str,
&end) == atol_test[i].num,
"\nhttp1_atol error: %s != %lld",
atol_test[i].str,
atol_test[i].num);
HTTP1_TEST_ASSERT((char *)end ==
(atol_test[i].str + strlen(atol_test[i].str)),
"\nhttp1_atol error: didn't end after (%s): %s",
atol_test[i].str,
(char *)end)
}
fprintf(stderr, "\n");
for (unsigned long long i = 1; i; i <<= 1) {
char tmp[128];
size_t tmp_len = sprintf(tmp, "%llx", i);
uint8_t *pos = (uint8_t *)tmp;
HTTP1_TEST_ASSERT(http1_atol16(pos, (const uint8_t **)&pos) ==
(long long)i &&
pos == (uint8_t *)(tmp + tmp_len),
"http1_atol16 roundtrip error.");
}
for (size_t i = 0; http1_test_data[i].request[0]; ++i) {
fprintf(stderr, "* http1 parser test: %s\n", http1_test_data[i].test_name);
/* parse each request / response */
http1_parser_s parser = HTTP1_PARSER_INIT;
char buf[4096];
size_t r = 0;
size_t w = 0;
http1_test_temp_buf_pos = 0;
for (int j = 0; http1_test_data[i].request[j]; ++j) {
memcpy(buf + w,
http1_test_data[i].request[j],
strlen(http1_test_data[i].request[j]));
w += strlen(http1_test_data[i].request[j]);
size_t p = http1_parse(&parser, buf + r, w - r);
r += p;
HTTP1_TEST_ASSERT(r <= w, "parser consumed more than the buffer holds!");
}
/* test each request / response before overwriting the buffer */
HTTP1_TEST_STRING_FIELD(body, i);
HTTP1_TEST_STRING_FIELD(method, i);
HTTP1_TEST_STRING_FIELD(path, i);
HTTP1_TEST_STRING_FIELD(version, i);
r = 0;
while (http1_test_data[i].result.headers[r].name) {
HTTP1_TEST_STRING_FIELD(headers[r].name, i);
HTTP1_TEST_STRING_FIELD(headers[r].val, i);
HTTP1_TEST_ASSERT(http1_test_data[i].expect.headers[r].val_len ==
http1_test_data[i].result.headers[r].val_len &&
http1_test_data[i].expect.headers[r].name_len ==
http1_test_data[i].result.headers[r].name_len,
"--- name / value length error");
++r;
}
HTTP1_TEST_ASSERT(!http1_test_data[i].expect.headers[r].name,
"Expected header missing:\n\t%s: %s",
http1_test_data[i].expect.headers[r].name,
http1_test_data[i].expect.headers[r].val);
/* advance counter */
++http1_test_pos;
}
}
#endif
|
janbiedermann/cstl
|
tests/random.c
|
<filename>tests/random.c
/*
* Original Source code copied from: http://xoshiro.di.unimi.it/hwd.php
*
* Copyright (C) 2004-2016 <NAME>.
* Copyright (C) 2017-2018 <NAME> and <NAME>.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
// I edited the original code only slightly, the original copyright still holds.
#define FIO_RAND
#define FIO_CLI
#include "fio-stl.h"
#define HWD_BITS 64
static uint64_t (*next)(void) = fio_rand64;
static uint64_t sys_next(void) {
uint64_t r = ((uint64_t)rand() >> 8) | ((uint64_t)rand() << 40);
r ^= (uint64_t)rand() << 20;
return r;
}
#include <assert.h>
#include <fcntl.h>
#include <float.h>
#include <inttypes.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#ifdef HWD_MMAP
#include <sys/mman.h>
#endif
/*
HWD 1.1 (2018-05-24)
This code implements the Hamming-weight dependency test based on z9
from gjrand 4.2.1.0 and described in detail in
<NAME> and <NAME>, "Scrambled linear pseudorandom number
generators", 2018.
Please refer to the paper for details about the test.
To compile, you must define:
- HWD_BITS is set to 64 in this implementation.
- HWD_BITS, which is the number of bits output by the PRNG, and it is by
default HWD_BITS. Presently legal combinations are 32/32, 32/64,
64/64 and 128/64.
- Optionally HWD_DIM, which defines the length of the signatures examined
(parameter k in the paper). Valid values are between 1 and 19;
the default value is 8.
- Optionally, HWD_NOPOPCOUNT, if your compiler does not support gcc's
builtins.
- Optionally, HWD_NUMCATS, if you want to override the default number
of categories. Valid values are between 1 and HWD_DIM; the default value
is HWD_DIM/2 + 1.
- Optionally, HWD_MMAP if you want to allocate memory in huge pages using
mmap().
You must insert the code for your PRNG, providing a suitable next()
method (returning a uint32_t or a uint64_t, depending on HWD_BITS)
at the HERE comment below. You may additionally initialize his state in
the main() if necessary.
*/
#ifndef HWD_DIM
// This must be at most 19
#define DIM (8)
#else
#define DIM (HWD_DIM)
#endif
#ifndef HWD_NUMCATS
// This must be at most DIM
#define NUMCATS (DIM / 2 + 1)
#else
#define NUMCATS (HWD_NUMCATS)
#endif
// Number of bits used for the sum in cs[] (small counters/sums).
#define SUM_BITS (19)
// Compile-time computation of 3^DIM
#define SIZE \
((DIM >= 1 ? UINT64_C(3) : UINT64_C(1)) * (DIM >= 2 ? 3 : 1) * \
(DIM >= 3 ? 3 : 1) * (DIM >= 4 ? 3 : 1) * (DIM >= 5 ? 3 : 1) * \
(DIM >= 6 ? 3 : 1) * (DIM >= 7 ? 3 : 1) * (DIM >= 8 ? 3 : 1) * \
(DIM >= 9 ? 3 : 1) * (DIM >= 10 ? 3 : 1) * (DIM >= 11 ? 3 : 1) * \
(DIM >= 12 ? 3 : 1) * (DIM >= 13 ? 3 : 1) * (DIM >= 14 ? 3 : 1) * \
(DIM >= 15 ? 3 : 1) * (DIM >= 16 ? 3 : 1) * (DIM >= 17 ? 3 : 1) * \
(DIM >= 18 ? 3 : 1) * (DIM >= 19 ? 3 : 1))
// Fast division by 3; works up to DIM = 19.
#define DIV3(x) ((x)*UINT64_C(1431655766) >> 32)
// batch_size values MUST be even. P is the probability of a 1 trit.
#define P (0.46769122397215788544)
const int64_t batch_size[] = {-1,
UINT64_C(14744),
UINT64_C(28320),
UINT64_C(56616),
UINT64_C(116264),
UINT64_C(242784),
UINT64_C(512040),
UINT64_C(1086096),
UINT64_C(2311072),
UINT64_C(4926224),
UINT64_C(10510376),
UINT64_C(22435504),
UINT64_C(47903280),
UINT64_C(102294608),
UINT64_C(218459240),
UINT64_C(466556056),
UINT64_C(996427288),
UINT64_C(2128099936),
UINT64_C(4545075936),
UINT64_C(9707156552)};
#ifdef HWD_NO_POPCOUNT
static inline int popcount64(uint64_t x) {
x = x - ((x >> 1) & 0x5555555555555555);
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);
x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f;
x = x + (x >> 8);
x = x + (x >> 16);
x = x + (x >> 32);
return x & 0x7f;
}
#else
#define popcount64(x) __builtin_popcountll(x)
#endif
/* Probability that the smallest of n numbers in [0..1) is <= x . */
static double pco_scale(double x, double n) {
if (x >= 1.0 || x <= 0.0)
return x;
/* This is the result we want: return 1.0 - pow(1.0 - x, n); except the
important cases are with x very small so this method gives better
accuracy. */
return -expm1(log1p(-x) * n);
}
/* The idea of the test is based around Hamming weights. We calculate the
average number of bits per BITS-bit word and how it depends on the
weights of the previous DIM words. There are SIZE different categories
for the previous words. For each one accumulate number of samples
(get_count(cs[j]) and count_sum[j].c) and number of bits per sample
(get_sum(cs[j]) and count_sum[j].s) .
To increase cache hits, we pack a 13-bit unsigned counter (upper bits)
and a and a 19-bit unsigned sum of Hamming weights (lower bits) into a
uint32_t. It would make sense to use bitfields, but in this way
update_cs() can update both fields with a single sum. */
static inline int get_count(uint32_t cs) { return cs >> SUM_BITS; }
static inline int get_sum(uint32_t cs) { return cs & ((1 << SUM_BITS) - 1); }
/* We add bc to the sum field of *p then add 1 to the count field. */
static inline void update_cs(int bc, uint32_t *p) {
*p += bc + (1 << SUM_BITS);
}
#ifdef HWD_MMAP
// "Small" counters/sums
static uint32_t *cs;
// "Large" counters/sums
static struct {
uint64_t c;
int64_t s;
} * count_sum;
#else
// "Small" counters/sums
static uint32_t cs[SIZE];
// "Large" counters/sums
static struct {
uint64_t c;
int64_t s;
} count_sum[SIZE];
#endif
/* Copy accumulated numbers out of cs[] into count_sum, then zero the ones
in cs[]. Note it is impossible for totals to overflow unless counts do. */
static void desat(const int64_t next_batch_size) {
int64_t c = 0;
for (uint64_t i = 0; i < SIZE; i++) {
const int32_t st = cs[i];
const int count = get_count(st);
c += count;
count_sum[i].c += count;
/* In cs[] the total Hamming weight is stored as actual weight. In
count_sum, it is stored as difference from expected average
Hamming weight, hence (BITS/2) * ct */
count_sum[i].s += get_sum(st) - (HWD_BITS / 2) * count;
cs[i] = 0;
}
if (c != next_batch_size) {
fprintf(stderr, "Counters overflowed. Seriously non-random.\n");
printf("p = %.3g\n", 1e-100);
exit(0);
}
}
/* sig is the last signature from the previous call. At each step it
contains an index into cs[], derived from the Hamming weights of the
previous DIM numbers. Considered as a base 3 number, the most
significant digit is the most recent trit. n is the batch size. */
static inline uint32_t scan_batch(uint32_t sig, int64_t n, uint64_t *ts) {
uint64_t t = ts ? *ts : 0;
int bc;
for (int64_t i = 0; i < n; i++) {
const uint64_t w = next();
if (ts) {
bc = popcount64(w ^ w << 1 ^ t);
t = w >> 63;
} else
bc = popcount64(w);
update_cs(bc, cs + sig);
sig = DIV3(sig) + ((bc >= 30) + (bc >= 35)) * (SIZE / 3);
}
if (ts)
*ts = t;
/* return the current signature so it can be passed back in on the next batch
*/
return sig;
}
/* Now we're out of the the accumulate phase, which is the inside loop.
Next is analysis. */
/* Mostly a debugging printf, though it can tell you a bit about the
structure of a prng when it fails. Print sig out in base 3, least
significant digits first. This means the most recent trit is the
rightmost. */
static void print_sig(uint32_t sig) {
for (uint64_t i = DIM; i > 0; i--) {
putchar(sig % 3 + '0');
sig /= 3;
}
}
#ifndef M_SQRT1_2
/* 1.0/sqrt(2.0) */
#define M_SQRT1_2 0.70710678118654752438
#endif
/* 1.0/sqrt(3.0) */
#define CORRECT3 0.57735026918962576451
/* 1.0/sqrt(6.0) */
#define CORRECT6 0.40824829046386301636
/* This is a transform similar in spirit to the Walsh-Hadamard transform
(see the paper). It's ortho-normal. So with independent normal
distribution mean 0 standard deviation 1 in, we get independent normal
distribution mean 0 standard deviation 1 out, except maybe for element 0.
And of course, for certain kinds of bad prngs when the null hypthosis is
false, some of these numbers will get extreme. */
static void mix3(double *ct, int sig) {
double *p1 = ct + sig, *p2 = p1 + sig;
double a, b, c;
for (int i = 0; i < sig; i++) {
a = ct[i];
b = p1[i];
c = p2[i];
ct[i] = (a + b + c) * CORRECT3;
p1[i] = (a - c) * M_SQRT1_2;
p2[i] = (2 * b - a - c) * CORRECT6;
}
sig = DIV3(sig);
if (sig) {
mix3(ct, sig);
mix3(p1, sig);
mix3(p2, sig);
}
}
/* categorise sig based on nonzero ternary digits. */
static int cat(uint32_t sig) {
int r = 0;
while (sig) {
r += (sig % 3) != 0;
sig /= 3;
}
return (r >= NUMCATS ? NUMCATS : r) - 1;
}
/* Apply the transform; then, compute, log and return the resulting p-value. */
#ifdef HWD_MMAP
static double *norm;
#else
static double norm[SIZE]; // This might be large
#endif
static double compute_pvalue(const bool trans) {
const double db = HWD_BITS * 0.25;
for (uint64_t i = 0; i < SIZE; i++) {
/* copy the bit count totals from count_sum[i].s to norm[i] with
normalisation. We expect mean 0 standard deviation 1 db is the
expected variance for Hamming weight of BITS-bit words.
count_sum[i].c is number of samples */
if (count_sum[i].c == 0)
norm[i] = 0.0;
else
norm[i] = count_sum[i].s / sqrt(count_sum[i].c * db);
}
/* The transform. The wonderful transform. After this we expect still
normalised to mean 0 stdev 1 under the null hypothesis. (But not for
element 0 which we will ignore.) */
mix3(norm, SIZE / 3);
double overall_pvalue = DBL_MAX;
/* To make the test more sensitive (see the paper) we split the
elements of norm into NUMCAT categories. These are based only on the
index into norm, not the content. We go though norm[], decide which
category each one is in, and record the signature (sig[]) and the
absolute value (sigma[]) For the most extreme value in each
category. Also a count (cat_count[]) of how many were in each
category. */
double sigma[NUMCATS];
uint32_t sig[NUMCATS], cat_count[NUMCATS] = {0};
for (int i = 0; i < NUMCATS; i++)
sigma[i] = DBL_MIN;
for (uint64_t i = 1; i < SIZE; i++) {
const int c = cat(i);
cat_count[c]++;
const double x = fabs(norm[i]);
if (x > sigma[c]) {
sig[c] = i;
sigma[c] = x;
}
}
/* For each category, calculate a p-value, put the lowest into
overall_pvalue, and print something out. */
for (int i = 0; i < NUMCATS; i++) {
printf("mix3 extreme = %.5f (sig = ", sigma[i]);
print_sig(sig[i]);
/* convert absolute value of approximate normal into p-value. */
double pvalue = erfc(M_SQRT1_2 * sigma[i]);
/* Ok, that's the lowest p-value cherry picked out of a choice of
cat_count[i] of them. Must correct for that. */
pvalue = pco_scale(pvalue, cat_count[i]);
printf(") weight %s%d (%" PRIu32 "), p-value = %.3g\n",
i == NUMCATS - 1 ? ">=" : "",
i + 1,
cat_count[i],
pvalue);
if (pvalue < overall_pvalue)
overall_pvalue = pvalue;
}
printf("bits per word = %d (analyzing %s); min category p-value = %.3g\n\n",
HWD_BITS,
trans ? "transitions" : "bits",
overall_pvalue);
/* again, we're cherry picking worst of NUMCATS, so correct it again. */
return pco_scale(overall_pvalue, NUMCATS);
}
static time_t tstart;
static double low_pvalue = DBL_MIN;
/* This is the call made when we want to print some analysis. This will be
done multiple times if --progress is used. */
static void analyze(int64_t pos, bool trans, bool final) {
if (pos < 2 * pow(2.0 / (1.0 - P), DIM))
printf("WARNING: p-values are unreliable, you have to wait (insufficient "
"data for meaningful answer)\n");
const double pvalue = compute_pvalue(trans);
const time_t tm = time(0);
printf("processed %.3g bytes in %.3g seconds (%.4g GB/s, %.4g TB/h). %s\n",
(double)pos,
(double)(tm - tstart),
pos * 1E-9 / (double)(tm - tstart),
pos * (3600 * 1E-12) / (double)(tm - tstart),
ctime(&tm));
if (final)
printf("final\n");
printf("p = %.3g\n", pvalue);
if (pvalue < low_pvalue)
exit(0);
if (!final)
printf("------\n\n");
}
static int64_t progsize[] = {100000000,
125000000,
150000000,
175000000,
200000000,
250000000,
300000000,
400000000,
500000000,
600000000,
700000000,
850000000,
0};
/* We use the all-one signature (the most probable) as initial signature. */
static int64_t pos;
static uint32_t last_sig = (SIZE - 1) / 2;
static uint64_t ts;
static int64_t next_progr = 100000000; // progsize[0]
static int progr_index;
static void run_test(const int64_t n, const bool trans, const bool progress) {
uint64_t *const p = trans ? &ts : NULL;
while (n < 0 || pos < n) {
int64_t next_batch_size = batch_size[DIM];
if (n >= 0 && (n - pos) / (HWD_BITS / 8) < next_batch_size)
next_batch_size = (n - pos) / (HWD_BITS / 8) & ~UINT64_C(7);
if (next_batch_size == 0)
break;
last_sig = scan_batch(last_sig, next_batch_size, p);
desat(next_batch_size);
pos += next_batch_size * (HWD_BITS / 8);
if (progress && pos >= next_progr) {
analyze(pos, trans, false);
progsize[progr_index++] *= 10;
next_progr = progsize[progr_index];
if (next_progr == 0) {
progr_index = 0;
next_progr = progsize[0];
}
}
}
analyze(pos, trans, true);
}
int main(int argc, const char **argv) {
int64_t n = -1;
bool trans = false, progress = false;
fio_cli_start(
argc,
argv,
0,
1,
"implements the Hamming-weight dependency test based on z9 from gjrand "
"4.2.1.0 and described by <NAME> and <NAME>.\n"
"Runs the test, by default, on the facil.io random function.",
FIO_CLI_BOOL("--system -s tests a patched `rand` instead of facil.io's "
"`fio_rand64`."),
FIO_CLI_BOOL("--progress -p uses progressive test sizes (true unless N "
"is provided)."),
FIO_CLI_BOOL("--trans -t tests transitions (vs. bits)."),
FIO_CLI_STRING("--low-pv a float indicating the test's low P value."),
FIO_CLI_INT("--N -n the tests iteration size limit."));
if (fio_cli_get_bool("-p"))
progress = true;
if (fio_cli_get_bool("-t"))
trans = true;
if (fio_cli_get_i("-n"))
n = fio_cli_get_i("-n");
if (fio_cli_get("--low-pv")) {
if (fio_cli_get("--low-pv") &&
sscanf(fio_cli_get("--low-pv"), "%lf", &low_pvalue) != 1)
fprintf(stderr, "Optional --low-pv must be a float.\n");
exit(1);
}
if (fio_cli_get_bool("-s")) {
fprintf(
stderr,
"Testing a fixed variation of system's `rand` instead of facil.io.\n");
sys_next();
next = sys_next;
}
fio_cli_end();
#ifdef HWD_MMAP
fprintf(stderr, "Allocating memory via mmap()... ");
// (SIZE + 1) is necessary for a correct memory alignment.
cs = mmap((void *)(0x0UL),
(SIZE + 1) * sizeof *cs + SIZE * sizeof *norm +
SIZE * sizeof *count_sum,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | (30 << MAP_HUGE_SHIFT),
0,
0);
if (cs == MAP_FAILED) {
fprintf(stderr, "Failed.\n");
exit(1);
}
fprintf(stderr, "OK.\n");
norm = (void *)(cs + SIZE + 1);
count_sum = (void *)(norm + SIZE);
#endif
tstart = time(0);
// for (int i = 1; i < argc; i++) {
// double dn;
// if (strcmp(argv[i], "--progress") == 0)
// progress = true;
// else if (strcmp(argv[i], "-t") == 0)
// trans = true;
// else if (sscanf(argv[i], "%lf", &dn) == 1)
// n = (int64_t)dn;
// else if (sscanf(argv[i], "--low-pv=%lf", &low_pvalue) == 1) {
// } else {
// fprintf(stderr,
// "Optional arg must be --progress or -t or "
// "--low-pv=number or numeric\n");
// exit(1);
// }
// }
if (n <= 0)
progress = true;
run_test(n, trans, progress);
exit(0);
}
|
janbiedermann/cstl
|
stl_slices/005 sha1.h
|
<gh_stars>10-100
/* *****************************************************************************
Copyright: <NAME>, 2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#define FIO_BITWISE /* Development inclusion - ignore line */
#define FIO_SHA1 /* Development inclusion - ignore line */
#include "000 header.h" /* Development inclusion - ignore line */
#include "004 bitwise.h" /* Development inclusion - ignore line */
#include "100 mem.h" /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
SHA 1
***************************************************************************** */
#ifdef FIO_SHA1
/* *****************************************************************************
SHA 1
***************************************************************************** */
/** The data tyope containing the SHA1 digest (result). */
typedef union {
#ifdef __SIZEOF_INT128__
__uint128_t align__;
#else
uint64_t align__;
#endif
uint32_t v[5];
uint8_t digest[20];
} fio_sha1_s;
/**
* A simple, non streaming, implementation of the SHA1 hashing algorithm.
*
* Do NOT use - SHA1 is broken... but for some reason some protocols still
* require it's use (i.e., WebSockets), so it's here for your convenience.
*/
SFUNC fio_sha1_s fio_sha1(const void *data, uint64_t len);
/** returns the digest length of SHA1 in bytes */
FIO_IFUNC size_t fio_sha1_len(void);
/** returns the digest of a SHA1 object. */
FIO_IFUNC uint8_t *fio_sha1_digest(fio_sha1_s *s);
/* *****************************************************************************
SHA 1 Implementation - inlined static functions
***************************************************************************** */
/** returns the digest length of SHA1 in bytes */
FIO_IFUNC size_t fio_sha1_len(void) { return 20; }
/** returns the digest of a SHA1 object. */
FIO_IFUNC uint8_t *fio_sha1_digest(fio_sha1_s *s) { return s->digest; }
/* *****************************************************************************
Implementation - possibly externed functions.
***************************************************************************** */
#ifdef FIO_EXTERN_COMPLETE
FIO_IFUNC void fio___sha1_round512(fio_sha1_s *old, /* state */
uint32_t *w /* 16 words */) {
register uint32_t v0 = old->v[0];
register uint32_t v1 = old->v[1];
register uint32_t v2 = old->v[2];
register uint32_t v3 = old->v[3];
register uint32_t v4 = old->v[4];
register uint32_t v5;
#define FIO___SHA1_ROTATE(K, F, i) \
v5 = fio_lrot32(v0, 5) + v4 + F + (uint32_t)K + w[(i)&15]; \
v4 = v3; \
v3 = v2; \
v2 = fio_lrot32(v1, 30); \
v1 = v0; \
v0 = v5;
#define FIO___SHA1_CALC_WORD(i) \
fio_lrot32( \
(w[(i + 13) & 15] ^ w[(i + 8) & 15] ^ w[(i + 2) & 15] ^ w[(i)&15]), \
1);
#define FIO___SHA1_ROUND4(K, F, i) \
FIO___SHA1_ROUND((K), (F), i); \
FIO___SHA1_ROUND((K), (F), i + 1); \
FIO___SHA1_ROUND((K), (F), i + 2); \
FIO___SHA1_ROUND((K), (F), i + 3);
#define FIO___SHA1_ROUND16(K, F, i) \
FIO___SHA1_ROUND4((K), (F), i); \
FIO___SHA1_ROUND4((K), (F), i + 4); \
FIO___SHA1_ROUND4((K), (F), i + 8); \
FIO___SHA1_ROUND4((K), (F), i + 12);
#define FIO___SHA1_ROUND20(K, F, i) \
FIO___SHA1_ROUND16(K, F, i); \
FIO___SHA1_ROUND4((K), (F), i + 16);
#define FIO___SHA1_ROUND(K, F, i) \
w[i] = fio_ntol32(w[i]); \
FIO___SHA1_ROTATE(K, F, i);
FIO___SHA1_ROUND16(0x5A827999, ((v1 & v2) | ((~v1) & (v3))), 0);
#undef FIO___SHA1_ROUND
#define FIO___SHA1_ROUND(K, F, i) \
w[(i)&15] = FIO___SHA1_CALC_WORD(i); \
FIO___SHA1_ROTATE(K, F, i);
FIO___SHA1_ROUND4(0x5A827999, ((v1 & v2) | ((~v1) & (v3))), 16);
FIO___SHA1_ROUND20(0x6ED9EBA1, (v1 ^ v2 ^ v3), 20);
FIO___SHA1_ROUND20(0x8F1BBCDC, ((v1 & (v2 | v3)) | (v2 & v3)), 40);
FIO___SHA1_ROUND20(0xCA62C1D6, (v1 ^ v2 ^ v3), 60);
old->v[0] += v0;
old->v[1] += v1;
old->v[2] += v2;
old->v[3] += v3;
old->v[4] += v4;
#undef FIO___SHA1_ROTATE
#undef FIO___SHA1_CALC_WORD
#undef FIO___SHA1_ROUND
#undef FIO___SHA1_ROUND4
#undef FIO___SHA1_ROUND16
#undef FIO___SHA1_ROUND20
}
/**
* A simple, non streaming, implementation of the SHA1 hashing algorithm.
*
* Do NOT use - SHA1 is broken... but for some reason some protocols still
* require it's use (i.e., WebSockets), so it's here for your convinience.
*/
SFUNC fio_sha1_s fio_sha1(const void *data, uint64_t len) {
/* TODO: hash */
fio_sha1_s s = (fio_sha1_s){
.v =
{
0x67452301,
0xEFCDAB89,
0x98BADCFE,
0x10325476,
0xC3D2E1F0,
},
};
const uint8_t *buf = (const uint8_t *)data;
uint32_t vec[16];
for (size_t i = 63; i < len; i += 64) {
FIO_MEMCPY(vec, buf, 64);
fio___sha1_round512(&s, vec);
buf += 64;
}
memset(vec, 0, sizeof(vec));
if ((len & 63)) {
FIO_MEMCPY(vec, buf, (len & 63));
}
((uint8_t *)vec)[(len & 63)] = 0x80;
if ((len & 63) > 55) {
fio___sha1_round512(&s, vec);
memset(vec, 0, sizeof(vec));
}
fio_u2buf64((void *)(vec + 14), (len << 3));
fio___sha1_round512(&s, vec);
s.v[0] = fio_ntol32(s.v[0]);
s.v[1] = fio_ntol32(s.v[1]);
s.v[2] = fio_ntol32(s.v[2]);
s.v[3] = fio_ntol32(s.v[3]);
s.v[4] = fio_ntol32(s.v[4]);
return s;
}
/* *****************************************************************************
SHA1 Testing
***************************************************************************** */
#ifdef FIO_TEST_CSTL
FIO_SFUNC uintptr_t FIO_NAME_TEST(stl, __sha1_wrapper)(char *data, size_t len) {
fio_sha1_s h = fio_sha1((const void *)data, (uint64_t)len);
return *(uintptr_t *)h.digest;
}
#if HAVE_OPENSSL
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
FIO_SFUNC uintptr_t FIO_NAME_TEST(stl, __sha1_open_ssl_wrapper)(char *data,
size_t len) {
/* test based on code from BearSSL with credit to <NAME> */
uintptr_t result[6];
SHA_CTX o_sh1;
SHA1_Init(&o_sh1);
SHA1_Update(&o_sh1, data, len);
SHA1_Final((unsigned char *)result, &o_sh1);
return result[0];
}
#endif
FIO_SFUNC void FIO_NAME_TEST(stl, sha1)(void) {
fprintf(stderr, "* Testing SHA1\n");
struct {
const char *str;
const char *sha1;
} data[] = {
{
.str = "",
.sha1 = "\xda\x39\xa3\xee\x5e\x6b\x4b\x0d\x32\x55\xbf\xef\x95\x60\x18"
"\x90\xaf\xd8\x07\x09",
},
{
.str = "The quick brown fox jumps over the lazy dog",
.sha1 = "\x2f\xd4\xe1\xc6\x7a\x2d\x28\xfc\xed\x84\x9e\xe1\xbb\x76\xe7"
"\x39\x1b\x93\xeb\x12",
},
{
.str = "The quick brown fox jumps over the lazy cog",
.sha1 = "\xde\x9f\x2c\x7f\xd2\x5e\x1b\x3a\xfa\xd3\xe8\x5a\x0b\xd1\x7d"
"\x9b\x10\x0d\xb4\xb3",
},
};
for (size_t i = 0; i < sizeof(data) / sizeof(data[0]); ++i) {
fio_sha1_s sha1 = fio_sha1(data[i].str, strlen(data[i].str));
FIO_ASSERT(!memcmp(sha1.digest, data[i].sha1, fio_sha1_len()),
"SHA1 mismatch for \"%s\"",
data[i].str);
}
#if !DEBUG
fio_test_hash_function(FIO_NAME_TEST(stl, __sha1_wrapper),
(char *)"fio_sha1",
5,
0,
0);
fio_test_hash_function(FIO_NAME_TEST(stl, __sha1_wrapper),
(char *)"fio_sha1",
13,
0,
1);
#if HAVE_OPENSSL
fio_test_hash_function(FIO_NAME_TEST(stl, __sha1_open_ssl_wrapper),
(char *)"OpenSSL SHA1",
5,
0,
0);
fio_test_hash_function(FIO_NAME_TEST(stl, __sha1_open_ssl_wrapper),
(char *)"OpenSSL SHA1",
13,
0,
1);
#endif /* HAVE_OPENSSL */
#endif /* !DEBUG */
}
#endif /* FIO_TEST_CSTL */
/* *****************************************************************************
Module Cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE */
#endif /* FIO_SHA1 */
#undef FIO_SHA1
|
janbiedermann/cstl
|
stl_slices/105 stream.h
|
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#define FIO_STREAM /* Development inclusion - ignore line */
#include "000 header.h" /* Development inclusion - ignore line */
#include "100 mem.h" /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
A packet based data stream for storing / buffering endless data.
***************************************************************************** */
#if defined(FIO_STREAM) && !defined(H___FIO_STREAM___H)
#define H___FIO_STREAM___H
#if !FIO_HAVE_UNIX_TOOLS
#if _MSC_VER
#pragma message( \
"POSIX is required for the fio_stream API, or issues may occure.")
#else
#warning "POSIX behavior is expected by the fio_stream API."
#endif
#endif
#include <sys/stat.h>
#ifndef FIO_STREAM_COPY_PER_PACKET
/** Break apart large memory blocks into smaller pieces. by default 96Kb */
#define FIO_STREAM_COPY_PER_PACKET 98304
#endif
/* *****************************************************************************
Stream API - types, constructor / destructor
***************************************************************************** */
typedef struct fio_stream_packet_s fio_stream_packet_s;
typedef struct {
/* do not directly acecss! */
fio_stream_packet_s *next;
fio_stream_packet_s **pos;
uint32_t consumed;
uint32_t packets;
} fio_stream_s;
/* at this point publish (declare only) the public API */
#ifndef FIO_STREAM_INIT
/* Initialization macro. */
#define FIO_STREAM_INIT(s) \
{ .next = NULL, .pos = &(s).next }
#endif
/* do we have a constructor? */
#ifndef FIO_REF_CONSTRUCTOR_ONLY
/* Allocates a new object on the heap and initializes it's memory. */
FIO_IFUNC fio_stream_s *fio_stream_new(void);
/* Frees any internal data AND the object's container! */
FIO_IFUNC int fio_stream_free(fio_stream_s *stream);
#endif /* FIO_REF_CONSTRUCTOR_ONLY */
/** Destroys the object, reinitializing its container. */
SFUNC void fio_stream_destroy(fio_stream_s *stream);
/* *****************************************************************************
Stream API - packing data into packets and adding it to the stream
***************************************************************************** */
/** Packs data into a fio_stream_packet_s container. */
SFUNC fio_stream_packet_s *fio_stream_pack_data(void *buf,
size_t len,
size_t offset,
uint8_t copy_buffer,
void (*dealloc_func)(void *));
/** Packs a file descriptor into a fio_stream_packet_s container. */
SFUNC fio_stream_packet_s *fio_stream_pack_fd(int fd,
size_t len,
size_t offset,
uint8_t keep_open);
/** Adds a packet to the stream. This isn't thread safe.*/
SFUNC void fio_stream_add(fio_stream_s *stream, fio_stream_packet_s *packet);
/** Destroys the fio_stream_packet_s - call this ONLY if unused. */
SFUNC void fio_stream_pack_free(fio_stream_packet_s *packet);
/* *****************************************************************************
Stream API - Consuming the stream
***************************************************************************** */
/**
* Reads data from the stream (if any), leaving it in the stream.
*
* `buf` MUST point to a buffer with - at least - `len` bytes. This is required
* in case the packed data is fragmented or references a file and needs to be
* copied to an available buffer.
*
* On error, or if the stream is empty, `buf` will be set to NULL and `len` will
* be set to zero.
*
* Otherwise, `buf` may retain the same value or it may point directly to a
* memory address wiithin the stream's buffer (the original value may be lost)
* and `len` will be updated to the largest possible value for valid data that
* can be read from `buf`.
*
* Note: this isn't thread safe.
*/
SFUNC void fio_stream_read(fio_stream_s *stream, char **buf, size_t *len);
/**
* Advances the Stream, so the first `len` bytes are marked as consumed.
*
* Note: this isn't thread safe.
*/
SFUNC void fio_stream_advance(fio_stream_s *stream, size_t len);
/**
* Returns true if there's any data in the stream.
*
* Note: this isn't truely thread safe.
*/
FIO_IFUNC uint8_t fio_stream_any(fio_stream_s *stream);
/**
* Returns the number of packets waiting in the stream.
*
* Note: this isn't truely thread safe.
*/
FIO_IFUNC uint32_t fio_stream_packets(fio_stream_s *stream);
/* *****************************************************************************
Stream Implementation
***************************************************************************** */
/* *****************************************************************************
Stream Implementation - inlined static functions
***************************************************************************** */
/* do we have a constructor? */
#ifndef FIO_REF_CONSTRUCTOR_ONLY
/* Allocates a new object on the heap and initializes it's memory. */
FIO_IFUNC fio_stream_s *fio_stream_new(void) {
fio_stream_s *s = (fio_stream_s *)FIO_MEM_REALLOC_(NULL, 0, sizeof(*s), 0);
if (s) {
*s = (fio_stream_s)FIO_STREAM_INIT(s[0]);
}
return s;
}
/* Frees any internal data AND the object's container! */
FIO_IFUNC int fio_stream_free(fio_stream_s *s) {
fio_stream_destroy(s);
FIO_MEM_FREE_(s, sizeof(*s));
return 0;
}
#endif /* FIO_REF_CONSTRUCTOR_ONLY */
/**
* Returns true if there's any data iin the stream.
*
* Note: this isn't thread safe.
*/
FIO_IFUNC uint8_t fio_stream_any(fio_stream_s *s) { return s && !!s->next; }
/**
* Returns the number of packets waiting in the stream.
*
* Note: this isn't truely thread safe.
*/
FIO_IFUNC uint32_t fio_stream_packets(fio_stream_s *s) { return s->packets; }
/* *****************************************************************************
Stream Implementation - possibly externed functions.
***************************************************************************** */
#ifdef FIO_EXTERN_COMPLETE
FIO_IFUNC void fio_stream_packet_free_all(fio_stream_packet_s *p);
/* Frees any internal data AND the object's container! */
SFUNC void fio_stream_destroy(fio_stream_s *s) {
if (!s)
return;
fio_stream_packet_free_all(s->next);
*s = (fio_stream_s)FIO_STREAM_INIT(s[0]);
return;
}
/* *****************************************************************************
Stream API - packing data into packets and adding it to the stream
***************************************************************************** */
struct fio_stream_packet_s {
fio_stream_packet_s *next;
};
typedef enum {
FIO_PACKET_TYPE_EMBEDDED = 0,
FIO_PACKET_TYPE_EXTERNAL = 1,
FIO_PACKET_TYPE_FILE = 2,
FIO_PACKET_TYPE_FILE_NO_CLOSE = 3,
} fio_stream_packet_type_e;
typedef struct fio_stream_packet_embd_s {
uint32_t type;
char buf[];
} fio_stream_packet_embd_s;
#define FIO_STREAM___EMBD_BIT_OFFSET 4
typedef struct fio_stream_packet_extrn_s {
uint32_t type;
uint32_t length;
char *buf;
uintptr_t offset;
void (*dealloc)(void *buf);
} fio_stream_packet_extrn_s;
/** User-space socket buffer data */
typedef struct {
uint32_t type;
uint32_t length;
int32_t offset;
int fd;
} fio_stream_packet_fd_s;
FIO_SFUNC void fio_stream_packet_free(fio_stream_packet_s *p) {
if (!p)
return;
union {
fio_stream_packet_embd_s *em;
fio_stream_packet_extrn_s *ext;
fio_stream_packet_fd_s *f;
} const u = {.em = (fio_stream_packet_embd_s *)(p + 1)};
switch ((fio_stream_packet_type_e)(u.em->type & 3)) {
case FIO_PACKET_TYPE_EMBEDDED:
FIO_MEM_FREE_(
p,
sizeof(*p) + sizeof(*u.em) +
(sizeof(char) * (u.em->type >> FIO_STREAM___EMBD_BIT_OFFSET)));
break;
case FIO_PACKET_TYPE_EXTERNAL:
if (u.ext->dealloc)
u.ext->dealloc(u.ext->buf);
FIO_MEM_FREE_(p, sizeof(*p) + sizeof(*u.ext));
break;
case FIO_PACKET_TYPE_FILE:
close(u.f->fd);
/* fallthrough */
case FIO_PACKET_TYPE_FILE_NO_CLOSE:
FIO_MEM_FREE_(p, sizeof(*p) + sizeof(*u.f));
break;
}
}
FIO_IFUNC void fio_stream_packet_free_all(fio_stream_packet_s *p) {
while (p) {
register fio_stream_packet_s *t = p;
p = p->next;
fio_stream_packet_free(t);
}
}
/** Packs data into a fio_stream_packet_s container. */
SFUNC fio_stream_packet_s *fio_stream_pack_data(void *buf,
size_t len,
size_t offset,
uint8_t copy_buffer,
void (*dealloc_func)(void *)) {
fio_stream_packet_s *p = NULL;
if (!len || !buf || (len & ((~(0UL)) << (32 - FIO_STREAM___EMBD_BIT_OFFSET))))
goto error;
if (copy_buffer || len <= 14) {
while (len) {
/* break apart large memory blocks into smaller pieces */
const size_t slice =
(len > FIO_STREAM_COPY_PER_PACKET) ? FIO_STREAM_COPY_PER_PACKET : len;
fio_stream_packet_embd_s *em;
fio_stream_packet_s *tmp = (fio_stream_packet_s *)FIO_MEM_REALLOC_(
NULL,
0,
sizeof(*p) + sizeof(*em) + (sizeof(char) * slice),
0);
if (!tmp)
goto error;
tmp->next = p;
em = (fio_stream_packet_embd_s *)(tmp + 1);
em->type = (uint32_t)FIO_PACKET_TYPE_EMBEDDED |
(uint32_t)(slice << FIO_STREAM___EMBD_BIT_OFFSET);
FIO_MEMCPY(em->buf, (char *)buf + offset + (len - slice), slice);
p = tmp;
len -= slice;
}
if (dealloc_func)
dealloc_func(buf);
} else {
fio_stream_packet_extrn_s *ext;
p = (fio_stream_packet_s *)
FIO_MEM_REALLOC_(NULL, 0, sizeof(*p) + sizeof(*ext), 0);
if (!p)
goto error;
p->next = NULL;
ext = (fio_stream_packet_extrn_s *)(p + 1);
*ext = (fio_stream_packet_extrn_s){
.type = FIO_PACKET_TYPE_EXTERNAL,
.length = (uint32_t)len,
.buf = (char *)buf,
.offset = offset,
.dealloc = dealloc_func,
};
}
return p;
error:
if (dealloc_func)
dealloc_func(buf);
fio_stream_packet_free_all(p);
return p;
}
/** Packs a file descriptor into a fio_stream_packet_s container. */
SFUNC fio_stream_packet_s *fio_stream_pack_fd(int fd,
size_t len,
size_t offset,
uint8_t keep_open) {
fio_stream_packet_s *p = NULL;
fio_stream_packet_fd_s *f;
if (fd < 0)
goto no_file;
if (!len) {
/* review file total length and auto-calculate */
struct stat st;
if (fstat(fd, &st))
goto error;
if (st.st_size <= 0 || offset >= (size_t)st.st_size ||
(uint64_t)st.st_size >= ((uint64_t)1UL << 32))
goto error;
len = (size_t)st.st_size - offset;
}
p = (fio_stream_packet_s *)
FIO_MEM_REALLOC_(NULL, 0, sizeof(*p) + sizeof(*f), 0);
if (!p)
goto error;
p->next = NULL;
f = (fio_stream_packet_fd_s *)(p + 1);
*f = (fio_stream_packet_fd_s){
.type =
(keep_open ? FIO_PACKET_TYPE_FILE : FIO_PACKET_TYPE_FILE_NO_CLOSE),
.length = (uint32_t)len,
.offset = (int32_t)offset,
.fd = fd,
};
return p;
error:
if (!keep_open)
close(fd);
no_file:
return p;
}
/** Adds a packet to the stream. This isn't thread safe.*/
SFUNC void fio_stream_add(fio_stream_s *s, fio_stream_packet_s *p) {
fio_stream_packet_s *last = p;
uint32_t packets = 1;
if (!s || !p)
goto error;
while (last->next) {
last = last->next;
++packets;
}
if (!s->pos)
s->pos = &s->next;
*s->pos = p;
s->pos = &last->next;
s->packets += packets;
return;
error:
fio_stream_pack_free(p);
}
/** Destroys the fio_stream_packet_s - call this ONLY if unused. */
SFUNC void fio_stream_pack_free(fio_stream_packet_s *p) {
fio_stream_packet_free_all(p);
}
/* *****************************************************************************
Stream API - Consuming the stream
***************************************************************************** */
FIO_IFUNC size_t fio___stream_p2len(fio_stream_packet_s *p) {
size_t len = 0;
if (!p)
return len;
union {
fio_stream_packet_embd_s *em;
fio_stream_packet_extrn_s *ext;
fio_stream_packet_fd_s *f;
} const u = {.em = (fio_stream_packet_embd_s *)(p + 1)};
switch ((fio_stream_packet_type_e)(u.em->type & 3)) {
case FIO_PACKET_TYPE_EMBEDDED:
len = u.em->type >> FIO_STREAM___EMBD_BIT_OFFSET;
return len;
case FIO_PACKET_TYPE_EXTERNAL:
len = u.ext->length;
return len;
case FIO_PACKET_TYPE_FILE: /* fallthrough */
case FIO_PACKET_TYPE_FILE_NO_CLOSE:
len = u.f->length;
return len;
}
return len;
}
FIO_SFUNC void fio___stream_read_internal(fio_stream_packet_s *p,
char **buf,
size_t *len,
size_t buf_offset,
size_t offset,
size_t must_copy) {
if (!p || !len[0]) {
len[0] = 0;
return;
}
union {
fio_stream_packet_embd_s *em;
fio_stream_packet_extrn_s *ext;
fio_stream_packet_fd_s *f;
} const u = {.em = (fio_stream_packet_embd_s *)(p + 1)};
size_t written = 0;
switch ((fio_stream_packet_type_e)(u.em->type & 3)) {
case FIO_PACKET_TYPE_EMBEDDED:
if (!buf[0] || !len[0] ||
(!must_copy &&
(!p->next ||
(u.em->type >> FIO_STREAM___EMBD_BIT_OFFSET) >= len[0] + offset))) {
buf[0] = u.em->buf + offset;
len[0] = (size_t)(u.em->type >> FIO_STREAM___EMBD_BIT_OFFSET) - offset;
return;
}
written = (u.em->type >> FIO_STREAM___EMBD_BIT_OFFSET) - offset;
if (written > len[0])
written = len[0];
if (written) {
FIO_MEMCPY(buf[0] + buf_offset, u.em->buf + offset, written);
len[0] -= written;
}
if (len[0]) {
fio___stream_read_internal(p->next, buf, len, written + buf_offset, 0, 1);
}
len[0] += written;
return;
case FIO_PACKET_TYPE_EXTERNAL:
if (!buf[0] || !len[0] ||
(!must_copy && (!p->next || u.ext->length >= len[0] + offset))) {
buf[0] = u.ext->buf + u.ext->offset + offset;
len[0] = (size_t)(u.ext->length) - offset;
return;
}
written = u.ext->length - offset;
if (written > len[0])
written = len[0];
if (written) {
FIO_MEMCPY(buf[0] + buf_offset,
u.ext->buf + u.ext->offset + offset,
written);
len[0] -= written;
}
if (len[0]) {
fio___stream_read_internal(p->next, buf, len, written + buf_offset, 0, 1);
}
len[0] += written;
return;
break;
case FIO_PACKET_TYPE_FILE: /* fallthrough */
case FIO_PACKET_TYPE_FILE_NO_CLOSE:
if (!buf[0] || !len[0]) {
buf[0] = NULL;
len[0] = 0;
return;
}
{
uint8_t possible_eol_surprise = 0;
written = u.f->length - offset;
if (written > len[0])
written = len[0];
if (written) {
ssize_t act;
retry_on_signal:
act =
pread(u.f->fd, buf[0] + buf_offset, written, u.f->offset + offset);
if (act <= 0) {
/* no more data in the file? */
FIO_LOG_DEBUG("file read error for %d: %s", u.f->fd, strerror(errno));
if (errno == EINTR)
goto retry_on_signal;
u.f->length = offset;
} else if ((size_t)act != written) {
/* a surprising EOF? */
written = act;
possible_eol_surprise = 1;
}
len[0] -= written;
}
if (!possible_eol_surprise && len[0]) {
fio___stream_read_internal(p->next,
buf,
len,
written + buf_offset,
0,
1);
}
len[0] += written;
}
return;
}
}
/**
* Reads data from the stream (if any), leaving it in the stream.
*
* `buf` MUST point to a buffer with - at least - `len` bytes. This is required
* in case the packed data is fragmented or references a file and needs to be
* copied to an available buffer.
*
* On error, or if the stream is empty, `buf` will be set to NULL and `len` will
* be set to zero.
*
* Otherwise, `buf` may retain the same value or it may point directly to a
* memory address wiithin the stream's buffer (the original value may be lost)
* and `len` will be updated to the largest possible value for valid data that
* can be read from `buf`.
*
* Note: this isn't thread safe.
*/
SFUNC void fio_stream_read(fio_stream_s *s, char **buf, size_t *len) {
if (!s || !s->next)
goto none;
fio___stream_read_internal(s->next, buf, len, 0, s->consumed, 0);
return;
none:
*buf = NULL;
*len = 0;
}
/**
* Advances the Stream, so the first `len` bytes are marked as consumed.
*
* Note: this isn't thread safe.
*/
SFUNC void fio_stream_advance(fio_stream_s *s, size_t len) {
if (!s || !s->next)
return;
len += s->consumed;
while (len) {
size_t p_len = fio___stream_p2len(s->next);
if (len >= p_len) {
fio_stream_packet_s *p = s->next;
s->next = p->next;
--s->packets;
fio_stream_packet_free(p);
len -= p_len;
if (!s->next) {
s->pos = &s->next;
s->consumed = 0;
s->packets = 0;
return;
}
} else {
s->consumed = len;
return;
}
}
s->consumed = len;
}
/* *****************************************************************************
Stream Testing
***************************************************************************** */
#ifdef FIO_TEST_CSTL
FIO_SFUNC void FIO_NAME_TEST(stl, stream)(void) {
char *const str =
(char *)"My Hello World string should be long enough so it can be used "
"for testing the stream functionality in the facil.io stream "
"module. The stream moduule takes strings and failes and places "
"them (by reference / copy) into a linked list of objects. When "
"data is requested from the stream, the stream will either copy "
"the data to a pre-allocated buffer or it may update the link to "
"it points to its own internal buffer (avoiding a copy when "
"possible).";
fio_stream_s s = FIO_STREAM_INIT(s);
char mem[4000];
char *buf = mem;
size_t len = 4000;
fprintf(stderr, "* Testing fio_stream for streaming buffer storage.\n");
fio_stream_add(&s, fio_stream_pack_data(str, 11, 3, 1, NULL));
FIO_ASSERT(fio_stream_any(&s),
"stream is empty after `fio_stream_add` (data, copy)");
for (int i = 0; i < 3; ++i) {
/* test that read operrations are immutable */
buf = mem;
len = 4000;
fio_stream_read(&s, &buf, &len);
FIO_ASSERT(len == 11,
"fio_stream_read didn't read all data from stream? (%zu)",
len);
FIO_ASSERT(!memcmp(str + 3, buf, len),
"fio_stream_read data error? (%.*s)",
(int)len,
buf);
FIO_ASSERT_DEBUG(
buf != mem,
"fio_stream_read should have been performed with zero-copy");
}
fio_stream_advance(&s, len);
FIO_ASSERT(
!fio_stream_any(&s),
"after advance, at this point, the stream should have been consumed.");
buf = mem;
len = 4000;
fio_stream_read(&s, &buf, &len);
FIO_ASSERT(
!buf && !len,
"reading from an empty stream should set buf and len to NULL and zero.");
fio_stream_destroy(&s);
FIO_ASSERT(!fio_stream_any(&s), "destroyed stream should be empty.");
fio_stream_add(&s, fio_stream_pack_data(str, 11, 0, 1, NULL));
fio_stream_add(&s, fio_stream_pack_data(str, 49, 11, 0, NULL));
fio_stream_add(&s, fio_stream_pack_data(str, 20, 60, 0, NULL));
FIO_ASSERT(fio_stream_any(&s), "stream with data shouldn't be empty.");
FIO_ASSERT(fio_stream_packets(&s) == 3, "packet counut error.");
buf = mem;
len = 4000;
fio_stream_read(&s, &buf, &len);
FIO_ASSERT(len == 80,
"fio_stream_read didn't read all data from stream(2)? (%zu)",
len);
FIO_ASSERT(!memcmp(str, buf, len),
"fio_stream_read data error? (%.*s)",
(int)len,
buf);
buf = mem;
len = 8;
fio_stream_read(&s, &buf, &len);
FIO_ASSERT(len < 80,
"fio_stream_read didn't perform a partial read? (%zu)",
len);
FIO_ASSERT(!memcmp(str, buf, len),
"fio_stream_read partial read data error? (%.*s)",
(int)len,
buf);
fio_stream_advance(&s, 20);
FIO_ASSERT(fio_stream_packets(&s) == 2, "packet counut error (2).");
buf = mem;
len = 4000;
fio_stream_read(&s, &buf, &len);
FIO_ASSERT(len == 60,
"fio_stream_read didn't read all data from stream(3)? (%zu)",
len);
FIO_ASSERT(!memcmp(str + 20, buf, len),
"fio_stream_read data error? (%.*s)",
(int)len,
buf);
fio_stream_add(&s, fio_stream_pack_fd(open(__FILE__, O_RDONLY), 20, 0, 0));
FIO_ASSERT(fio_stream_packets(&s) == 3, "packet counut error (3).");
buf = mem;
len = 4000;
fio_stream_read(&s, &buf, &len);
FIO_ASSERT(len == 80,
"fio_stream_read didn't read all data from stream(4)? (%zu)",
len);
FIO_ASSERT(!memcmp("/* *****************", buf + 60, 20),
"fio_stream_read file read data error?\n%.*s",
(int)len,
buf);
buf = mem;
len = 4000;
fio_stream_read(&s, &buf, &len);
FIO_ASSERT(len == 80,
"fio_stream_read didn't (re)read all data from stream(5)? (%zu)",
len);
FIO_ASSERT(!memcmp("/* *****************", buf + 60, 20),
"fio_stream_read file (re)read data error? (%.*s)",
(int)len,
buf);
fio_stream_destroy(&s);
FIO_ASSERT(!fio_stream_any(&s), "destroyed stream should be empty.");
}
#endif /* FIO_TEST_CSTL */
/* *****************************************************************************
Module Cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE */
#undef FIO_STREAM___EMBD_BIT_OFFSET
#endif /* FIO_STREAM */
#undef FIO_STREAM
|
janbiedermann/cstl
|
tests/json_find.c
|
<filename>tests/json_find.c<gh_stars>10-100
#define FIO_LOG
#define FIO_CLI
#include "fio-stl.h" /* from: https://github.com/facil-io/cstl */
#define FIO_FIOBJ
#include "fio-stl.h" /* from: https://github.com/facil-io/cstl */
int main(int argc, char const *argv[]) {
// select the JSON file.
fio_cli_start(argc,
argv,
2,
2,
"NAME will extract a data field from a JSON file using "
"Javascript notation.\nUse:\n\tNAME <filename> <JSON_field>",
FIO_CLI_PRINT_LINE("Example:"),
FIO_CLI_PRINT("NAME users.json \\\"users[0].name\\\""));
// open and read the JSON fiile
FIOBJ json = fiobj_str_new();
FIO_LOG_DEBUG2("attempting open:%s", fio_cli_unnamed(0));
fio_str_info_s result = fiobj_str_readfile(json, fio_cli_unnamed(0), 0, 0);
FIO_ASSERT(result.buf, "Couldn't open file %s", fio_cli_unnamed(0));
// parse the JSON data
FIO_LOG_DEBUG2("attempting to parse:\n%s", fiobj_str2cstr(json).buf);
size_t consumed = 0;
FIOBJ data = fiobj_json_parse(fiobj_str2cstr(json), &consumed);
FIO_ASSERT(data != FIOBJ_INVALID, "couldn't parse data.");
fiobj_free(json); /* we don't need the JSON file content anymore. */
// re-format the JSON - example (replacing key-value pairs with arrays)
json = fiobj_json_find2(data,
(char *)fio_cli_unnamed(1),
strlen(fio_cli_unnamed(1)));
fiobj_dup(json);
fiobj_free(data); /* we don't need the original object structure */
data = fiobj2json(FIOBJ_INVALID, json, 1);
/* print out the final data in JSON format. */
printf("%s\n", fiobj_str2ptr(data));
/* cleanup. */
fiobj_free(data);
fiobj_free(json);
fio_cli_end();
return 0;
}
|
janbiedermann/cstl
|
stl_slices/211 ordered map.h
|
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#define FIO_MAP_NAME map /* Development inclusion - ignore line */
#include "004 bitwise.h" /* Development inclusion - ignore line */
#include "100 mem.h" /* Development inclusion - ignore line */
#include "210 map api.h" /* Development inclusion - ignore line */
#define FIO_MAP_TEST /* Development inclusion - ignore line */
#define FIO_MAP_V2 /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
Unordered Map - an Unordered Hash Map / Set
***************************************************************************** */
#if defined(FIO_MAP_NAME) && FIO_MAP_ORDERED
/* *****************************************************************************
Ordered Map Types - Implementation
***************************************************************************** */
/** An Ordered Map Type */
struct FIO_NAME(FIO_MAP_NAME, s) {
/** Internal map / memory - do not access directly */
FIO_NAME(FIO_MAP_NAME, each_s) * map;
/** Object count - do not access directly */
FIO_MAP_SIZE_TYPE count;
/** Writing position - do not access directly */
FIO_MAP_SIZE_TYPE w;
#if FIO_MAP_EVICT_LRU
/** LRU evicion monitoring - do not access directly */
FIO_MAP_SIZE_TYPE last_used;
#endif /* FIO_MAP_EVICT_LRU */
uint8_t bits;
uint8_t under_attack;
};
/* *****************************************************************************
Ordered Map Implementation - inlined static functions
***************************************************************************** */
#ifndef FIO_MAP_CAPA
#define FIO_MAP_CAPA(bits) (((uintptr_t)1ULL << (bits)) - 1)
#endif
/* do we have a constructor? */
#ifndef FIO_REF_CONSTRUCTOR_ONLY
/* Allocates a new object on the heap and initializes it's memory. */
FIO_IFUNC FIO_MAP_PTR FIO_NAME(FIO_MAP_NAME, new)(void) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_MEM_REALLOC_(NULL, 0, sizeof(*m), 0);
if (!m)
return (FIO_MAP_PTR)NULL;
*m = (FIO_NAME(FIO_MAP_NAME, s))FIO_MAP_INIT;
return (FIO_MAP_PTR)FIO_PTR_TAG(m);
}
/* Frees any internal data AND the object's container! */
FIO_IFUNC int FIO_NAME(FIO_MAP_NAME, free)(FIO_MAP_PTR map) {
FIO_PTR_TAG_VALID_OR_RETURN(map, 0);
FIO_NAME(FIO_MAP_NAME, destroy)(map);
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
FIO_MEM_FREE_(m, sizeof(*m));
return 0;
}
#endif /* FIO_REF_CONSTRUCTOR_ONLY */
FIO_IFUNC size_t FIO_NAME(FIO_MAP_NAME, count)(FIO_MAP_PTR map) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return 0;
FIO_PTR_TAG_VALID_OR_RETURN(map, 0);
return m->count;
}
FIO_IFUNC size_t FIO_NAME(FIO_MAP_NAME, capa)(FIO_MAP_PTR map) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return 0;
FIO_PTR_TAG_VALID_OR_RETURN(map, 0);
return FIO_MAP_CAPA(m->bits);
}
FIO_IFUNC FIO_NAME(FIO_MAP_NAME, each_s) *
FIO_NAME(FIO_MAP_NAME, each_next)(FIO_MAP_PTR map,
FIO_NAME(FIO_MAP_NAME, each_s) * *first,
FIO_NAME(FIO_MAP_NAME, each_s) * pos) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m || !first)
return NULL;
FIO_PTR_TAG_VALID_OR_RETURN(map, NULL);
if (!m->count || !m->map)
return NULL;
intptr_t i;
#if FIO_MAP_EVICT_LRU
FIO_MAP_SIZE_TYPE next;
if (!pos) {
i = m->last_used;
*first = m->map;
return m->map + i;
}
i = pos - *first;
*first = m->map; /* was it updated? */
next = m->map[i].node.next;
if (next == m->last_used)
return NULL;
return m->map + next;
#else /* FIO_MAP_EVICT_LRU */
if (!pos) {
i = -1;
} else {
i = (intptr_t)(pos - *first);
}
++i;
*first = m->map;
while ((uintptr_t)i < (uintptr_t)m->w) {
if (m->map[i].hash)
return m->map + i;
++i;
}
return NULL;
#endif /* FIO_MAP_EVICT_LRU */
}
/* *****************************************************************************
Ordered Map Implementation - possibly externed functions.
***************************************************************************** */
#ifdef FIO_EXTERN_COMPLETE
#ifndef FIO_MAP_MEMORY_SIZE
#define FIO_MAP_MEMORY_SIZE(bits) \
((sizeof(FIO_NAME(FIO_MAP_NAME, each_s)) + sizeof(FIO_MAP_SIZE_TYPE)) * \
FIO_MAP_CAPA(bits))
#endif
/* *****************************************************************************
Ordered Map Implementation - helper functions.
***************************************************************************** */
/** the value to be used when the hash is a reserved value. */
#define FIO_MAP_HASH_FIXED ((FIO_MAP_HASH)-2LL)
/** the value to be used when the hash is a reserved value. */
#define FIO_MAP_HASH_FIX(h) (!h ? FIO_MAP_HASH_FIXED : (h))
FIO_IFUNC FIO_MAP_SIZE_TYPE *FIO_NAME(FIO_MAP_NAME,
__imap)(FIO_NAME(FIO_MAP_NAME, s) * m) {
return (FIO_MAP_SIZE_TYPE *)(m->map + FIO_MAP_CAPA(m->bits));
}
FIO_IFUNC FIO_MAP_SIZE_TYPE FIO_NAME(FIO_MAP_NAME,
__hash2imap)(FIO_MAP_HASH hash,
uint8_t bits) {
FIO_MAP_SIZE_TYPE r = hash & ((~(FIO_MAP_SIZE_TYPE)0) << bits);
return r ? r
: (((~(FIO_MAP_SIZE_TYPE)0) << bits) << 1); /* must never be zero */
}
typedef struct {
/* index in the index map */
FIO_MAP_SIZE_TYPE i;
/* index in the data array */
FIO_MAP_SIZE_TYPE a;
} FIO_NAME(FIO_MAP_NAME, __pos_s);
/* locat an objects index in the index map and its array position */
FIO_SFUNC FIO_NAME(FIO_MAP_NAME, __pos_s)
FIO_NAME(FIO_MAP_NAME, __index)(FIO_NAME(FIO_MAP_NAME, s) * m,
const FIO_MAP_HASH hash,
FIO_MAP_OBJ_KEY key,
FIO_MAP_SIZE_TYPE set_hash) {
FIO_NAME(FIO_MAP_NAME, __pos_s)
i = {
.i = (FIO_MAP_SIZE_TYPE)-1LL,
.a = (FIO_MAP_SIZE_TYPE)-1LL,
};
size_t total_collisions = 0;
if (!m->map)
return i;
FIO_MAP_SIZE_TYPE *const imap = FIO_NAME(FIO_MAP_NAME, __imap)(m);
/* note: hash MUST be normalized by this point */
const FIO_MAP_SIZE_TYPE pos_mask = FIO_MAP_CAPA(m->bits);
const FIO_MAP_SIZE_TYPE hashed_mask =
((size_t)(m->bits + 1) < (size_t)(sizeof(FIO_MAP_SIZE_TYPE) * 8))
? ((~(FIO_MAP_SIZE_TYPE)0) << m->bits)
: 0;
const int max_attempts = (FIO_MAP_CAPA(m->bits)) >= FIO_MAP_MAX_SEEK
? (int)FIO_MAP_MAX_SEEK
: (FIO_MAP_CAPA(m->bits));
/* we perform X attempts using large cuckoo steps */
FIO_MAP_SIZE_TYPE pos = hash;
if (m->bits <= FIO_MAP_SEEK_AS_ARRAY_LOG_LIMIT)
goto seek_as_array;
for (int attempts = 0; attempts < max_attempts;
(++attempts), (pos += FIO_MAP_CUCKOO_STEPS)) {
const FIO_MAP_SIZE_TYPE desired_hash =
FIO_NAME(FIO_MAP_NAME, __hash2imap)(pos, m->bits);
/* each attempt tests a group of 5 slots with high cache locality */
for (int byte = 0, offset = 0; byte < 5; (++byte), (offset += byte)) {
const FIO_MAP_SIZE_TYPE index = (pos + offset) & pos_mask;
/* the last slot is reserved for marking deleted items, not allocated. */
if (index == pos_mask) {
continue;
}
/* return if there's an available slot (no need to look further) */
if (!imap[index]) {
i.i = index;
if (set_hash)
imap[index] = desired_hash;
return i;
}
/* test cache friendly partial match */
if ((imap[index] & hashed_mask) == desired_hash || !hashed_mask) {
/* test full hash */
FIO_MAP_SIZE_TYPE a_index = imap[index] & pos_mask;
if (a_index != pos_mask) {
if (m->map[a_index].hash == hash) {
/* test full collisions (attack) / match */
if (m->under_attack ||
FIO_MAP_OBJ_KEY_CMP(m->map[a_index].obj, key)) {
i.i = index;
i.a = a_index;
return i;
} else if (++total_collisions >= FIO_MAP_MAX_FULL_COLLISIONS) {
m->under_attack = 1;
FIO_LOG_SECURITY("Ordered map under attack?");
}
}
}
} else if (i.i == (FIO_MAP_SIZE_TYPE)-1LL &&
(imap[index] & pos_mask) == pos_mask) {
/* (recycling) mark first available slot in the group */
i.i = index;
set_hash *= desired_hash;
}
}
}
if (set_hash && i.i != (FIO_MAP_SIZE_TYPE)-1LL)
imap[i.i] = set_hash;
return i;
seek_as_array:
pos = 0;
if (m->w < FIO_MAP_CAPA(m->bits))
i.i = m->w;
while (pos < m->w) {
if (m->map[pos].hash == hash) {
/* test full collisions (attack) / match */
if (m->under_attack || FIO_MAP_OBJ_KEY_CMP(m->map[pos].obj, key)) {
i.i = pos;
i.a = pos;
return i;
} else if (++total_collisions >= FIO_MAP_MAX_FULL_COLLISIONS) {
m->under_attack = 1;
FIO_LOG_SECURITY("Ordered map under attack?");
}
} else if (!m->map[pos].hash && i.i > pos) {
i.i = pos;
}
++pos;
}
if (set_hash && i.i != (FIO_MAP_SIZE_TYPE)-1LL)
imap[i.i] = FIO_NAME(FIO_MAP_NAME, __hash2imap)(hash, m->bits);
return i;
(void)key; /* if unused */
}
FIO_IFUNC int FIO_NAME(FIO_MAP_NAME, __realloc)(FIO_NAME(FIO_MAP_NAME, s) * m,
size_t bits) {
if (!m || bits > (sizeof(FIO_MAP_SIZE_TYPE) * 8))
return -1;
// if (bits < 3)
// bits = 3;
if (bits != m->bits) {
FIO_NAME(FIO_MAP_NAME, each_s) *tmp =
(FIO_NAME(FIO_MAP_NAME, each_s) *)FIO_MEM_REALLOC_(
m->map,
FIO_MAP_MEMORY_SIZE(m->bits),
FIO_MAP_MEMORY_SIZE(bits),
(m->w * sizeof(*m->map)));
if (!tmp)
return -1;
m->map = tmp;
m->bits = (uint8_t)bits;
}
if (!FIO_MEM_REALLOC_IS_SAFE_ || bits == m->bits)
memset(FIO_NAME(FIO_MAP_NAME, __imap)(m),
0,
sizeof(FIO_MAP_SIZE_TYPE) * FIO_MAP_CAPA(bits));
/* rehash the map */
if (m->count) {
register FIO_MAP_SIZE_TYPE *const imap = FIO_NAME(FIO_MAP_NAME, __imap)(m);
/* scan map for used slots to re-insert data */
register const FIO_MAP_SIZE_TYPE end = m->w;
if (m->w == m->count) {
/* no holes, we can quickly run through the array and reindex */
FIO_MAP_SIZE_TYPE i = 0;
do {
if (m->map[i].hash) {
FIO_NAME(FIO_MAP_NAME, __pos_s)
pos = FIO_NAME(
FIO_MAP_NAME,
__index)(m, m->map[i].hash, FIO_MAP_OBJ2KEY(m->map[i].obj), 1);
if (pos.i == (FIO_MAP_SIZE_TYPE)-1LL)
goto error;
imap[pos.i] |= i;
}
i++;
} while (i < end);
} else {
/* the array has holes -o compact the array while reindexing */
FIO_MAP_SIZE_TYPE r = 0, w = 0;
do {
#if FIO_MAP_EVICT_LRU
if (w != r) {
FIO_MAP_SIZE_TYPE head = m->map[r].node.next;
m->map[w++] = m->map[r];
if (m->last_used == r)
m->last_used = w;
FIO_INDEXED_LIST_REMOVE(m->map, node, r);
FIO_INDEXED_LIST_PUSH(m->map, node, head, w);
}
#else
m->map[w++] = m->map[r];
#endif /* FIO_MAP_EVICT_LRU */
if (m->map[r].hash) {
FIO_NAME(FIO_MAP_NAME, __pos_s)
pos = FIO_NAME(
FIO_MAP_NAME,
__index)(m, m->map[r].hash, FIO_MAP_OBJ2KEY(m->map[r].obj), 1);
if (pos.i == (FIO_MAP_SIZE_TYPE)-1)
goto error;
imap[pos.i] |= r;
}
r++;
} while (r < end);
FIO_ASSERT_DEBUG(w == m->count, "rehashing logic error @ ordered map");
}
}
return 0;
error:
return -1;
}
FIO_IFUNC void FIO_NAME(FIO_MAP_NAME,
__destroy_all_objects)(FIO_NAME(FIO_MAP_NAME, s) * m) {
#if !FIO_MAP_TYPE_DESTROY_SIMPLE || !FIO_MAP_KEY_DESTROY_SIMPLE
for (FIO_MAP_SIZE_TYPE i = 0; i < m->w; ++i) {
if (!m->map[i].hash)
continue;
FIO_MAP_OBJ_DESTROY(m->map[i].obj);
#if DEBUG
--m->count;
#endif
}
FIO_ASSERT_DEBUG(!m->count, "logic error @ ordered map clear.");
#else
(void)m; /* no-op*/
#endif
}
/* *****************************************************************************
Unordered Map Implementation - API implementation
***************************************************************************** */
/* Frees any internal data AND the object's container! */
SFUNC void FIO_NAME(FIO_MAP_NAME, destroy)(FIO_MAP_PTR map) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return;
FIO_PTR_TAG_VALID_OR_RETURN_VOID(map);
/* add destruction logic */
FIO_NAME(FIO_MAP_NAME, __destroy_all_objects)(m);
FIO_MEM_FREE_(m->map, FIO_MAP_MEMORY_SIZE(m->bits));
*m = (FIO_NAME(FIO_MAP_NAME, s))FIO_MAP_INIT;
return;
}
/* *****************************************************************************
Get / Set / Remove
***************************************************************************** */
SFUNC FIO_MAP_TYPE *FIO_NAME(FIO_MAP_NAME, get_ptr)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
FIO_MAP_OBJ_KEY key) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return NULL;
FIO_PTR_TAG_VALID_OR_RETURN(map, NULL);
hash = FIO_MAP_HASH_FIX(hash);
FIO_NAME(FIO_MAP_NAME, __pos_s)
pos = FIO_NAME(FIO_MAP_NAME, __index)(m, hash, key, 0);
if (pos.a == (FIO_MAP_SIZE_TYPE)(-1) || !m->map[pos.a].hash)
return NULL;
#if FIO_MAP_EVICT_LRU
if (m->last_used != pos.a) {
FIO_INDEXED_LIST_REMOVE(m->map, node, pos.a);
FIO_INDEXED_LIST_PUSH(m->map, node, m->last_used, pos.a);
m->last_used = pos.a;
}
#endif /* FIO_MAP_EVICT_LRU */
return &FIO_MAP_OBJ2TYPE(m->map[pos.a].obj);
}
SFUNC FIO_MAP_TYPE *FIO_NAME(FIO_MAP_NAME, set_ptr)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
#ifdef FIO_MAP_KEY
FIO_MAP_KEY key,
#endif /* FIO_MAP_KEY */
FIO_MAP_TYPE obj,
FIO_MAP_TYPE *old,
uint8_t overwrite) {
if (old)
*old = FIO_MAP_TYPE_INVALID;
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return NULL;
FIO_PTR_TAG_VALID_OR_RETURN(map, NULL);
hash = FIO_MAP_HASH_FIX(hash);
/* make sure there's room in the value array */
if (m->w + 1 == FIO_MAP_CAPA(m->bits))
FIO_NAME(FIO_MAP_NAME, __realloc)(m, m->bits + (m->w == m->count));
#ifdef FIO_MAP_KEY
FIO_NAME(FIO_MAP_NAME, __pos_s)
pos = FIO_NAME(FIO_MAP_NAME, __index)(m, hash, key, 1);
#else
FIO_NAME(FIO_MAP_NAME, __pos_s)
pos = FIO_NAME(FIO_MAP_NAME, __index)(m, hash, obj, 1);
#endif /* FIO_MAP_KEY */
for (int i = 0; pos.i == (FIO_MAP_SIZE_TYPE)-1LL && i < 2; ++i) {
if (FIO_NAME(FIO_MAP_NAME, __realloc)(m, m->bits + 1))
continue;
#ifdef FIO_MAP_KEY
pos = FIO_NAME(FIO_MAP_NAME, __index)(m, hash, key, 1);
#else
pos = FIO_NAME(FIO_MAP_NAME, __index)(m, hash, obj, 1);
#endif /* FIO_MAP_KEY */
}
if (pos.i == (FIO_MAP_SIZE_TYPE)-1LL)
goto error;
if (pos.a == (FIO_MAP_SIZE_TYPE)-1LL || !m->map[pos.a].hash) {
/* new */
if (pos.a == (FIO_MAP_SIZE_TYPE)-1LL)
pos.a = m->w++;
#if FIO_MAP_MAX_ELEMENTS
if (m->count >= FIO_MAP_MAX_ELEMENTS) {
FIO_NAME(FIO_MAP_NAME, evict)(map, 1);
}
#endif
FIO_NAME(FIO_MAP_NAME, __imap)
(m)[pos.i] |= pos.a;
m->map[pos.a].hash = hash;
FIO_MAP_TYPE_COPY(FIO_MAP_OBJ2TYPE(m->map[pos.a].obj), obj);
FIO_MAP_KEY_COPY(FIO_MAP_OBJ2KEY(m->map[pos.a].obj), key);
#if FIO_MAP_EVICT_LRU
if (m->count) {
FIO_INDEXED_LIST_PUSH(m->map, node, m->last_used, pos.a);
} else {
m->map[pos.a].node.prev = m->map[pos.a].node.next = pos.a;
}
m->last_used = pos.a;
#endif /* FIO_MAP_EVICT_LRU */
++m->count;
} else if (overwrite &&
FIO_MAP_SHOULD_OVERWRITE(FIO_MAP_OBJ2TYPE(m->map[pos.a].obj),
obj)) {
/* overwrite existing */
FIO_MAP_KEY_DISCARD(key);
if (old) {
FIO_MAP_TYPE_COPY(old[0], FIO_MAP_OBJ2TYPE(m->map[pos.a].obj));
if (FIO_MAP_DESTROY_AFTER_COPY) {
FIO_MAP_TYPE_DESTROY(FIO_MAP_OBJ2TYPE(m->map[pos.a].obj));
}
} else {
FIO_MAP_TYPE_DESTROY(FIO_MAP_OBJ2TYPE(m->map[pos.a].obj));
}
FIO_MAP_TYPE_COPY(FIO_MAP_OBJ2TYPE(m->map[pos.a].obj), obj);
#if FIO_MAP_EVICT_LRU
if (m->last_used != pos.a) {
FIO_INDEXED_LIST_REMOVE(m->map, node, pos.a);
FIO_INDEXED_LIST_PUSH(m->map, node, m->last_used, pos.a);
m->last_used = pos.a;
}
#endif /* FIO_MAP_EVICT_LRU */
} else {
FIO_MAP_TYPE_DISCARD(obj);
FIO_MAP_KEY_DISCARD(key);
}
return &FIO_MAP_OBJ2TYPE(m->map[pos.a].obj);
error:
FIO_MAP_TYPE_DISCARD(obj);
FIO_MAP_KEY_DISCARD(key);
return NULL;
}
SFUNC int FIO_NAME(FIO_MAP_NAME, remove)(FIO_MAP_PTR map,
FIO_MAP_HASH hash,
FIO_MAP_OBJ_KEY key,
FIO_MAP_TYPE *old) {
if (old)
*old = FIO_MAP_TYPE_INVALID;
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m || !m->count)
return -1;
FIO_PTR_TAG_VALID_OR_RETURN(map, NULL);
hash = FIO_MAP_HASH_FIX(hash);
FIO_NAME(FIO_MAP_NAME, __pos_s)
pos = FIO_NAME(FIO_MAP_NAME, __index)(m, hash, key, 0);
if (pos.a == (FIO_MAP_SIZE_TYPE)(-1) || pos.i == (FIO_MAP_SIZE_TYPE)(-1) ||
!m->map[pos.a].hash)
return -1;
FIO_NAME(FIO_MAP_NAME, __imap)(m)[pos.i] = ~(FIO_MAP_SIZE_TYPE)0;
m->map[pos.a].hash = 0;
--m->count;
if (old) {
FIO_MAP_TYPE_COPY(*old, FIO_MAP_OBJ2TYPE(m->map[pos.a].obj));
FIO_MAP_OBJ_DESTROY_AFTER(m->map[pos.a].obj);
} else {
FIO_MAP_OBJ_DESTROY(m->map[pos.a].obj);
}
#if FIO_MAP_EVICT_LRU
if (pos.a == m->last_used)
m->last_used = m->map[pos.a].node.next;
FIO_INDEXED_LIST_REMOVE(m->map, node, pos.a);
#endif
if (!m->count)
m->w = 0;
else if (pos.a + 1 == m->w) {
--m->w;
while (m->w && !m->map[m->w - 1].hash)
--m->w;
}
return 0;
}
SFUNC void FIO_NAME(FIO_MAP_NAME, clear)(FIO_MAP_PTR map) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return;
FIO_PTR_TAG_VALID_OR_RETURN_VOID(map);
FIO_NAME(FIO_MAP_NAME, __destroy_all_objects)(m);
memset(FIO_NAME(FIO_MAP_NAME, __imap)(m), 0, FIO_MAP_CAPA(m->bits));
m->under_attack = 0;
m->count = m->w = 0;
#if FIO_MAP_EVICT_LRU
m->last_used = 0;
#endif
}
SFUNC int FIO_NAME(FIO_MAP_NAME, evict)(FIO_MAP_PTR map,
size_t number_of_elements) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return -1;
FIO_PTR_TAG_VALID_OR_RETURN(map, -1);
if (!m->count)
return -1;
if (number_of_elements >= m->count) {
FIO_NAME(FIO_MAP_NAME, clear)(map);
return -1;
}
#if FIO_MAP_EVICT_LRU
/* evict by LRU */
do {
FIO_MAP_SIZE_TYPE n = m->map[m->last_used].node.prev;
FIO_NAME(FIO_MAP_NAME, remove)
(map, m->map[n].hash, FIO_MAP_OBJ2KEY(m->map[n].obj), NULL);
} while (--number_of_elements);
#else /* FIO_MAP_EVICT_LRU */
/* scan map and evict FIFO. */
for (FIO_MAP_SIZE_TYPE i = 0; number_of_elements && i < m->w; ++i) {
/* skip empty groups (test for all bytes == 0 || 255 */
if (m->map[i].hash) {
FIO_NAME(FIO_MAP_NAME, remove)
(map, m->map[i].hash, FIO_MAP_OBJ2KEY(m->map[i].obj), NULL);
--number_of_elements; /* stop evicting? */
}
}
#endif /* FIO_MAP_EVICT_LRU */
return 0;
}
/* *****************************************************************************
Object state information
***************************************************************************** */
/** Reservse enough space for a theoretical capacity of `capa` objects. */
SFUNC size_t FIO_NAME(FIO_MAP_NAME, reserve)(FIO_MAP_PTR map,
FIO_MAP_SIZE_TYPE capa) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return 0;
FIO_PTR_TAG_VALID_OR_RETURN(map, 0);
if (FIO_MAP_CAPA(m->bits) < capa) {
size_t bits = 3;
while (FIO_MAP_CAPA(bits) < capa)
++bits;
for (int i = 0; FIO_NAME(FIO_MAP_NAME, __realloc)(m, bits + i) && i < 2;
++i) {
}
if (m->bits < bits)
return 0;
}
return FIO_MAP_CAPA(m->bits);
}
/** Attempts to minimize memory use. */
SFUNC void FIO_NAME(FIO_MAP_NAME, compact)(FIO_MAP_PTR map) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return;
FIO_PTR_TAG_VALID_OR_RETURN_VOID(map);
if (!m->bits)
return;
if (!m->count) {
FIO_NAME(FIO_MAP_NAME, destroy)(map);
return;
}
size_t bits = m->bits;
size_t count = 0;
while (bits && FIO_MAP_CAPA((bits - 1)) > m->count) {
--bits;
++count;
}
for (size_t i = 0; i < count; ++i) {
if (!FIO_NAME(FIO_MAP_NAME, __realloc)(m, bits + i))
return;
}
}
/** Rehashes the map. No need to call this, rehashing is automatic. */
SFUNC int FIO_NAME(FIO_MAP_NAME, rehash)(FIO_MAP_PTR map) {
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return -1;
FIO_PTR_TAG_VALID_OR_RETURN(map, -1);
return FIO_NAME(FIO_MAP_NAME, __realloc)(m, m->bits);
}
/* *****************************************************************************
Iteration
***************************************************************************** */
FIO_SFUNC __thread FIO_MAP_SIZE_TYPE FIO_NAME(FIO_MAP_NAME, __each_pos) = 0;
FIO_SFUNC __thread FIO_NAME(FIO_MAP_NAME, s) *
FIO_NAME(FIO_MAP_NAME, __each_map) = NULL;
/**
* Iteration using a callback for each element in the map.
*
* The callback task function must accept an element variable as well as an
* opaque user pointer.
*
* If the callback returns -1, the loop is broken. Any other value is ignored.
*
* Returns the relative "stop" position, i.e., the number of items processed +
* the starting point.
*/
SFUNC FIO_MAP_SIZE_TYPE FIO_NAME(FIO_MAP_NAME,
each)(FIO_MAP_PTR map,
ssize_t start_at,
int (*task)(FIO_MAP_TYPE obj, void *arg),
void *arg) {
FIO_MAP_SIZE_TYPE count = (FIO_MAP_SIZE_TYPE)start_at;
FIO_NAME(FIO_MAP_NAME, s) *m =
(FIO_NAME(FIO_MAP_NAME, s) *)FIO_PTR_UNTAG(map);
if (!m)
return 0;
FIO_PTR_TAG_VALID_OR_RETURN(map, 0);
if (!m->count)
return 0;
if (start_at < 0) {
start_at = m->count + start_at;
if (start_at < 0)
start_at = 0;
}
if ((FIO_MAP_SIZE_TYPE)start_at >= m->count)
return m->count;
FIO_NAME(FIO_MAP_NAME, s) *old_map = FIO_NAME(FIO_MAP_NAME, __each_map);
FIO_MAP_SIZE_TYPE old_pos = FIO_NAME(FIO_MAP_NAME, __each_pos);
FIO_NAME(FIO_MAP_NAME, __each_pos) = 0;
FIO_NAME(FIO_MAP_NAME, __each_map) = m;
if (m->w == m->count) {
FIO_NAME(FIO_MAP_NAME, __each_pos) = (FIO_MAP_SIZE_TYPE)start_at;
while (
count < m->count && (++count) &&
task(FIO_MAP_OBJ2TYPE(m->map[FIO_NAME(FIO_MAP_NAME, __each_pos)].obj),
arg) != -1)
++FIO_NAME(FIO_MAP_NAME, __each_pos);
FIO_NAME(FIO_MAP_NAME, __each_pos) = old_pos;
FIO_NAME(FIO_MAP_NAME, __each_map) = old_map;
return count;
}
while (start_at && FIO_NAME(FIO_MAP_NAME, __each_pos) < m->w) {
if (!m->map[FIO_NAME(FIO_MAP_NAME, __each_pos)++].hash) {
continue;
}
--start_at;
}
if (start_at)
return m->count;
while (count < m->count && FIO_NAME(FIO_MAP_NAME, __each_pos) < m->w) {
if (m->map[FIO_NAME(FIO_MAP_NAME, __each_pos)].hash) {
++count;
if (task(FIO_MAP_OBJ2TYPE(m->map[FIO_NAME(FIO_MAP_NAME, __each_pos)].obj),
arg) == -1)
break;
}
++FIO_NAME(FIO_MAP_NAME, __each_pos);
}
FIO_NAME(FIO_MAP_NAME, __each_pos) = old_pos;
FIO_NAME(FIO_MAP_NAME, __each_map) = old_map;
return count;
}
#ifdef FIO_MAP_KEY
SFUNC FIO_MAP_KEY FIO_NAME(FIO_MAP_NAME, each_get_key)(void) {
if (!FIO_NAME(FIO_MAP_NAME, __each_map) ||
!FIO_NAME(FIO_MAP_NAME, __each_map)->count)
return FIO_MAP_KEY_INVALID;
return FIO_NAME(FIO_MAP_NAME, __each_map)
->map[FIO_NAME(FIO_MAP_NAME, __each_pos)]
.obj.key;
}
#else
SFUNC FIO_MAP_HASH FIO_NAME(FIO_MAP_NAME, each_get_key)(void) {
if (!FIO_NAME(FIO_MAP_NAME, __each_map) ||
!FIO_NAME(FIO_MAP_NAME, __each_map)->count)
return 0;
return FIO_NAME(FIO_MAP_NAME, __each_map)
->map[FIO_NAME(FIO_MAP_NAME, __each_pos)]
.hash;
}
#endif
/* *****************************************************************************
Ordered Map Cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE */
#endif /* FIO_MAP_NAME */
|
janbiedermann/cstl
|
tests/json_minify.c
|
#define FIO_JSON
#define FIO_STR_NAME fio_str
#define FIO_LOG
#include "fio-stl.h"
#define FIO_CLI
#include "fio-stl.h"
typedef struct {
fio_json_parser_s p;
fio_str_s out;
uint8_t counter;
uint8_t done;
} my_json_parser_s;
#define JSON_PARSER_CAST(ptr) FIO_PTR_FROM_FIELD(my_json_parser_s, p, ptr)
#define JSON_PARSER2OUTPUT(p) (&JSON_PARSER_CAST(p)->out)
FIO_IFUNC void my_json_write_nesting(fio_json_parser_s *p) {
my_json_parser_s *j = JSON_PARSER_CAST(p);
if (fio_cli_get_bool("-p")) {
fio_str_write(&j->out, "\n", 1);
for (uint32_t i = 0; i < p->depth; ++i) {
fio_str_write(&j->out, " ", 2);
}
}
}
FIO_IFUNC void my_json_write_seperator(fio_json_parser_s *p) {
my_json_parser_s *j = JSON_PARSER_CAST(p);
if (j->counter) {
switch (fio_json_parser_is_in_object(p)) {
case 0: /* array */
if (fio_json_parser_is_in_array(p)) {
fio_str_write(&j->out, ",", 1);
my_json_write_nesting(p);
}
break;
case 1: /* object */
// note the reverse `if` statement due to operation ordering
if (fio_json_parser_is_key(p)) {
fio_str_write(&j->out, ",", 1);
my_json_write_nesting(p);
} else {
fio_str_write(&j->out, ":", 1);
}
break;
}
}
j->counter |= 1;
}
/** a NULL object was detected */
FIO_JSON_CB void fio_json_on_null(fio_json_parser_s *p) {
my_json_write_seperator(p);
fio_str_write(JSON_PARSER2OUTPUT(p), "null", 4);
}
/** a TRUE object was detected */
static inline void fio_json_on_true(fio_json_parser_s *p) {
my_json_write_seperator(p);
fio_str_write(JSON_PARSER2OUTPUT(p), "true", 4);
}
/** a FALSE object was detected */
FIO_JSON_CB void fio_json_on_false(fio_json_parser_s *p) {
my_json_write_seperator(p);
fio_str_write(JSON_PARSER2OUTPUT(p), "false", 4);
}
/** a Number was detected (long long). */
FIO_JSON_CB void fio_json_on_number(fio_json_parser_s *p, long long i) {
my_json_write_seperator(p);
fio_str_write_i(JSON_PARSER2OUTPUT(p), i);
}
/** a Float was detected (double). */
FIO_JSON_CB void fio_json_on_float(fio_json_parser_s *p, double f) {
my_json_write_seperator(p);
char buffer[256];
size_t len = fio_ftoa(buffer, f, 10);
fio_str_write(JSON_PARSER2OUTPUT(p), buffer, len);
}
/** a String was detected (int / float). update `pos` to point at ending */
FIO_JSON_CB void fio_json_on_string(fio_json_parser_s *p,
const void *start,
size_t len) {
my_json_write_seperator(p);
fio_str_write(JSON_PARSER2OUTPUT(p), "\"", 1);
fio_str_write(JSON_PARSER2OUTPUT(p), start, len);
fio_str_write(JSON_PARSER2OUTPUT(p), "\"", 1);
}
/** a dictionary object was detected, should return 0 unless error occurred. */
FIO_JSON_CB int fio_json_on_start_object(fio_json_parser_s *p) {
my_json_write_seperator(p);
fio_str_write(JSON_PARSER2OUTPUT(p), "{", 1);
my_json_write_nesting(p);
JSON_PARSER_CAST(p)->counter = 0;
return 0;
}
/** a dictionary object closure detected */
FIO_JSON_CB void fio_json_on_end_object(fio_json_parser_s *p) {
my_json_write_nesting(p);
fio_str_write(JSON_PARSER2OUTPUT(p), "}", 1);
JSON_PARSER_CAST(p)->counter = 1;
}
/** an array object was detected, should return 0 unless error occurred. */
FIO_JSON_CB int fio_json_on_start_array(fio_json_parser_s *p) {
my_json_write_seperator(p);
fio_str_write(JSON_PARSER2OUTPUT(p), "[", 1);
my_json_write_nesting(p);
JSON_PARSER_CAST(p)->counter = 0;
return 0;
}
/** an array closure was detected */
FIO_JSON_CB void fio_json_on_end_array(fio_json_parser_s *p) {
my_json_write_nesting(p);
fio_str_write(JSON_PARSER2OUTPUT(p), "]", 1);
JSON_PARSER_CAST(p)->counter = 1;
}
/** the JSON parsing is complete */
FIO_JSON_CB void fio_json_on_json(fio_json_parser_s *p) {
JSON_PARSER_CAST(p)->done = 1;
(void)p;
}
/** the JSON parsing encountered an error */
FIO_JSON_CB void fio_json_on_error(fio_json_parser_s *p) {
fio_str_write(JSON_PARSER2OUTPUT(p),
"--- ERROR, invalid JSON after this point.\0",
42);
}
void run_my_json_minifier(char *json, size_t len) {
my_json_parser_s p = {{0}};
fio_json_parse(&p.p, json, len);
if (!p.done)
FIO_LOG_WARNING(
"JSON parsing was incomplete, minification output is partial");
fprintf(stderr, "%s\n", fio_str2ptr(&p.out));
fio_str_destroy(&p.out);
}
int main(int argc, char const *argv[]) {
// a default string to demo
const char *json_cstr =
u8"{\n\t\"id\":1,\n"
"\t// comments are ignored.\n"
"\t\"number\":42,\n"
"\t\"float\":42.42,\n"
"\t\"string\":\"\\uD834\\uDD1E oh yeah...\",\n"
"\t\"hash\":{\n"
"\t\t\"nested\":true\n"
"\t},\n"
"\t\"symbols\":[\"id\","
"\"number\",\"float\",\"string\",\"hash\",\"symbols\"]\n}";
fio_str_s json = FIO_STR_INIT_STATIC(json_cstr);
fio_cli_start(
argc,
argv,
0,
1,
"This program runs a JSON roundtrip test. Use:\n\n\tNAME [-d] [-f "
"<filename>]\n\tNAME [-d] [JSON string]",
FIO_CLI_STRING("--file -f a file to load for JSON roundtrip testing."),
FIO_CLI_BOOL("--pretty -p -b test Beautify / Prettify roundtrip."),
FIO_CLI_BOOL("--verbose -v enable debugging mode logging."));
if (fio_cli_get_bool("-v")) {
FIO_LOG_LEVEL = FIO_LOG_LEVEL_DEBUG;
}
if (fio_cli_unnamed_count()) {
fio_str_destroy(&json);
fio_str_write(&json, fio_cli_unnamed(0), strlen(fio_cli_unnamed(0)));
}
if (fio_cli_get("-f")) {
fio_str_destroy(&json);
if (!fio_str_readfile(&json, fio_cli_get("-f"), 0, 0).buf) {
FIO_LOG_FATAL("File missing: %s", fio_cli_get("-f"));
exit(-1);
}
}
FIO_LOG_DEBUG2("attempting to parse:\n%s\n", fio_str2ptr(&json));
// Parsing the JSON and cleanup
run_my_json_minifier(fio_str2ptr(&json), fio_str_len(&json));
fio_str_destroy(&json);
return 0;
}
|
janbiedermann/cstl
|
tests/url.c
|
<reponame>janbiedermann/cstl<gh_stars>10-100
#define FIO_URL
#include "fio-stl.h"
int main(int argc, char const *argv[]) {
char *to_parse =
(char *)"http://anon:1234@example.com:443/my/path?answer=42#target";
if (argc >= 2)
to_parse = (char *)argv[1];
fio_url_s u = fio_url_parse(to_parse, strlen(to_parse));
fprintf(stderr,
"Parsed URL:\n"
"\tscheme:\t %.*s\n"
"\tuser:\t%.*s\n"
"\tpass:\t%.*s\n"
"\thost:\t%.*s\n"
"\tport:\t%.*s\n"
"\tpath:\t%.*s\n"
"\tquery:\t%.*s\n"
"\ttarget:\t%.*s\n",
(int)u.scheme.len,
u.scheme.buf,
(int)u.user.len,
u.user.buf,
(int)u.password.len,
u.password.buf,
(int)u.host.len,
u.host.buf,
(int)u.port.len,
u.port.buf,
(int)u.path.len,
u.path.buf,
(int)u.query.len,
u.query.buf,
(int)u.target.len,
u.target.buf);
return 0;
}
|
janbiedermann/cstl
|
stl_slices/102 queue.h
|
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#define FIO_QUEUE /* Development inclusion - ignore line */
#include "000 header.h" /* Development inclusion - ignore line */
#include "003 atomics.h" /* Development inclusion - ignore line */
#include "100 mem.h" /* Development inclusion - ignore line */
#include "101 time.h" /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
Task / Timer Queues
(Event Loop Engine)
***************************************************************************** */
#if defined(FIO_QUEUE) && !defined(H___FIO_QUEUE___H)
#define H___FIO_QUEUE___H
/* *****************************************************************************
Queue Type(s)
***************************************************************************** */
/* Note: FIO_QUEUE_TASKS_PER_ALLOC can't be more than 65535 */
#ifndef FIO_QUEUE_TASKS_PER_ALLOC
#if UINTPTR_MAX <= 0xFFFFFFFF
/* fits fio_queue_s in one page on most 32 bit machines */
#define FIO_QUEUE_TASKS_PER_ALLOC 338
#else
/* fits fio_queue_s in one page on most 64 bit machines */
#define FIO_QUEUE_TASKS_PER_ALLOC 168
#endif
#endif
/** Task information */
typedef struct {
/** The function to call */
void (*fn)(void *, void *);
/** User opaque data */
void *udata1;
/** User opaque data */
void *udata2;
} fio_queue_task_s;
/* internal use */
typedef struct fio___task_ring_s {
uint16_t r; /* reader position */
uint16_t w; /* writer position */
uint16_t dir; /* direction */
struct fio___task_ring_s *next;
fio_queue_task_s buf[FIO_QUEUE_TASKS_PER_ALLOC];
} fio___task_ring_s;
/** The queue object - should be considered opaque (or, at least, read only). */
typedef struct {
fio___task_ring_s *r;
fio___task_ring_s *w;
/** the number of tasks waiting to be performed. */
size_t count;
FIO___LOCK_TYPE lock;
fio___task_ring_s mem;
} fio_queue_s;
/* *****************************************************************************
Queue API
***************************************************************************** */
/** May be used to initialize global, static memory, queues. */
#define FIO_QUEUE_STATIC_INIT(queue) \
{ .r = &(queue).mem, .w = &(queue).mem, .lock = FIO___LOCK_INIT }
/** Initializes a fio_queue_s object. */
FIO_IFUNC void fio_queue_init(fio_queue_s *q);
/** Destroys a queue and re-initializes it, after freeing any used resources. */
SFUNC void fio_queue_destroy(fio_queue_s *q);
/** Creates a new queue object (allocated on the heap). */
FIO_IFUNC fio_queue_s *fio_queue_new(void);
/** Frees a queue object after calling fio_queue_destroy. */
SFUNC void fio_queue_free(fio_queue_s *q);
/** Pushes a task to the queue. Returns -1 on error. */
SFUNC int fio_queue_push(fio_queue_s *q, fio_queue_task_s task);
/**
* Pushes a task to the queue, offering named arguments for the task.
* Returns -1 on error.
*/
#define fio_queue_push(q, ...) \
fio_queue_push((q), (fio_queue_task_s){__VA_ARGS__})
/** Pushes a task to the head of the queue. Returns -1 on error (no memory). */
SFUNC int fio_queue_push_urgent(fio_queue_s *q, fio_queue_task_s task);
/**
* Pushes a task to the queue, offering named arguments for the task.
* Returns -1 on error.
*/
#define fio_queue_push_urgent(q, ...) \
fio_queue_push_urgent((q), (fio_queue_task_s){__VA_ARGS__})
/** Pops a task from the queue (FIFO). Returns a NULL task on error. */
SFUNC fio_queue_task_s fio_queue_pop(fio_queue_s *q);
/** Performs a task from the queue. Returns -1 on error (queue empty). */
SFUNC int fio_queue_perform(fio_queue_s *q);
/** Performs all tasks in the queue. */
SFUNC void fio_queue_perform_all(fio_queue_s *q);
/** returns the number of tasks in the queue. */
FIO_IFUNC size_t fio_queue_count(fio_queue_s *q);
/* *****************************************************************************
Timer Queue Types and API
***************************************************************************** */
typedef struct fio___timer_event_s fio___timer_event_s;
typedef struct {
fio___timer_event_s *next;
FIO___LOCK_TYPE lock;
} fio_timer_queue_s;
#define FIO_TIMER_QUEUE_INIT \
{ .lock = FIO___LOCK_INIT }
typedef struct {
/** The timer function. If it returns a non-zero value, the timer stops. */
int (*fn)(void *, void *);
/** Opaque user data. */
void *udata1;
/** Opaque user data. */
void *udata2;
/** Called when the timer is done (finished). */
void (*on_finish)(void *, void *);
/** Timer interval, in milliseconds. */
uint32_t every;
/** The number of times the timer should be performed. -1 == infinity. */
int32_t repetitions;
/** Millisecond at which to start. If missing, filled automatically. */
int64_t start_at;
} fio_timer_schedule_args_s;
/** Adds a time-bound event to the timer queue. */
SFUNC void fio_timer_schedule(fio_timer_queue_s *timer_queue,
fio_timer_schedule_args_s args);
/** A MACRO allowing named arguments to be used. See fio_timer_schedule_args_s.
*/
#define fio_timer_schedule(timer_queue, ...) \
fio_timer_schedule((timer_queue), (fio_timer_schedule_args_s){__VA_ARGS__})
/** Pushes due events from the timer queue to an event queue. */
SFUNC size_t fio_timer_push2queue(fio_queue_s *queue,
fio_timer_queue_s *timer_queue,
int64_t now_in_milliseconds);
/*
* Returns the millisecond at which the next event should occur.
*
* If no timer is due (list is empty), returns `(uint64_t)-1`.
*
* NOTE: unless manually specified, millisecond timers are relative to
* `fio_time_milli()`.
*/
FIO_IFUNC int64_t fio_timer_next_at(fio_timer_queue_s *timer_queue);
/**
* Clears any waiting timer bound tasks.
*
* NOTE:
*
* The timer queue must NEVER be freed when there's a chance that timer tasks
* are waiting to be performed in a `fio_queue_s`.
*
* This is due to the fact that the tasks may try to reschedule themselves (if
* they repeat).
*/
SFUNC void fio_timer_destroy(fio_timer_queue_s *timer_queue);
/* *****************************************************************************
Queue Inline Helpers
***************************************************************************** */
/** Creates a new queue object (allocated on the heap). */
FIO_IFUNC fio_queue_s *fio_queue_new(void) {
fio_queue_s *q = (fio_queue_s *)FIO_MEM_REALLOC_(NULL, 0, sizeof(*q), 0);
if (!q)
return NULL;
fio_queue_init(q);
return q;
}
/** returns the number of tasks in the queue. */
FIO_IFUNC size_t fio_queue_count(fio_queue_s *q) { return q->count; }
/* *****************************************************************************
Timer Queue Inline Helpers
***************************************************************************** */
struct fio___timer_event_s {
int (*fn)(void *, void *);
void *udata1;
void *udata2;
void (*on_finish)(void *udata1, void *udata2);
int64_t due;
uint32_t every;
int32_t repetitions;
struct fio___timer_event_s *next;
};
/*
* Returns the millisecond at which the next event should occur.
*
* If no timer is due (list is empty), returns `(uint64_t)-1`.
*
* NOTE: unless manually specified, millisecond timers are relative to
* `fio_time_milli()`.
*/
FIO_IFUNC int64_t fio_timer_next_at(fio_timer_queue_s *tq) {
int64_t v = -1;
if (!tq)
goto missing_tq;
if (!tq || !tq->next)
return v;
FIO___LOCK_LOCK(tq->lock);
if (tq->next)
v = tq->next->due;
FIO___LOCK_UNLOCK(tq->lock);
return v;
missing_tq:
FIO_LOG_ERROR("`fio_timer_next_at` called with a NULL timer queue!");
return v;
}
/* *****************************************************************************
Queue Implementation
***************************************************************************** */
#if defined(FIO_EXTERN_COMPLETE)
/** Initializes a fio_queue_s object. */
FIO_IFUNC void fio_queue_init(fio_queue_s *q) {
/* do this manually, we don't want to reset a whole page */
q->r = &q->mem;
q->w = &q->mem;
q->count = 0;
q->lock = FIO___LOCK_INIT;
q->mem.next = NULL;
q->mem.r = q->mem.w = q->mem.dir = 0;
}
/** Destroys a queue and re-initializes it, after freeing any used resources. */
SFUNC void fio_queue_destroy(fio_queue_s *q) {
FIO___LOCK_LOCK(q->lock);
while (q->r) {
fio___task_ring_s *tmp = q->r;
q->r = q->r->next;
if (tmp != &q->mem)
FIO_MEM_FREE_(tmp, sizeof(*tmp));
}
FIO___LOCK_UNLOCK(q->lock);
FIO___LOCK_DESTROY(q->lock);
fio_queue_init(q);
}
/** Frees a queue object after calling fio_queue_destroy. */
SFUNC void fio_queue_free(fio_queue_s *q) {
fio_queue_destroy(q);
FIO_MEM_FREE_(q, sizeof(*q));
}
FIO_IFUNC int fio___task_ring_push(fio___task_ring_s *r,
fio_queue_task_s task) {
if (r->dir && r->r == r->w)
return -1;
r->buf[r->w] = task;
++r->w;
if (r->w == FIO_QUEUE_TASKS_PER_ALLOC) {
r->w = 0;
r->dir = ~r->dir;
}
return 0;
}
FIO_IFUNC int fio___task_ring_unpop(fio___task_ring_s *r,
fio_queue_task_s task) {
if (r->dir && r->r == r->w)
return -1;
if (!r->r) {
r->r = FIO_QUEUE_TASKS_PER_ALLOC;
r->dir = ~r->dir;
}
--r->r;
r->buf[r->r] = task;
return 0;
}
FIO_IFUNC fio_queue_task_s fio___task_ring_pop(fio___task_ring_s *r) {
fio_queue_task_s t = {.fn = NULL};
if (!r->dir && r->r == r->w) {
return t;
}
t = r->buf[r->r];
++r->r;
if (r->r == FIO_QUEUE_TASKS_PER_ALLOC) {
r->r = 0;
r->dir = ~r->dir;
}
return t;
}
int fio_queue_push___(void); /* sublime text marker */
/** Pushes a task to the queue. Returns -1 on error. */
SFUNC int fio_queue_push FIO_NOOP(fio_queue_s *q, fio_queue_task_s task) {
if (!task.fn)
return 0;
FIO___LOCK_LOCK(q->lock);
if (fio___task_ring_push(q->w, task)) {
if (q->w != &q->mem && q->mem.next == NULL) {
q->w->next = &q->mem;
q->mem.w = q->mem.r = q->mem.dir = 0;
} else {
void *tmp = (fio___task_ring_s *)
FIO_MEM_REALLOC_(NULL, 0, sizeof(*q->w->next), 0);
if (!tmp)
goto no_mem;
q->w->next = (fio___task_ring_s *)tmp;
if (!FIO_MEM_REALLOC_IS_SAFE_) {
q->w->next->r = q->w->next->w = q->w->next->dir = 0;
q->w->next->next = NULL;
}
}
q->w = q->w->next;
fio___task_ring_push(q->w, task);
}
++q->count;
FIO___LOCK_UNLOCK(q->lock);
return 0;
no_mem:
FIO___LOCK_UNLOCK(q->lock);
return -1;
}
int fio_queue_push_urgent___(void); /* sublimetext marker */
/** Pushes a task to the head of the queue. Returns -1 on error (no memory). */
SFUNC int fio_queue_push_urgent FIO_NOOP(fio_queue_s *q,
fio_queue_task_s task) {
if (!task.fn)
return 0;
FIO___LOCK_LOCK(q->lock);
if (fio___task_ring_unpop(q->r, task)) {
/* such a shame... but we must allocate a while task block for one task */
fio___task_ring_s *tmp =
(fio___task_ring_s *)FIO_MEM_REALLOC_(NULL, 0, sizeof(*q->w->next), 0);
if (!tmp)
goto no_mem;
tmp->next = q->r;
q->r = tmp;
tmp->w = 1;
tmp->dir = tmp->r = 0;
tmp->buf[0] = task;
}
++q->count;
FIO___LOCK_UNLOCK(q->lock);
return 0;
no_mem:
FIO___LOCK_UNLOCK(q->lock);
return -1;
}
/** Pops a task from the queue (FIFO). Returns a NULL task on error. */
SFUNC fio_queue_task_s fio_queue_pop(fio_queue_s *q) {
fio_queue_task_s t = {.fn = NULL};
fio___task_ring_s *to_free = NULL;
if (!q->count)
return t;
FIO___LOCK_LOCK(q->lock);
if (!q->count)
goto finish;
if (!(t = fio___task_ring_pop(q->r)).fn) {
to_free = q->r;
q->r = to_free->next;
to_free->next = NULL;
t = fio___task_ring_pop(q->r);
}
if (t.fn && !(--q->count) && q->r != &q->mem) {
if (to_free && to_free != &q->mem) { // edge case? never happens?
FIO_MEM_FREE_(to_free, sizeof(*to_free));
}
to_free = q->r;
q->r = q->w = &q->mem;
q->mem.w = q->mem.r = q->mem.dir = 0;
}
finish:
FIO___LOCK_UNLOCK(q->lock);
if (to_free && to_free != &q->mem) {
FIO_MEM_FREE_(to_free, sizeof(*to_free));
}
return t;
}
/** Performs a task from the queue. Returns -1 on error (queue empty). */
SFUNC int fio_queue_perform(fio_queue_s *q) {
fio_queue_task_s t = fio_queue_pop(q);
if (t.fn) {
t.fn(t.udata1, t.udata2);
return 0;
}
return -1;
}
/** Performs all tasks in the queue. */
SFUNC void fio_queue_perform_all(fio_queue_s *q) {
fio_queue_task_s t;
while ((t = fio_queue_pop(q)).fn)
t.fn(t.udata1, t.udata2);
}
/* *****************************************************************************
Timer Queue Implementation
***************************************************************************** */
FIO_IFUNC void fio___timer_insert(fio___timer_event_s **pos,
fio___timer_event_s *e) {
while (*pos && e->due >= (*pos)->due)
pos = &((*pos)->next);
e->next = *pos;
*pos = e;
}
FIO_IFUNC fio___timer_event_s *fio___timer_pop(fio___timer_event_s **pos,
int64_t due) {
if (!*pos || (*pos)->due > due)
return NULL;
fio___timer_event_s *t = *pos;
*pos = t->next;
return t;
}
FIO_IFUNC fio___timer_event_s *fio___timer_event_new(
fio_timer_schedule_args_s args) {
fio___timer_event_s *t = NULL;
t = (fio___timer_event_s *)FIO_MEM_REALLOC_(NULL, 0, sizeof(*t), 0);
if (!t)
goto init_error;
if (!args.repetitions)
args.repetitions = 1;
*t = (fio___timer_event_s){
.fn = args.fn,
.udata1 = args.udata1,
.udata2 = args.udata2,
.on_finish = args.on_finish,
.due = args.start_at + args.every,
.every = args.every,
.repetitions = args.repetitions,
};
return t;
init_error:
if (args.on_finish)
args.on_finish(args.udata1, args.udata2);
return NULL;
}
FIO_IFUNC void fio___timer_event_free(fio_timer_queue_s *tq,
fio___timer_event_s *t) {
if (tq && (t->repetitions < 0 || fio_atomic_sub_fetch(&t->repetitions, 1))) {
FIO___LOCK_LOCK(tq->lock);
fio___timer_insert(&tq->next, t);
FIO___LOCK_UNLOCK(tq->lock);
return;
}
if (t->on_finish)
t->on_finish(t->udata1, t->udata2);
FIO_MEM_FREE_(t, sizeof(*t));
}
SFUNC void fio___timer_perform(void *timer_, void *t_) {
fio_timer_queue_s *tq = (fio_timer_queue_s *)timer_;
fio___timer_event_s *t = (fio___timer_event_s *)t_;
if (t->fn(t->udata1, t->udata2))
tq = NULL;
t->due += t->every;
fio___timer_event_free(tq, t);
}
/** Pushes due events from the timer queue to an event queue. */
SFUNC size_t fio_timer_push2queue(fio_queue_s *queue,
fio_timer_queue_s *timer,
int64_t start_at) {
size_t r = 0;
if (!start_at)
start_at = fio_time_milli();
if (FIO___LOCK_TRYLOCK(timer->lock))
return 0;
fio___timer_event_s *t;
while ((t = fio___timer_pop(&timer->next, start_at))) {
fio_queue_push(queue,
.fn = fio___timer_perform,
.udata1 = timer,
.udata2 = t);
++r;
}
FIO___LOCK_UNLOCK(timer->lock);
return r;
}
void fio_timer_schedule___(void); /* sublimetext marker */
/** Adds a time-bound event to the timer queue. */
SFUNC void fio_timer_schedule FIO_NOOP(fio_timer_queue_s *timer,
fio_timer_schedule_args_s args) {
fio___timer_event_s *t = NULL;
if (!timer || !args.fn || !args.every)
goto no_timer_queue;
if (!args.start_at)
args.start_at = fio_time_milli();
t = fio___timer_event_new(args);
if (!t)
return;
FIO___LOCK_LOCK(timer->lock);
fio___timer_insert(&timer->next, t);
FIO___LOCK_UNLOCK(timer->lock);
return;
no_timer_queue:
if (args.on_finish)
args.on_finish(args.udata1, args.udata2);
FIO_LOG_ERROR("fio_timer_schedule called with illegal arguments.");
}
/**
* Clears any waiting timer bound tasks.
*
* NOTE:
*
* The timer queue must NEVER be freed when there's a chance that timer tasks
* are waiting to be performed in a `fio_queue_s`.
*
* This is due to the fact that the tasks may try to reschedule themselves (if
* they repeat).
*/
SFUNC void fio_timer_destroy(fio_timer_queue_s *tq) {
fio___timer_event_s *next;
FIO___LOCK_LOCK(tq->lock);
next = tq->next;
tq->next = NULL;
FIO___LOCK_UNLOCK(tq->lock);
FIO___LOCK_DESTROY(tq->lock);
while (next) {
fio___timer_event_s *tmp = next;
next = next->next;
fio___timer_event_free(NULL, tmp);
}
}
/* *****************************************************************************
Queue - test
***************************************************************************** */
#ifdef FIO_TEST_CSTL
#ifndef FIO___QUEUE_TEST_PRINT
#define FIO___QUEUE_TEST_PRINT 0
#endif
#define FIO___QUEUE_TOTAL_COUNT (512 * 1024)
typedef struct {
fio_queue_s *q;
uintptr_t count;
} fio___queue_test_s;
FIO_SFUNC void fio___queue_test_sample_task(void *i_count, void *unused2) {
(void)(unused2);
fio_atomic_add((uintptr_t *)i_count, 1);
}
FIO_SFUNC void fio___queue_test_sched_sample_task(void *t_, void *i_count) {
fio___queue_test_s *t = (fio___queue_test_s *)t_;
for (size_t i = 0; i < t->count; i++) {
FIO_ASSERT(!fio_queue_push(t->q,
.fn = fio___queue_test_sample_task,
.udata1 = i_count),
"Couldn't push task!");
}
}
FIO_SFUNC int fio___queue_test_timer_task(void *i_count, void *unused2) {
fio_atomic_add((uintptr_t *)i_count, 1);
return (unused2 ? -1 : 0);
}
FIO_SFUNC void FIO_NAME_TEST(stl, queue)(void) {
fprintf(stderr, "* Testing facil.io task scheduling (fio_queue)\n");
fio_queue_s *q = fio_queue_new();
fio_queue_s q2;
fprintf(stderr, "\t- size of queue object (fio_queue_s): %zu\n", sizeof(*q));
fprintf(stderr,
"\t- size of queue ring buffer (per allocation): %zu\n",
sizeof(q->mem));
fprintf(stderr,
"\t- event slots per queue allocation: %zu\n",
(size_t)FIO_QUEUE_TASKS_PER_ALLOC);
const size_t max_threads = 12; // assumption / pure conjuncture...
uintptr_t i_count;
clock_t start, end;
i_count = 0;
start = clock();
for (size_t i = 0; i < FIO___QUEUE_TOTAL_COUNT; i++) {
fio___queue_test_sample_task(&i_count, NULL);
}
end = clock();
if (FIO___QUEUE_TEST_PRINT) {
fprintf(
stderr,
"\t- Queueless (direct call) counter: %lu cycles with i_count = %lu\n",
(unsigned long)(end - start),
(unsigned long)i_count);
}
size_t i_count_should_be = i_count;
i_count = 0;
start = clock();
for (size_t i = 0; i < FIO___QUEUE_TOTAL_COUNT; i++) {
fio_queue_push(q,
.fn = fio___queue_test_sample_task,
.udata1 = (void *)&i_count);
}
fio_queue_perform_all(q);
end = clock();
if (FIO___QUEUE_TEST_PRINT) {
fprintf(stderr,
"\t- single task counter: %lu cycles with i_count = %lu\n",
(unsigned long)(end - start),
(unsigned long)i_count);
}
FIO_ASSERT(i_count == i_count_should_be, "ERROR: queue count invalid\n");
if (FIO___QUEUE_TEST_PRINT) {
fprintf(stderr, "\n");
}
for (size_t i = 1; i < 32 && FIO___QUEUE_TOTAL_COUNT >> i; ++i) {
fio___queue_test_s info = {.q = q,
.count =
(uintptr_t)(FIO___QUEUE_TOTAL_COUNT >> i)};
const size_t tasks = 1 << i;
i_count = 0;
start = clock();
for (size_t j = 0; j < tasks; ++j) {
fio_queue_push(q,
fio___queue_test_sched_sample_task,
(void *)&info,
&i_count);
}
FIO_ASSERT(fio_queue_count(q), "tasks not counted?!");
{
const size_t t_count = (i % max_threads) + 1;
union {
void *(*t)(void *);
void (*act)(fio_queue_s *);
} thread_tasks;
thread_tasks.act = fio_queue_perform_all;
fio_thread_t *threads = (fio_thread_t *)
FIO_MEM_REALLOC_(NULL, 0, sizeof(*threads) * t_count, 0);
for (size_t j = 0; j < t_count; ++j) {
if (fio_thread_create(threads + j, thread_tasks.t, q)) {
abort();
}
}
for (size_t j = 0; j < t_count; ++j) {
fio_thread_join(threads[j]);
}
FIO_MEM_FREE(threads, sizeof(*threads) * t_count);
}
end = clock();
if (FIO___QUEUE_TEST_PRINT) {
fprintf(stderr,
"- queue performed using %zu threads, %zu scheduling loops (%zu "
"each):\n"
" %lu cycles with i_count = %lu\n",
((i % max_threads) + 1),
tasks,
info.count,
(unsigned long)(end - start),
(unsigned long)i_count);
} else {
fprintf(stderr, ".");
}
FIO_ASSERT(i_count == i_count_should_be, "ERROR: queue count invalid\n");
}
if (!(FIO___QUEUE_TEST_PRINT))
fprintf(stderr, "\n");
FIO_ASSERT(q->w == &q->mem,
"queue library didn't release dynamic queue (should be static)");
fio_queue_free(q);
{
fprintf(stderr, "* testing urgent insertion\n");
fio_queue_init(&q2);
for (size_t i = 0; i < (FIO_QUEUE_TASKS_PER_ALLOC * 3); ++i) {
FIO_ASSERT(!fio_queue_push_urgent(&q2,
.fn = (void (*)(void *, void *))(i + 1),
.udata1 = (void *)(i + 1)),
"fio_queue_push_urgent failed");
}
FIO_ASSERT(q2.r->next && q2.r->next->next && !q2.r->next->next->next,
"should have filled only three task blocks");
for (size_t i = 0; i < (FIO_QUEUE_TASKS_PER_ALLOC * 3); ++i) {
fio_queue_task_s t = fio_queue_pop(&q2);
FIO_ASSERT(
t.fn && (size_t)t.udata1 == (FIO_QUEUE_TASKS_PER_ALLOC * 3) - i,
"fio_queue_push_urgent pop ordering error [%zu] %zu != %zu (%p)",
i,
(size_t)t.udata1,
(FIO_QUEUE_TASKS_PER_ALLOC * 3) - i,
(void *)(uintptr_t)t.fn);
}
FIO_ASSERT(fio_queue_pop(&q2).fn == NULL,
"pop overflow after urgent tasks");
fio_queue_destroy(&q2);
}
{
fprintf(stderr,
"* Testing facil.io timer scheduling (fio_timer_queue_s)\n");
fprintf(stderr, " Note: Errors SHOULD print out to the log.\n");
fio_queue_init(&q2);
uintptr_t tester = 0;
fio_timer_queue_s tq = FIO_TIMER_QUEUE_INIT;
/* test failuers */
fio_timer_schedule(&tq,
.udata1 = &tester,
.on_finish = fio___queue_test_sample_task,
.every = 100,
.repetitions = -1);
FIO_ASSERT(tester == 1,
"fio_timer_schedule should have called `on_finish`");
tester = 0;
fio_timer_schedule(NULL,
.fn = fio___queue_test_timer_task,
.udata1 = &tester,
.on_finish = fio___queue_test_sample_task,
.every = 100,
.repetitions = -1);
FIO_ASSERT(tester == 1,
"fio_timer_schedule should have called `on_finish`");
tester = 0;
fio_timer_schedule(&tq,
.fn = fio___queue_test_timer_task,
.udata1 = &tester,
.on_finish = fio___queue_test_sample_task,
.every = 0,
.repetitions = -1);
FIO_ASSERT(tester == 1,
"fio_timer_schedule should have called `on_finish`");
fprintf(stderr, " Note: no more errors should pront for this test.\n");
/* test endless task */
tester = 0;
fio_timer_schedule(&tq,
.fn = fio___queue_test_timer_task,
.udata1 = &tester,
.on_finish = fio___queue_test_sample_task,
.every = 1,
.repetitions = -1,
.start_at = fio_time_milli() - 10);
FIO_ASSERT(tester == 0,
"fio_timer_schedule should have scheduled the task.");
for (size_t i = 0; i < 10; ++i) {
uint64_t now = fio_time_milli();
fio_timer_push2queue(&q2, &tq, now);
fio_timer_push2queue(&q2, &tq, now);
FIO_ASSERT(fio_queue_count(&q2), "task should have been scheduled");
FIO_ASSERT(fio_queue_count(&q2) == 1,
"task should have been scheduled only once");
fio_queue_perform(&q2);
FIO_ASSERT(!fio_queue_count(&q2), "queue should be empty");
FIO_ASSERT(tester == i + 1,
"task should have been performed (%zu).",
(size_t)tester);
}
tester = 0;
fio_timer_destroy(&tq);
FIO_ASSERT(tester == 1, "fio_timer_destroy should have called `on_finish`");
/* test single-use task */
tester = 0;
int64_t milli_now = fio_time_milli();
fio_timer_schedule(&tq,
.fn = fio___queue_test_timer_task,
.udata1 = &tester,
.on_finish = fio___queue_test_sample_task,
.every = 100,
.repetitions = 1,
.start_at = milli_now - 10);
FIO_ASSERT(tester == 0,
"fio_timer_schedule should have scheduled the task.");
fio_timer_schedule(&tq,
.fn = fio___queue_test_timer_task,
.udata1 = &tester,
.on_finish = fio___queue_test_sample_task,
.every = 1,
// .repetitions = 1, // auto-value is 1
.start_at = milli_now - 10);
FIO_ASSERT(tester == 0,
"fio_timer_schedule should have scheduled the task.");
FIO_ASSERT(fio_timer_next_at(&tq) == milli_now - 9,
"fio_timer_next_at value error.");
fio_timer_push2queue(&q2, &tq, milli_now);
FIO_ASSERT(fio_queue_count(&q2) == 1,
"task should have been scheduled (2)");
FIO_ASSERT(fio_timer_next_at(&tq) == milli_now + 90,
"fio_timer_next_at value error for unscheduled task.");
fio_queue_perform(&q2);
FIO_ASSERT(!fio_queue_count(&q2), "queue should be empty");
FIO_ASSERT(tester == 2,
"task should have been performed and on_finish called (%zu).",
(size_t)tester);
fio_timer_destroy(&tq);
FIO_ASSERT(
tester == 3,
"fio_timer_destroy should have called on_finish of future task (%zu).",
(size_t)tester);
FIO_ASSERT(!tq.next, "timer queue should be empty.");
fio_queue_destroy(&q2);
}
fprintf(stderr, "* passed.\n");
}
#endif /* FIO_TEST_CSTL */
/* *****************************************************************************
Queue/Timer Cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE */
#undef FIO_QUEUE
#endif /* FIO_QUEUE */
|
janbiedermann/cstl
|
stl_slices/101 time.h
|
<filename>stl_slices/101 time.h
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#define FIO_TIME /* Development inclusion - ignore line */
#define FIO_ATOL /* Development inclusion - ignore line */
#include "000 header.h" /* Development inclusion - ignore line */
#include "003 atomics.h" /* Development inclusion - ignore line */
#include "006 atol.h" /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
Time Helpers
***************************************************************************** */
#if defined(FIO_TIME) && !defined(H___FIO_TIME___H)
#define H___FIO_TIME___H
/* *****************************************************************************
Collecting Monotonic / Real Time
***************************************************************************** */
/** Returns human (watch) time... this value isn't as safe for measurements. */
FIO_IFUNC struct timespec fio_time_real();
/** Returns monotonic time. */
FIO_IFUNC struct timespec fio_time_mono();
/** Returns monotonic time in nano-seconds (now in 1 billionth of a second). */
FIO_IFUNC int64_t fio_time_nano();
/** Returns monotonic time in micro-seconds (now in 1 millionth of a second). */
FIO_IFUNC int64_t fio_time_micro();
/** Returns monotonic time in milliseconds. */
FIO_IFUNC int64_t fio_time_milli();
/** Converts a `struct timespec` to milliseconds. */
FIO_IFUNC int64_t fio_time2milli(struct timespec);
/**
* A faster (yet less localized) alternative to `gmtime_r`.
*
* See the libc `gmtime_r` documentation for details.
*
* Falls back to `gmtime_r` for dates before epoch.
*/
SFUNC struct tm fio_time2gm(time_t time);
/** Converts a `struct tm` to time in seconds (assuming UTC). */
SFUNC time_t fio_gm2time(struct tm tm);
/**
* Writes an RFC 7231 date representation (HTTP date format) to target.
*
* Usually requires 29 characters, although this may vary.
*/
SFUNC size_t fio_time2rfc7231(char *target, time_t time);
/**
* Writes an RFC 2109 date representation to target.
*
* Usually requires 31 characters, although this may vary.
*/
SFUNC size_t fio_time2rfc2109(char *target, time_t time);
/**
* Writes an RFC 2822 date representation to target.
*
* Usually requires 28 to 29 characters, although this may vary.
*/
SFUNC size_t fio_time2rfc2822(char *target, time_t time);
/**
* Writes a date representation to target in common log format. i.e.,
*
* [DD/MMM/yyyy:hh:mm:ss +0000]
*
* Usually requires 29 characters (includiing square brackes and NUL).
*/
SFUNC size_t fio_time2log(char *target, time_t time);
/* *****************************************************************************
Time Inline Helpers
***************************************************************************** */
/** Returns human (watch) time... this value isn't as safe for measurements. */
FIO_IFUNC struct timespec fio_time_real() {
struct timespec t;
clock_gettime(CLOCK_REALTIME, &t);
return t;
}
/** Returns monotonic time. */
FIO_IFUNC struct timespec fio_time_mono() {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t;
}
/** Returns monotonic time in nano-seconds (now in 1 micro of a second). */
FIO_IFUNC int64_t fio_time_nano() {
struct timespec t = fio_time_mono();
return ((int64_t)t.tv_sec * 1000000000) + (int64_t)t.tv_nsec;
}
/** Returns monotonic time in micro-seconds (now in 1 millionth of a second). */
FIO_IFUNC int64_t fio_time_micro() {
struct timespec t = fio_time_mono();
return ((int64_t)t.tv_sec * 1000000) + (int64_t)t.tv_nsec / 1000;
}
/** Returns monotonic time in milliseconds. */
FIO_IFUNC int64_t fio_time_milli() {
struct timespec t = fio_time_mono();
return ((int64_t)t.tv_sec * 1000) + (int64_t)t.tv_nsec / 1000000;
}
/** Converts a `struct timespec` to milliseconds. */
FIO_IFUNC int64_t fio_time2milli(struct timespec t) {
return ((int64_t)t.tv_sec * 1000) + (int64_t)t.tv_nsec / 1000000;
}
/* *****************************************************************************
Time Implementation
***************************************************************************** */
#if defined(FIO_EXTERN_COMPLETE)
/**
* A faster (yet less localized) alternative to `gmtime_r`.
*
* See the libc `gmtime_r` documentation for details.
*
* Falls back to `gmtime_r` for dates before epoch.
*/
SFUNC struct tm fio_time2gm(time_t timer) {
struct tm tm;
ssize_t a, b;
#if HAVE_TM_TM_ZONE || defined(BSD)
tm = (struct tm){
.tm_isdst = 0,
.tm_zone = (char *)"UTC",
};
#else
tm = (struct tm){
.tm_isdst = 0,
};
#endif
// convert seconds from epoch to days from epoch + extract data
if (timer >= 0) {
// for seconds up to weekdays, we reduce the reminder every step.
a = (ssize_t)timer;
b = a / 60; // b == time in minutes
tm.tm_sec = (int)(a - (b * 60));
a = b / 60; // b == time in hours
tm.tm_min = (int)(b - (a * 60));
b = a / 24; // b == time in days since epoch
tm.tm_hour = (int)(a - (b * 24));
// b == number of days since epoch
// day of epoch was a thursday. Add + 4 so sunday == 0...
tm.tm_wday = (b + 4) % 7;
} else {
// for seconds up to weekdays, we reduce the reminder every step.
a = (ssize_t)timer;
b = a / 60; // b == time in minutes
if (b * 60 != a) {
/* seconds passed */
tm.tm_sec = (int)((a - (b * 60)) + 60);
--b;
} else {
/* no seconds */
tm.tm_sec = 0;
}
a = b / 60; // b == time in hours
if (a * 60 != b) {
/* minutes passed */
tm.tm_min = (int)((b - (a * 60)) + 60);
--a;
} else {
/* no minutes */
tm.tm_min = 0;
}
b = a / 24; // b == time in days since epoch?
if (b * 24 != a) {
/* hours passed */
tm.tm_hour = (int)((a - (b * 24)) + 24);
--b;
} else {
/* no hours */
tm.tm_hour = 0;
}
// day of epoch was a thursday. Add + 4 so sunday == 0...
tm.tm_wday = ((b - 3) % 7);
if (tm.tm_wday)
tm.tm_wday += 7;
/* b == days from epoch */
}
// at this point we can apply the algorithm described here:
// http://howardhinnant.github.io/date_algorithms.html#civil_from_days
// Credit to <NAME>.
{
b += 719468L; // adjust to March 1st, 2000 (post leap of 400 year era)
// 146,097 = days in era (400 years)
const size_t era = (b >= 0 ? b : b - 146096) / 146097;
const uint32_t doe = (uint32_t)(b - (era * 146097)); // day of era
const uint16_t yoe = (uint16_t)(
(doe - doe / 1460 + doe / 36524 - doe / 146096) / 365); // year of era
a = yoe;
a += era * 400; // a == year number, assuming year starts on March 1st...
const uint16_t doy = (uint16_t)(doe - (365 * yoe + yoe / 4 - yoe / 100));
const uint16_t mp = (uint16_t)((5U * doy + 2) / 153);
const uint16_t d = (uint16_t)(doy - (153U * mp + 2) / 5 + 1);
const uint8_t m = (uint8_t)(mp + (mp < 10 ? 2 : -10));
a += (m <= 1);
tm.tm_year = (int)(a - 1900); // tm_year == years since 1900
tm.tm_mon = m;
tm.tm_mday = d;
const uint8_t is_leap = (a % 4 == 0 && (a % 100 != 0 || a % 400 == 0));
tm.tm_yday = (doy + (is_leap) + 28 + 31) % (365 + is_leap);
}
return tm;
}
/** Converts a `struct tm` to time in seconds (assuming UTC). */
SFUNC time_t fio_gm2time(struct tm tm) {
int64_t time = 0;
// we start with the algorithm described here:
// http://howardhinnant.github.io/date_algorithms.html#days_from_civil
// Credit to <NAME>.
{
const int32_t y = (tm.tm_year + 1900) - (tm.tm_mon < 2);
const int32_t era = (y >= 0 ? y : y - 399) / 400;
const uint16_t yoe = (y - era * 400L); // 0-399
const uint32_t doy =
(153L * (tm.tm_mon + (tm.tm_mon > 1 ? -2 : 10)) + 2) / 5 + tm.tm_mday -
1; // 0-365
const uint32_t doe = yoe * 365L + yoe / 4 - yoe / 100 + doy; // 0-146096
time = era * 146097LL + doe - 719468LL; // time == days from epoch
}
/* Adjust for hour, minute and second */
time = time * 24LL + tm.tm_hour;
time = time * 60LL + tm.tm_min;
time = time * 60LL + tm.tm_sec;
if (tm.tm_isdst > 0) {
time -= 60 * 60;
}
#if HAVE_TM_TM_ZONE || defined(BSD)
if (tm.tm_gmtoff) {
time += tm.tm_gmtoff;
}
#endif
return (time_t)time;
}
static const char *FIO___DAY_NAMES[] =
{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
// clang-format off
static const char *FIO___MONTH_NAMES[] =
{"Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ",
"Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "};
// clang-format on
static const char *FIO___GMT_STR = "GMT";
/** Writes an RFC 7231 date representation (HTTP date format) to target. */
SFUNC size_t fio_time2rfc7231(char *target, time_t time) {
const struct tm tm = fio_time2gm(time);
/* note: day of month is always 2 digits */
char *pos = target;
uint16_t tmp;
pos[0] = FIO___DAY_NAMES[tm.tm_wday][0];
pos[1] = FIO___DAY_NAMES[tm.tm_wday][1];
pos[2] = FIO___DAY_NAMES[tm.tm_wday][2];
pos[3] = ',';
pos[4] = ' ';
pos += 5;
tmp = tm.tm_mday / 10;
pos[0] = '0' + tmp;
pos[1] = '0' + (tm.tm_mday - (tmp * 10));
pos += 2;
*(pos++) = ' ';
pos[0] = FIO___MONTH_NAMES[tm.tm_mon][0];
pos[1] = FIO___MONTH_NAMES[tm.tm_mon][1];
pos[2] = FIO___MONTH_NAMES[tm.tm_mon][2];
pos[3] = ' ';
pos += 4;
// write year.
pos += fio_ltoa(pos, tm.tm_year + 1900, 10);
*(pos++) = ' ';
tmp = tm.tm_hour / 10;
pos[0] = '0' + tmp;
pos[1] = '0' + (tm.tm_hour - (tmp * 10));
pos[2] = ':';
tmp = tm.tm_min / 10;
pos[3] = '0' + tmp;
pos[4] = '0' + (tm.tm_min - (tmp * 10));
pos[5] = ':';
tmp = tm.tm_sec / 10;
pos[6] = '0' + tmp;
pos[7] = '0' + (tm.tm_sec - (tmp * 10));
pos += 8;
pos[0] = ' ';
pos[1] = FIO___GMT_STR[0];
pos[2] = FIO___GMT_STR[1];
pos[3] = FIO___GMT_STR[2];
pos[4] = 0;
pos += 4;
return pos - target;
}
/** Writes an RFC 2109 date representation to target. */
SFUNC size_t fio_time2rfc2109(char *target, time_t time) {
const struct tm tm = fio_time2gm(time);
/* note: day of month is always 2 digits */
char *pos = target;
uint16_t tmp;
pos[0] = FIO___DAY_NAMES[tm.tm_wday][0];
pos[1] = FIO___DAY_NAMES[tm.tm_wday][1];
pos[2] = FIO___DAY_NAMES[tm.tm_wday][2];
pos[3] = ',';
pos[4] = ' ';
pos += 5;
tmp = tm.tm_mday / 10;
pos[0] = '0' + tmp;
pos[1] = '0' + (tm.tm_mday - (tmp * 10));
pos += 2;
*(pos++) = ' ';
pos[0] = FIO___MONTH_NAMES[tm.tm_mon][0];
pos[1] = FIO___MONTH_NAMES[tm.tm_mon][1];
pos[2] = FIO___MONTH_NAMES[tm.tm_mon][2];
pos[3] = ' ';
pos += 4;
// write year.
pos += fio_ltoa(pos, tm.tm_year + 1900, 10);
*(pos++) = ' ';
tmp = tm.tm_hour / 10;
pos[0] = '0' + tmp;
pos[1] = '0' + (tm.tm_hour - (tmp * 10));
pos[2] = ':';
tmp = tm.tm_min / 10;
pos[3] = '0' + tmp;
pos[4] = '0' + (tm.tm_min - (tmp * 10));
pos[5] = ':';
tmp = tm.tm_sec / 10;
pos[6] = '0' + tmp;
pos[7] = '0' + (tm.tm_sec - (tmp * 10));
pos += 8;
*pos++ = ' ';
*pos++ = '-';
*pos++ = '0';
*pos++ = '0';
*pos++ = '0';
*pos++ = '0';
*pos = 0;
return pos - target;
}
/** Writes an RFC 2822 date representation to target. */
SFUNC size_t fio_time2rfc2822(char *target, time_t time) {
const struct tm tm = fio_time2gm(time);
/* note: day of month is either 1 or 2 digits */
char *pos = target;
uint16_t tmp;
pos[0] = FIO___DAY_NAMES[tm.tm_wday][0];
pos[1] = FIO___DAY_NAMES[tm.tm_wday][1];
pos[2] = FIO___DAY_NAMES[tm.tm_wday][2];
pos[3] = ',';
pos[4] = ' ';
pos += 5;
if (tm.tm_mday < 10) {
*pos = '0' + tm.tm_mday;
++pos;
} else {
tmp = tm.tm_mday / 10;
pos[0] = '0' + tmp;
pos[1] = '0' + (tm.tm_mday - (tmp * 10));
pos += 2;
}
*(pos++) = '-';
pos[0] = FIO___MONTH_NAMES[tm.tm_mon][0];
pos[1] = FIO___MONTH_NAMES[tm.tm_mon][1];
pos[2] = FIO___MONTH_NAMES[tm.tm_mon][2];
pos += 3;
*(pos++) = '-';
// write year.
pos += fio_ltoa(pos, tm.tm_year + 1900, 10);
*(pos++) = ' ';
tmp = tm.tm_hour / 10;
pos[0] = '0' + tmp;
pos[1] = '0' + (tm.tm_hour - (tmp * 10));
pos[2] = ':';
tmp = tm.tm_min / 10;
pos[3] = '0' + tmp;
pos[4] = '0' + (tm.tm_min - (tmp * 10));
pos[5] = ':';
tmp = tm.tm_sec / 10;
pos[6] = '0' + tmp;
pos[7] = '0' + (tm.tm_sec - (tmp * 10));
pos += 8;
pos[0] = ' ';
pos[1] = FIO___GMT_STR[0];
pos[2] = FIO___GMT_STR[1];
pos[3] = FIO___GMT_STR[2];
pos[4] = 0;
pos += 4;
return pos - target;
}
/**
* Writes a date representation to target in common log format. i.e.,
*
* [DD/MMM/yyyy:hh:mm:ss +0000]
*
* Usually requires 29 characters (includiing square brackes and NUL).
*/
SFUNC size_t fio_time2log(char *target, time_t time) {
{
const struct tm tm = fio_time2gm(time);
/* note: day of month is either 1 or 2 digits */
char *pos = target;
uint16_t tmp;
*(pos++) = '[';
tmp = tm.tm_mday / 10;
*(pos++) = '0' + tmp;
*(pos++) = '0' + (tm.tm_mday - (tmp * 10));
*(pos++) = '/';
*(pos++) = FIO___MONTH_NAMES[tm.tm_mon][0];
*(pos++) = FIO___MONTH_NAMES[tm.tm_mon][1];
*(pos++) = FIO___MONTH_NAMES[tm.tm_mon][2];
*(pos++) = '/';
pos += fio_ltoa(pos, tm.tm_year + 1900, 10);
*(pos++) = ':';
tmp = tm.tm_hour / 10;
*(pos++) = '0' + tmp;
*(pos++) = '0' + (tm.tm_hour - (tmp * 10));
*(pos++) = ':';
tmp = tm.tm_min / 10;
*(pos++) = '0' + tmp;
*(pos++) = '0' + (tm.tm_min - (tmp * 10));
*(pos++) = ':';
tmp = tm.tm_sec / 10;
*(pos++) = '0' + tmp;
*(pos++) = '0' + (tm.tm_sec - (tmp * 10));
*(pos++) = ' ';
*(pos++) = '+';
*(pos++) = '0';
*(pos++) = '0';
*(pos++) = '0';
*(pos++) = '0';
*(pos++) = ']';
*(pos) = 0;
return pos - target;
}
}
/* *****************************************************************************
Time - test
***************************************************************************** */
#ifdef FIO_TEST_CSTL
#define FIO___GMTIME_TEST_INTERVAL ((60LL * 60 * 23) + 1027) /* 23:17:07 */
#if 1 || FIO_OS_WIN
#define FIO___GMTIME_TEST_RANGE (1001LL * 376) /* test 0.5 millenia */
#else
#define FIO___GMTIME_TEST_RANGE (3003LL * 376) /* test ~3 millenia */
#endif
FIO_SFUNC void FIO_NAME_TEST(stl, time)(void) {
fprintf(stderr, "* Testing facil.io fio_time2gm vs gmtime_r\n");
struct tm tm1, tm2;
const time_t now = fio_time_real().tv_sec;
#if FIO_OS_WIN
const time_t end = (FIO___GMTIME_TEST_RANGE * FIO___GMTIME_TEST_INTERVAL);
time_t t = 1; /* Windows fails on some date ranges. */
#else
const time_t end =
now + (FIO___GMTIME_TEST_RANGE * FIO___GMTIME_TEST_INTERVAL);
time_t t = now - (FIO___GMTIME_TEST_RANGE * FIO___GMTIME_TEST_INTERVAL);
#endif
FIO_ASSERT(t < end, "time testing range overflowed.");
do {
time_t tmp = t;
t += FIO___GMTIME_TEST_INTERVAL;
tm2 = fio_time2gm(tmp);
FIO_ASSERT(fio_gm2time(tm2) == tmp,
"fio_gm2time roundtrip error (%zu != %zu)",
(size_t)fio_gm2time(tm2),
(size_t)tmp);
gmtime_r(&tmp, &tm1);
if (tm1.tm_year != tm2.tm_year || tm1.tm_mon != tm2.tm_mon ||
tm1.tm_mday != tm2.tm_mday || tm1.tm_yday != tm2.tm_yday ||
tm1.tm_hour != tm2.tm_hour || tm1.tm_min != tm2.tm_min ||
tm1.tm_sec != tm2.tm_sec || tm1.tm_wday != tm2.tm_wday) {
char buf[256];
FIO_LOG_ERROR("system gmtime_r != fio_time2gm for %ld!\n", (long)t);
fio_time2rfc7231(buf, tmp);
FIO_ASSERT(0,
"\n"
"-- System:\n"
"\ttm_year: %d\n"
"\ttm_mon: %d\n"
"\ttm_mday: %d\n"
"\ttm_yday: %d\n"
"\ttm_hour: %d\n"
"\ttm_min: %d\n"
"\ttm_sec: %d\n"
"\ttm_wday: %d\n"
"-- facil.io:\n"
"\ttm_year: %d\n"
"\ttm_mon: %d\n"
"\ttm_mday: %d\n"
"\ttm_yday: %d\n"
"\ttm_hour: %d\n"
"\ttm_min: %d\n"
"\ttm_sec: %d\n"
"\ttm_wday: %d\n"
"-- As String:\n"
"\t%s",
tm1.tm_year,
tm1.tm_mon,
tm1.tm_mday,
tm1.tm_yday,
tm1.tm_hour,
tm1.tm_min,
tm1.tm_sec,
tm1.tm_wday,
tm2.tm_year,
tm2.tm_mon,
tm2.tm_mday,
tm2.tm_yday,
tm2.tm_hour,
tm2.tm_min,
tm2.tm_sec,
tm2.tm_wday,
buf);
}
} while (t < end);
{
char buf[48];
buf[47] = 0;
memset(buf, 'X', 47);
fio_time2rfc7231(buf, now);
FIO_LOG_DEBUG2("fio_time2rfc7231: %s", buf);
memset(buf, 'X', 47);
fio_time2rfc2109(buf, now);
FIO_LOG_DEBUG2("fio_time2rfc2109: %s", buf);
memset(buf, 'X', 47);
fio_time2rfc2822(buf, now);
FIO_LOG_DEBUG2("fio_time2rfc2822: %s", buf);
memset(buf, 'X', 47);
fio_time2log(buf, now);
FIO_LOG_DEBUG2("fio_time2log: %s", buf);
}
{
uint64_t start, stop;
#if DEBUG
fprintf(stderr, "PERFOMEANCE TESTS IN DEBUG MODE ARE BIASED\n");
#endif
fprintf(stderr, " performance testing fio_time2gm vs gmtime_r\n");
start = fio_time_micro();
for (size_t i = 0; i < (1 << 17); ++i) {
volatile struct tm tm = fio_time2gm(now);
FIO_COMPILER_GUARD;
(void)tm;
}
stop = fio_time_micro();
fprintf(stderr,
"\t- fio_time2gm speed test took:\t%zuus\n",
(size_t)(stop - start));
start = fio_time_micro();
for (size_t i = 0; i < (1 << 17); ++i) {
volatile struct tm tm;
time_t tmp = now;
gmtime_r(&tmp, (struct tm *)&tm);
FIO_COMPILER_GUARD;
}
stop = fio_time_micro();
fprintf(stderr,
"\t- gmtime_r speed test took: \t%zuus\n",
(size_t)(stop - start));
fprintf(stderr, "\n");
struct tm tm_now = fio_time2gm(now);
start = fio_time_micro();
for (size_t i = 0; i < (1 << 17); ++i) {
tm_now = fio_time2gm(now + i);
time_t t_tmp = fio_gm2time(tm_now);
FIO_COMPILER_GUARD;
(void)t_tmp;
}
stop = fio_time_micro();
fprintf(stderr,
"\t- fio_gm2time speed test took:\t%zuus\n",
(size_t)(stop - start));
start = fio_time_micro();
for (size_t i = 0; i < (1 << 17); ++i) {
tm_now = fio_time2gm(now + i);
volatile time_t t_tmp = mktime((struct tm *)&tm_now);
FIO_COMPILER_GUARD;
(void)t_tmp;
}
stop = fio_time_micro();
fprintf(stderr,
"\t- mktime speed test took: \t%zuus\n",
(size_t)(stop - start));
fprintf(stderr, "\n");
}
}
#undef FIO___GMTIME_TEST_INTERVAL
#undef FIO___GMTIME_TEST_RANGE
#endif /* FIO_TEST_CSTL */
/* *****************************************************************************
Time Cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE */
#undef FIO_TIME
#endif /* FIO_TIME */
|
janbiedermann/cstl
|
stl_slices/000 header.h
|
<reponame>janbiedermann/cstl
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
********************************************************************************
********************************************************************************
NOTE: this file is auto-generated from: https://github.com/facil-io/cstl
***************************************************************************** */
/** ****************************************************************************
# facil.io's C STL - Simple (type) Template Library
This file contains macros that create generic / common core types, such as:
* Linked Lists - defined by `FIO_LIST_NAME`
* Dynamic Arrays - defined by `FIO_ARRAY_NAME`
* Hash Maps / Sets - defined by `FIO_MAP_NAME`
* Binary Safe Dynamic Strings - defined by `FIO_STR_NAME` or `FIO_STR_SMALL`
* Reference counting / Type wrapper - defined by `FIO_REF_NAME` (adds atomic)
* Pointer Tagging for Types - defined by `FIO_PTR_TAG(p)`/`FIO_PTR_UNTAG(p)`
* Soft / Dynamic Types (FIOBJ) - defined by `FIO_FIOBJ`
This file also contains common helper macros / primitives, such as:
* Macro Stringifier - `FIO_MACRO2STR(macro)`
* Version Macros - i.e., `FIO_VERSION_MAJOR` / `FIO_VERSION_STRING`
* Pointer Math - i.e., `FIO_PTR_MATH_ADD` / `FIO_PTR_FROM_FIELD`
* Memory Allocation Macros - i.e., `FIO_MEM_REALLOC`
* Security Related macros - i.e., `FIO_MEM_STACK_WIPE`
* String Information Helper Type - `fio_str_info_s` / `FIO_STR_INFO_IS_EQ`
* Naming Macros - i.e., `FIO_NAME` / `FIO_NAME2` / `FIO_NAME_BL`
* Sleep / Thread Scheduling Macros - i.e., `FIO_THREAD_RESCHEDULE`
* Logging and Assertion (no heap allocation) - defined by `FIO_LOG`
* Atomic add/subtract/replace - defined by `FIO_ATOMIC`
* Bit-Byte Operations - defined by `FIO_BITWISE` and `FIO_BITMAP` (adds atomic)
* Data Hashing (using Risky Hash) - defined by `FIO_RISKY_HASH`
* Psedo Random Generation - defined by `FIO_RAND`
* String / Number conversion - defined by `FIO_ATOL`
* Time Helpers - defined by `FIO_TIME`
* Task / Timer Queues (Event Loop Engine) - defined by `FIO_QUEUE`
* Command Line Interface helpers - defined by `FIO_CLI`
* Socket Helpers - defined by `FIO_SOCK`
* Data Stream Containers - defined by `FIO_STREAM`
* Signal (passthrough) Monitors - defined by `FIO_SIGNAL`
* Custom Memory Pool / Allocation - defined by `FIO_MEMORY_NAME` / `FIO_MALLOC`,
if `FIO_MALLOC` is used, it updates `FIO_MEM_REALLOC` etc'
* Custom JSON Parser - defined by `FIO_JSON`
However, this file does very little unless specifically requested.
To make sure this file defines a specific macro or type, it's macro should be
set.
In addition, if the `FIO_TEST_CSTL` macro is defined, the self-testing function
`fio_test_dynamic_types()` will be defined. the `fio_test_dynamic_types`
function will test the functionality of this file and, as consequence, will
define all available macros.
**Notes**:
- To make this file usable for kernel authoring, the `include` statements should
be reviewed.
- To make these functions safe for kernel authoring, the `FIO_MEM_REALLOC` and
`FIO_MEM_FREE` macros should be (re)-defined.
These macros default to using the `realloc` and `free` functions calls. If
`FIO_MALLOC` was defined, these macros will default to the custom memory
allocator.
- To make the custom memory allocator safe for kernel authoring, the
`FIO_MEM_PAGE_ALLOC`, `FIO_MEM_PAGE_REALLOC` and `FIO_MEM_PAGE_FREE` macros
should be redefined. These macros default to using `mmap` and `munmap` (on
linux, also `mremap`).
- The functions defined using this file default to `static` or `static
inline`.
To create an externally visible API, define the `FIO_EXTERN`. Define the
`FIO_EXTERN_COMPLETE` macro to include the API's implementation as well.
- To implement a library style version guard, define the `FIO_VERSION_GUARD`
macro in a single translation unit (.c file) **before** including this STL
library for the first time.
***************************************************************************** */
/* *****************************************************************************
C++ extern start
***************************************************************************** */
/* support C++ */
#ifdef __cplusplus
extern "C" {
/* C++ keyword was deprecated */
#ifndef register
#define register
#endif
/* C keyword - unavailable in C++ */
#ifndef restrict
#define restrict
#endif
#endif
/* *****************************************************************************
Constants (included once)
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H
#define H___FIO_CSTL_INCLUDE_ONCE_H
/* *****************************************************************************
Compiler detection, GCC / CLang features and OS dependent included files
***************************************************************************** */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#if !defined(__GNUC__) && !defined(__clang__) && !defined(GNUC_BYPASS)
#define __attribute__(...)
#define __has_include(...) 0
#define __has_builtin(...) 0
#define GNUC_BYPASS 1
#elif !defined(__clang__) && !defined(__has_builtin)
/* E.g: GCC < 6.0 doesn't support __has_builtin */
#define __has_builtin(...) 0
#define GNUC_BYPASS 1
#endif
#ifndef __has_include
#define __has_include(...) 0
#define GNUC_BYPASS 1
#endif
#if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5))
/* GCC < 4.5 doesn't support deprecation reason string */
#define DEPRECATED(reason) __attribute__((deprecated))
#else
#define DEPRECATED(reason) __attribute__((deprecated(reason)))
#endif
#if defined(__GNUC__) || defined(__clang__)
#define FIO_ALIGN(bytes) __attribute__((aligned(bytes)))
#elif defined(__INTEL_COMPILER) || defined(_MSC_VER)
#define FIO_ALIGN(bytes) __declspec(align(bytes))
#else
#define FIO_ALIGN(bytes)
#endif
#if _MSC_VER
#define __thread __declspec(thread)
#elif !defined(__clang__) && !defined(__GNUC__)
#define __thread _Thread_value
#endif
#if defined(__clang__) || defined(__GNUC__)
/** Clobber CPU registers and prevent compiler reordering optimizations. */
#define FIO_COMPILER_GUARD __asm__ volatile("" ::: "memory")
#elif defined(_MSC_VER)
#include <intrin.h>
/** Clobber CPU registers and prevent compiler reordering optimizations. */
#define FIO_COMPILER_GUARD _ReadWriteBarrier()
#pragma message("Warning: Windows deprecated it's low-level C memory barrier.")
#else
#warning Unknown OS / compiler, some macros are poorly defined and errors might occur.
#define FIO_COMPILER_GUARD asm volatile("" ::: "memory")
#endif
#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)
#define FIO_HAVE_UNIX_TOOLS 1
#define FIO_OS_POSIX 1
#define FIO___PRINTF_STYLE printf
#elif defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
defined(__MINGW32__) || defined(__BORLANDC__)
#define FIO_OS_WIN 1
#define POSIX_C_SOURCE 200809L
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#if defined(__MINGW32__)
/* Mingw supports */
#define FIO_HAVE_UNIX_TOOLS 2
#define __USE_MINGW_ANSI_STDIO 1
#define FIO___PRINTF_STYLE __MINGW_PRINTF_FORMAT
#elif defined(__CYGWIN__)
/* TODO: cygwin support */
#define FIO_HAVE_UNIX_TOOLS 3
#define __USE_MINGW_ANSI_STDIO 1
#define FIO___PRINTF_STYLE __MINGW_PRINTF_FORMAT
#else
#define FIO_HAVE_UNIX_TOOLS 0
typedef SSIZE_T ssize_t;
#endif /* __CYGWIN__ __MINGW32__ */
#else
#define FIO_HAVE_UNIX_TOOLS 0
#warning Unknown OS / compiler, some macros are poorly defined and errors might occur.
#endif
#include <ctype.h>
#include <errno.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#ifndef CLOCK_REALTIME
#define CLOCK_REALTIME 0
#endif
#ifndef CLOCK_MONOTONIC
#define CLOCK_MONOTONIC 0
#endif
#if FIO_HAVE_UNIX_TOOLS
#include <sys/param.h>
#include <unistd.h>
#endif
#if FIO_UNALIGNED_ACCESS && \
(__amd64 || __amd64__ || __x86_64 || __x86_64__ || __i386 || \
__aarch64__ || _M_IX86 || _M_X64 || _M_ARM64)
#define FIO_UNALIGNED_MEMORY_ACCESS_ENABLED 1
#else
#define FIO_UNALIGNED_MEMORY_ACCESS_ENABLED 0
#endif
/* memcpy selectors / overriding */
#ifndef FIO_MEMCPY
#if __has_builtin(__builtin_memcpy)
#define FIO_MEMCPY __builtin_memcpy
#else
#define FIO_MEMCPY memcpy
#endif
#endif
/* *****************************************************************************
Function Attributes
***************************************************************************** */
/** Marks a function as `static`, `inline` and possibly unused. */
#define FIO_IFUNC static inline __attribute__((unused))
/** Marks a function as `static` and possibly unused. */
#define FIO_SFUNC static __attribute__((unused))
/** Marks a function as weak */
#define FIO_WEAK __attribute__((weak))
#if _MSC_VER
#pragma section(".CRT$XCU", read)
#undef FIO_CONSTRUCTOR
/** Marks a function as a constructor - if supported. */
#if _WIN64 /* MSVC linker uses different name mangling on 32bit systems */
#define FIO___CONSTRUCTOR_INTERNAL(fname) \
static void fname(void); \
__pragma(comment(linker, "/include:" #fname "__")); /* and next.... */ \
__declspec(allocate(".CRT$XCU")) void (*fname##__)(void) = fname; \
static void fname(void)
#else
#define FIO___CONSTRUCTOR_INTERNAL(fname) \
static void fname(void); \
__declspec(allocate(".CRT$XCU")) void (*fname##__)(void) = fname; \
__pragma(comment(linker, "/include:_" #fname "__")); /* and next.... */ \
static void fname(void)
#endif
#define FIO_CONSTRUCTOR(fname) FIO___CONSTRUCTOR_INTERNAL(fname)
#else
/** Marks a function as a constructor - if supported. */
#define FIO_CONSTRUCTOR(fname) \
FIO_SFUNC __attribute__((constructor)) void fname FIO_NOOP(void)
#endif
/** Marks a function as a destructor - if supported. Consider using atexit() */
#define FIO_DESTRUCTOR(fname) \
FIO_SFUNC \
__attribute__((destructor)) void fname FIO_NOOP(void)
/* *****************************************************************************
Macro Stringifier
***************************************************************************** */
#ifndef FIO_MACRO2STR
#define FIO_MACRO2STR_STEP2(macro) #macro
/** Converts a macro's content to a string literal. */
#define FIO_MACRO2STR(macro) FIO_MACRO2STR_STEP2(macro)
#endif
/* *****************************************************************************
Conditional Likelihood
***************************************************************************** */
#if defined(__clang__) || defined(__GNUC__)
#define FIO_LIKELY(cond) __builtin_expect((cond), 1)
#define FIO_UNLIKELY(cond) __builtin_expect((cond), 0)
#else
#define FIO_LIKELY(cond) (cond)
#define FIO_UNLIKELY(cond) (cond)
#endif
/* *****************************************************************************
Naming Macros
***************************************************************************** */
/* Used for naming functions and types */
#define FIO_NAME_FROM_MACRO_STEP2(prefix, postfix, div) prefix##div##postfix
#define FIO_NAME_FROM_MACRO_STEP1(prefix, postfix, div) \
FIO_NAME_FROM_MACRO_STEP2(prefix, postfix, div)
/** Used for naming functions and variables resulting in: prefix_postfix */
#define FIO_NAME(prefix, postfix) FIO_NAME_FROM_MACRO_STEP1(prefix, postfix, _)
/** Sets naming convention for conversion functions, i.e.: foo2bar */
#define FIO_NAME2(prefix, postfix) FIO_NAME_FROM_MACRO_STEP1(prefix, postfix, 2)
/** Sets naming convention for boolean testing functions, i.e.: foo_is_true */
#define FIO_NAME_BL(prefix, postfix) \
FIO_NAME_FROM_MACRO_STEP1(prefix, postfix, _is_)
/** Used internally to name test functions. */
#define FIO_NAME_TEST(prefix, postfix) \
FIO_NAME(fio___test, FIO_NAME(prefix, postfix))
/* *****************************************************************************
Version Macros
The facil.io C STL library follows [semantic versioning](https://semver.org) and
supports macros that will help detect and validate it's version.
***************************************************************************** */
/** MAJOR version: API/ABI breaking changes. */
#define FIO_VERSION_MAJOR 0
/** MINOR version: Deprecation, or significant features added. May break ABI. */
#define FIO_VERSION_MINOR 8
/** PATCH version: Bug fixes, minor features may be added. */
#define FIO_VERSION_PATCH 0
/** BETA version: pre-version development marker. Nothing is stable. */
#define FIO_VERSION_BETA 1
#if FIO_VERSION_BETA
/** Version as a String literal (MACRO). */
#define FIO_VERSION_STRING \
FIO_MACRO2STR(FIO_VERSION_MAJOR) \
"." FIO_MACRO2STR(FIO_VERSION_MINOR) "." FIO_MACRO2STR( \
FIO_VERSION_PATCH) ".beta" FIO_MACRO2STR(FIO_VERSION_BETA)
#else
/** Version as a String literal (MACRO). */
#define FIO_VERSION_STRING \
FIO_MACRO2STR(FIO_VERSION_MAJOR) \
"." FIO_MACRO2STR(FIO_VERSION_MINOR) "." FIO_MACRO2STR(FIO_VERSION_PATCH)
#endif
/** If implemented, returns the major version number. */
size_t fio_version_major(void);
/** If implemented, returns the minor version number. */
size_t fio_version_minor(void);
/** If implemented, returns the patch version number. */
size_t fio_version_patch(void);
/** If implemented, returns the beta version number. */
size_t fio_version_beta(void);
/** If implemented, returns the version number as a string. */
char *fio_version_string(void);
#define FIO_VERSION_VALIDATE() \
FIO_ASSERT(fio_version_major() == FIO_VERSION_MAJOR && \
fio_version_minor() == FIO_VERSION_MINOR && \
fio_version_patch() == FIO_VERSION_PATCH && \
fio_version_beta() == FIO_VERSION_BETA, \
"facil.io version mismatch, not %s", \
fio_version_string())
/**
* To implement the fio_version_* functions and FIO_VERSION_VALIDATE guard, the
* `FIO_VERSION_GUARD` must be defined (only) once per application / library.
*/
#ifdef FIO_VERSION_GUARD
size_t __attribute__((weak)) fio_version_major(void) {
return FIO_VERSION_MAJOR;
}
size_t __attribute__((weak)) fio_version_minor(void) {
return FIO_VERSION_MINOR;
}
size_t __attribute__((weak)) fio_version_patch(void) {
return FIO_VERSION_PATCH;
}
size_t __attribute__((weak)) fio_version_beta(void) { return FIO_VERSION_BETA; }
char *__attribute__((weak)) fio_version_string(void) {
return FIO_VERSION_STRING;
}
#undef FIO_VERSION_GUARD
#endif /* FIO_VERSION_GUARD */
#if !defined(FIO_NO_COOKIE)
/** If implemented, does stuff. */
void __attribute__((weak)) fio___(void) {
volatile uint8_t tmp[] =
"\xA8\x94\x9A\x10\x99\x92\x93\x96\x9C\x1D\x96\x9F\x10\x9C\x96\x91\xB1\x92"
"\xB1\xB6\x10\xBB\x92\xB3\x10\x92\xBA\xB8\x94\x9F\xB1\x9A\x98\x10\x91\xB6"
"\x10\x81\x9F\x92\xB5\x10\xA3\x9A\x9B\x9A\xB9\x1D\x05\x10\x10\x10\x10\x8C"
"\x96\xB9\x9A\x10\x9C\x9F\x9D\x9B\x10\x92\x9D\x98\x10\xB0\xB1\x9F\xB3\xB0"
"\x9A\xB1\x1D";
for (size_t i = 0; tmp[i]; ++i) {
tmp[i] = ((tmp[i] & 0x55) << 1) | ((tmp[i] & 0xaa) >> 1);
}
fprintf(stderr, "%s\n", tmp);
}
#endif
/* *****************************************************************************
Pointer Math
***************************************************************************** */
/** Masks a pointer's left-most bits, returning the right bits. */
#define FIO_PTR_MATH_LMASK(T_type, ptr, bits) \
((T_type *)((uintptr_t)(ptr) & (((uintptr_t)1 << (bits)) - 1)))
/** Masks a pointer's right-most bits, returning the left bits. */
#define FIO_PTR_MATH_RMASK(T_type, ptr, bits) \
((T_type *)((uintptr_t)(ptr) & ((~(uintptr_t)0) << (bits))))
/** Add offset bytes to pointer, updating the pointer's type. */
#define FIO_PTR_MATH_ADD(T_type, ptr, offset) \
((T_type *)((uintptr_t)(ptr) + (uintptr_t)(offset)))
/** Subtract X bytes from pointer, updating the pointer's type. */
#define FIO_PTR_MATH_SUB(T_type, ptr, offset) \
((T_type *)((uintptr_t)(ptr) - (uintptr_t)(offset)))
/** Find the root object (of a struct) from it's field. */
#define FIO_PTR_FROM_FIELD(T_type, field, ptr) \
FIO_PTR_MATH_SUB(T_type, ptr, (&((T_type *)0)->field))
/* *****************************************************************************
Security Related macros
***************************************************************************** */
#define FIO_MEM_STACK_WIPE(pages) \
do { \
volatile char stack_mem[(pages) << 12] = {0}; \
(void)stack_mem; \
} while (0)
/* *****************************************************************************
String Information Helper Type
***************************************************************************** */
/** An information type for reporting the string's state. */
typedef struct fio_str_info_s {
/** The string's buffer (pointer to first byte) or NULL on error. */
char *buf;
/** The string's length, if any. */
size_t len;
/** The buffer's capacity. Zero (0) indicates the buffer is read-only. */
size_t capa;
} fio_str_info_s;
/** An information type for reporting/storing buffer data. */
typedef struct fio_buf_info_s {
/** The string's buffer (pointer to first byte) or NULL on error. */
char *buf;
/** The string's length, if any. */
size_t len;
} fio_buf_info_s;
/** Compares two `fio_str_info_s` objects for content equality. */
#define FIO_STR_INFO_IS_EQ(s1, s2) \
((s1).len == (s2).len && (!(s1).len || (s1).buf == (s2).buf || \
!memcmp((s1).buf, (s2).buf, (s1).len)))
/* *****************************************************************************
Linked Lists Persistent Macros and Types
***************************************************************************** */
/** A common linked list node type. */
typedef struct fio___list_node_s {
struct fio___list_node_s *next;
struct fio___list_node_s *prev;
} fio___list_node_s;
/** A linked list node type */
#define FIO_LIST_NODE fio___list_node_s
/** A linked list head type */
#define FIO_LIST_HEAD fio___list_node_s
/** Allows initialization of FIO_LIST_HEAD objects. */
#define FIO_LIST_INIT(obj) \
(obj) = (fio___list_node_s) { .next = &(obj), .prev = &(obj) }
#ifndef FIO_LIST_EACH
/** Loops through every node in the linked list except the head. */
#define FIO_LIST_EACH(type, node_name, head, pos) \
for (type *pos = FIO_PTR_FROM_FIELD(type, node_name, (head)->next), \
*next____p_ls = \
FIO_PTR_FROM_FIELD(type, node_name, (head)->next->next); \
pos != FIO_PTR_FROM_FIELD(type, node_name, (head)); \
(pos = next____p_ls), \
(next____p_ls = FIO_PTR_FROM_FIELD(type, \
node_name, \
next____p_ls->node_name.next)))
#endif
/** UNSAFE macro for pushing a node to a list. */
#define FIO_LIST_PUSH(head, n) \
do { \
(n)->prev = (head)->prev; \
(n)->next = (head); \
(head)->prev->next = (n); \
(head)->prev = (n); \
} while (0)
/** UNSAFE macro for removing a node from a list. */
#define FIO_LIST_REMOVE(n) \
do { \
(n)->prev->next = (n)->next; \
(n)->next->prev = (n)->prev; \
(n)->next = (n)->prev = NULL; \
} while (0)
/* *****************************************************************************
Indexed Linked Lists Persistent Macros and Types
Indexed Linked Lists can be used to create a linked list that uses is always
relative to some root pointer (usually the root of an array). This:
1. Allows easy reallocation of the list without requiring pointer updates.
2. Could be used for memory optimization if the array limits are known.
The "head" index is usualy validated by reserving the value of `-1` to indicate
an empty list.
***************************************************************************** */
#ifndef FIO_INDEXED_LIST_EACH
/** A common linked list node type. */
typedef struct fio___index32_node_s {
uint32_t next;
uint32_t prev;
} fio___index32_node_s;
/** A linked list node type */
#define FIO_INDEXED_LIST32_NODE fio___index32_node_s
#define FIO_INDEXED_LIST32_HEAD uint32_t
/** UNSAFE macro for pushing a node to a list. */
#define FIO_INDEXED_LIST_PUSH(root, node_name, head, i) \
do { \
register const size_t n__ = (i); \
(root)[n__].node_name.prev = (root)[(head)].node_name.prev; \
(root)[n__].node_name.next = (head); \
(root)[(root)[(head)].node_name.prev].node_name.next = n__; \
(root)[(head)].node_name.prev = n__; \
} while (0)
/** UNSAFE macro for removing a node from a list. */
#define FIO_INDEXED_LIST_REMOVE(root, node_name, i) \
do { \
register const size_t n__ = (i); \
(root)[(root)[n__].node_name.prev].node_name.next = \
(root)[n__].node_name.next; \
(root)[(root)[n__].node_name.next].node_name.prev = \
(root)[n__].node_name.prev; \
(root)[n__].node_name.next = (root)[n__].node_name.prev = n__; \
} while (0)
/** Loops through every index in the indexed list, assuming `head` is valid. */
#define FIO_INDEXED_LIST_EACH(root, node_name, head, pos) \
for (size_t pos = (head), stopper___ils___ = 0; !stopper___ils___; \
stopper___ils___ = ((pos = (root)[pos].node_name.next) == (head)))
#endif
/* *****************************************************************************
Sleep / Thread Scheduling Macros
***************************************************************************** */
#ifndef FIO_THREAD_WAIT
#if FIO_OS_WIN
/**
* Calls NtDelayExecution with the requested nano-second count.
*/
#define FIO_THREAD_WAIT(nano_sec) \
do { \
Sleep(((nano_sec) / 1000000) ? ((nano_sec) / 1000000) : 1); \
} while (0)
// https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep
#elif FIO_OS_POSIX
/**
* Calls nonsleep with the requested nano-second count.
*/
#define FIO_THREAD_WAIT(nano_sec) \
do { \
const struct timespec tm = {.tv_sec = (time_t)((nano_sec) / 1000000000), \
.tv_nsec = ((long)(nano_sec) % 1000000000)}; \
nanosleep(&tm, (struct timespec *)NULL); \
} while (0)
#endif
#endif
#ifndef FIO_THREAD_RESCHEDULE
/**
* Reschedules the thread by calling nanosleeps for a sinlge nano-second.
*
* In practice, the thread will probably sleep for 60ns or more.
*/
#define FIO_THREAD_RESCHEDULE() FIO_THREAD_WAIT(4)
#endif
/* *****************************************************************************
Miscellaneous helper macros
***************************************************************************** */
/* avoid printing a full / nested path when __FILE_NAME__ is available */
#ifdef __FILE_NAME__
#define FIO__FILE__ __FILE_NAME__
#else
#define FIO__FILE__ __FILE__
#endif
/** An empty macro, adding white space. Used to avoid function like macros. */
#define FIO_NOOP
/* allow logging to quitely fail unless enabled */
#define FIO_LOG_DEBUG(...)
#define FIO_LOG_DEBUG2(...)
#define FIO_LOG_INFO(...)
#define FIO_LOG_WARNING(...)
#define FIO_LOG_ERROR(...)
#define FIO_LOG_SECURITY(...)
#define FIO_LOG_FATAL(...)
#define FIO_LOG2STDERR(...)
#define FIO_LOG2STDERR2(...)
#define FIO_LOG_PRINT__(...)
#ifndef FIO_LOG_LENGTH_LIMIT
/** Defines a point at which logging truncates (limited by stack memory) */
#define FIO_LOG_LENGTH_LIMIT 1024
#endif
// clang-format off
/* Asserts a condition is true, or kills the application using SIGINT. */
#define FIO_ASSERT(cond, ...) \
if (!(cond)) { \
FIO_LOG_FATAL("(" FIO__FILE__ ":" FIO_MACRO2STR(__LINE__) ") " __VA_ARGS__); \
fprintf(stderr, " errno(%d): %s\n", errno, strerror(errno)); \
kill(0, SIGINT); \
exit(-1); \
}
#ifndef FIO_ASSERT_ALLOC
/** Tests for an allocation failure. The behavior can be overridden. */
#define FIO_ASSERT_ALLOC(ptr) FIO_ASSERT((ptr), "memory allocation failed.")
#endif
// clang-format on
#ifdef DEBUG
/** If `DEBUG` is defined, acts as `FIO_ASSERT`, otherwise a NOOP. */
#define FIO_ASSERT_DEBUG(cond, ...) FIO_ASSERT(cond, __VA_ARGS__)
#else
#define FIO_ASSERT_DEBUG(...)
#endif
/* *****************************************************************************
End persistent segment (end include-once guard)
***************************************************************************** */
#endif /* H___FIO_CSTL_INCLUDE_ONCE_H */
/* *****************************************************************************
Common internal Macros
***************************************************************************** */
/* *****************************************************************************
Memory allocation macros
***************************************************************************** */
#ifndef FIO_MEMORY_INITIALIZE_ALLOCATIONS_DEFAULT
/* secure by default */
#define FIO_MEMORY_INITIALIZE_ALLOCATIONS_DEFAULT 1
#endif
#if defined(FIO_MEM_REST) || !defined(FIO_MEM_REALLOC) || !defined(FIO_MEM_FREE)
#undef FIO_MEM_REALLOC
#undef FIO_MEM_FREE
#undef FIO_MEM_REALLOC_IS_SAFE
#undef FIO_MEM_REST
/* if a global allocator was previously defined route macros to fio_malloc */
#ifdef H___FIO_MALLOC___H
/** Reallocates memory, copying (at least) `copy_len` if necessary. */
#define FIO_MEM_REALLOC(ptr, old_size, new_size, copy_len) \
fio_realloc2((ptr), (new_size), (copy_len))
/** Frees allocated memory. */
#define FIO_MEM_FREE(ptr, size) fio_free((ptr))
/** Set to true of internall allocator is used (memory returned set to zero). */
#define FIO_MEM_REALLOC_IS_SAFE 1
#else
/** Reallocates memory, copying (at least) `copy_len` if necessary. */
#define FIO_MEM_REALLOC(ptr, old_size, new_size, copy_len) \
realloc((ptr), (new_size))
/** Frees allocated memory. */
#define FIO_MEM_FREE(ptr, size) free((ptr))
/** Set to true of internall allocator is used (memory returned set to zero). */
#define FIO_MEM_REALLOC_IS_SAFE 0
#endif /* H___FIO_MALLOC___H */
#endif /* defined(FIO_MEM_REALLOC) */
/* *****************************************************************************
Locking selector
***************************************************************************** */
#ifndef FIO_USE_THREAD_MUTEX
#define FIO_USE_THREAD_MUTEX 0
#endif
#ifndef FIO_USE_THREAD_MUTEX_TMP
#define FIO_USE_THREAD_MUTEX_TMP FIO_USE_THREAD_MUTEX
#endif
#if FIO_USE_THREAD_MUTEX_TMP
#define FIO_THREAD
#define FIO___LOCK_TYPE fio_thread_mutex_t
#define FIO___LOCK_INIT ((FIO___LOCK_TYPE)FIO_THREAD_MUTEX_INIT)
#define FIO___LOCK_DESTROY(lock) fio_thread_mutex_destroy(&(lock))
#define FIO___LOCK_LOCK(lock) \
do { \
if (fio_thread_mutex_lock(&(lock))) \
FIO_LOG_ERROR("Couldn't lock mutex @ %s:%d - error (%d): %s", \
__FILE__, \
__LINE__, \
errno, \
strerror(errno)); \
} while (0)
#define FIO___LOCK_TRYLOCK(lock) fio_thread_mutex_trylock(&(lock))
#define FIO___LOCK_UNLOCK(lock) \
do { \
if (fio_thread_mutex_unlock(&(lock))) { \
FIO_LOG_ERROR("Couldn't release mutex @ %s:%d - error (%d): %s", \
__FILE__, \
__LINE__, \
errno, \
strerror(errno)); \
} \
} while (0)
#else
#define FIO___LOCK_TYPE fio_lock_i
#define FIO___LOCK_INIT (FIO_LOCK_INIT)
#define FIO___LOCK_DESTROY(lock) ((lock) = FIO___LOCK_INIT)
#define FIO___LOCK_LOCK(lock) fio_lock(&(lock))
#define FIO___LOCK_TRYLOCK(lock) fio_trylock(&(lock))
#define FIO___LOCK_UNLOCK(lock) fio_unlock(&(lock))
#endif
/* *****************************************************************************
Common macros
***************************************************************************** */
#ifndef SFUNC_ /* if we aren't in a recursive #include statement */
#ifdef FIO_EXTERN
#define SFUNC_
#define IFUNC_
#else /* !FIO_EXTERN */
#undef SFUNC
#undef IFUNC
#define SFUNC_ static __attribute__((unused))
#define IFUNC_ static inline __attribute__((unused))
#ifndef FIO_EXTERN_COMPLETE /* force implementation, emitting static data */
#define FIO_EXTERN_COMPLETE 2
#endif /* FIO_EXTERN_COMPLETE */
#endif /* FIO_EXTERN */
#undef SFUNC
#undef IFUNC
#define SFUNC SFUNC_
#define IFUNC IFUNC_
#ifndef FIO_PTR_TAG
/**
* Supports embedded pointer tagging / untagging for the included types.
*
* Should resolve to a tagged pointer value. i.e.: ((uintptr_t)(p) | 1)
*/
#define FIO_PTR_TAG(p) (p)
#endif
#ifndef FIO_PTR_UNTAG
/**
* Supports embedded pointer tagging / untagging for the included types.
*
* Should resolve to an untagged pointer value. i.e.: ((uintptr_t)(p) | ~1UL)
*/
#define FIO_PTR_UNTAG(p) (p)
#endif
/**
* If FIO_PTR_TAG_TYPE is defined, then functions returning a type's pointer
* will return a pointer of the specified type instead.
*/
#ifndef FIO_PTR_TAG_TYPE
#endif
/**
* If FIO_PTR_TAG_VALIDATE is defined, tagging will be verified before executing
* any code.
*/
#ifdef FIO_PTR_TAG_VALIDATE
#define FIO_PTR_TAG_VALID_OR_RETURN(tagged_ptr, value) \
do { \
if (!(FIO_PTR_TAG_VALIDATE(tagged_ptr))) { \
FIO_LOG_DEBUG("pointer tag (type) mismatch in function call."); \
return (value); \
} \
} while (0)
#define FIO_PTR_TAG_VALID_OR_RETURN_VOID(tagged_ptr) \
do { \
if (!(FIO_PTR_TAG_VALIDATE(tagged_ptr))) { \
FIO_LOG_DEBUG("pointer tag (type) mismatch in function call."); \
return; \
} \
} while (0)
#define FIO_PTR_TAG_VALID_OR_GOTO(tagged_ptr, lable) \
do { \
if (!(FIO_PTR_TAG_VALIDATE(tagged_ptr))) { \
/* Log error since GOTO indicates cleanup or other side-effects. */ \
FIO_LOG_ERROR("(" FIO__FILE__ ":" FIO_MACRO2STR( \
__LINE__) ") pointer tag (type) mismatch in function call."); \
goto lable; \
} \
} while (0)
#else
#define FIO_PTR_TAG_VALIDATE(tagged_ptr) 1
#define FIO_PTR_TAG_VALID_OR_RETURN(tagged_ptr, value)
#define FIO_PTR_TAG_VALID_OR_RETURN_VOID(tagged_ptr)
#define FIO_PTR_TAG_VALID_OR_GOTO(tagged_ptr, lable) \
while (0) { \
goto lable; \
}
#endif
#else /* SFUNC_ - internal helper types are `static` */
#undef SFUNC
#undef IFUNC
#define SFUNC FIO_SFUNC
#define IFUNC FIO_IFUNC
#endif /* SFUNC_ vs FIO_STL_KEEP__*/
/* *****************************************************************************
Internal Dependencies
***************************************************************************** */
/* FIO_MEMORY_NAME dependencies */
#if defined(FIO_MEMORY_NAME) || defined(FIO_MALLOC)
#ifndef FIO_LOG
#define FIO_LOG
#endif
#ifndef FIO_RAND
#define FIO_RAND
#endif
#endif /* FIO_MALLOC */
/* Modules that require FIO_SOCK */
#if defined(FIO_POLL)
#define FIO_SOCK
#endif
#if (defined(FIO_QUEUE) && defined(FIO_TEST_CSTL)) || \
defined(FIO_MEMORY_USE_PTHREAD_MUTEX) || defined(FIO_USE_THREAD_MUTEX_TMP)
#define FIO_THREADS
#endif
/* Modules that require FIO_TIME */
#if defined(FIO_QUEUE) || defined(FIO_RAND)
#ifndef FIO_TIME
#define FIO_TIME
#endif
#endif /* FIO_QUEUE */
/* Modules that require FIO_RISKY_HASH */
#if defined(FIO_RAND) || defined(FIO_STR_NAME) || defined(FIO_STR_SMALL) || \
defined(FIO_CLI)
#ifndef FIO_RISKY_HASH
#define FIO_RISKY_HASH
#endif
#endif /* FIO_RISKY_HASH */
/* Modules that require FIO_BITMAP */
#if defined(FIO_JSON)
#ifndef FIO_BITMAP
#define FIO_BITMAP
#endif
#endif /* FIO_BITMAP */
/* Modules that require FIO_BITWISE (includes FIO_RISKY_HASH requirements) */
#if defined(FIO_RISKY_HASH) || defined(FIO_JSON) || defined(FIO_MAP_NAME) || \
defined(FIO_UMAP_NAME) || defined(FIO_SHA1)
#ifndef FIO_BITWISE
#define FIO_BITWISE
#endif
#endif /* FIO_BITWISE */
/* Modules that require FIO_ATOMIC */
#if defined(FIO_BITMAP) || defined(FIO_REF_NAME) || defined(FIO_LOCK2) || \
(defined(FIO_POLL) && !FIO_USE_THREAD_MUTEX_TMP) || \
((defined(FIO_MEMORY_NAME) || defined(FIO_MALLOC)) && !FIO_OS_WIN) || \
(defined(FIO_QUEUE) && !FIO_USE_THREAD_MUTEX_TMP) || defined(FIO_JSON) || \
(defined(FIO_SIGNAL) && !FIO_OS_WIN) || defined(FIO_BITMAP) || \
(defined(FIO_THREADS) && FIO_OS_WIN)
#ifndef FIO_ATOMIC
#define FIO_ATOMIC
#endif
#endif /* FIO_ATOMIC */
/* Modules that require FIO_ATOL */
#if defined(FIO_STR_NAME) || defined(FIO_STR_SMALL) || defined(FIO_QUEUE) || \
defined(FIO_TIME) || defined(FIO_CLI) || defined(FIO_JSON)
#ifndef FIO_ATOL
#define FIO_ATOL
#endif
#endif /* FIO_ATOL */
|
janbiedermann/cstl
|
stl_slices/219 map finish.h
|
/* *****************************************************************************
Map Testing
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#define FIO_MAP_NAME map /* Development inclusion - ignore line */
#include "004 bitwise.h" /* Development inclusion - ignore line */
#include "100 mem.h" /* Development inclusion - ignore line */
#include "210 map api.h" /* Development inclusion - ignore line */
#include "211 ordered map.h" /* Development inclusion - ignore line */
#include "211 unordered map.h" /* Development inclusion - ignore line */
#define FIO_MAP_TEST /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
#if defined(FIO_MAP_TEST) && defined(FIO_MAP_NAME)
FIO_SFUNC int FIO_NAME_TEST(stl, FIO_NAME(FIO_MAP_NAME, task))(FIO_MAP_TYPE o,
void *p) {
*(size_t *)p -= (size_t)o;
return 0;
}
FIO_SFUNC void FIO_NAME_TEST(stl, FIO_MAP_NAME)(void) {
/*
* test unrodered maps here
*/
uint64_t total = 0;
#ifdef FIO_MAP_KEY
fprintf(stderr,
"* testing %s map (hash-map) " FIO_MACRO2STR(FIO_MAP_NAME) "\n",
(FIO_MAP_ORDERED ? "ordered " : "unordered"));
#define FIO_MAP_TEST_KEY FIO_MAP_KEY
#else
fprintf(stderr,
"* testing %s map (set) " FIO_MACRO2STR(FIO_MAP_NAME) "\n",
(FIO_MAP_ORDERED ? "ordered " : "unordered"));
#define FIO_MAP_TEST_KEY FIO_MAP_TYPE
#endif
FIO_NAME(FIO_MAP_NAME, s) m = FIO_MAP_INIT;
const size_t MEMBERS = (1 << 18);
for (size_t i = 1; i < MEMBERS; ++i) {
total += i;
FIO_MAP_TYPE old = (FIO_MAP_TYPE)i;
#ifdef FIO_MAP_KEY
FIO_ASSERT((FIO_MAP_TYPE)i == FIO_NAME(FIO_MAP_NAME, set)(&m,
(FIO_MAP_HASH)i,
(FIO_MAP_KEY)i,
(FIO_MAP_TYPE)i,
&old),
"insertion failed at %zu",
i);
#else
FIO_ASSERT((FIO_MAP_TYPE)i ==
FIO_NAME(FIO_MAP_NAME,
set)(&m, (FIO_MAP_HASH)i, (FIO_MAP_TYPE)i, &old),
"insertion failed at %zu",
i);
#endif
FIO_ASSERT(old == FIO_MAP_TYPE_INVALID,
"old value should be set to the invalid value (%zu != %zu @%zu)",
old,
(size_t)FIO_MAP_TYPE_INVALID,
i);
FIO_ASSERT(
FIO_NAME(FIO_MAP_NAME, get)(&m, (FIO_MAP_HASH)i, (FIO_MAP_TEST_KEY)i) ==
(FIO_MAP_TYPE)i,
"set-get roundtrip error for %zu",
i);
}
size_t old_capa = FIO_NAME(FIO_MAP_NAME, capa)(&m);
for (size_t i = 1; i < MEMBERS; ++i) {
FIO_ASSERT(
FIO_NAME(FIO_MAP_NAME, get)(&m, (FIO_MAP_HASH)i, (FIO_MAP_TEST_KEY)i) ==
(FIO_MAP_TYPE)i,
"get error for %zu",
i);
}
for (size_t i = 1; i < MEMBERS; ++i) {
FIO_MAP_TYPE old = (FIO_MAP_TYPE)i;
#ifdef FIO_MAP_KEY
FIO_ASSERT((FIO_MAP_TYPE)i == FIO_NAME(FIO_MAP_NAME, set)(&m,
(FIO_MAP_HASH)i,
(FIO_MAP_KEY)i,
(FIO_MAP_TYPE)i,
&old),
"overwrite failed at %zu",
i);
#else
FIO_ASSERT((FIO_MAP_TYPE)i ==
FIO_NAME(FIO_MAP_NAME,
set)(&m, (FIO_MAP_HASH)i, (FIO_MAP_TYPE)i, &old),
"overwrite failed at %zu",
i);
#endif
FIO_ASSERT(
!memcmp(&old, &i, sizeof(old) > sizeof(i) ? sizeof(i) : sizeof(old)),
"old value should be set to the replaced value");
FIO_ASSERT(
FIO_NAME(FIO_MAP_NAME, get)(&m, (FIO_MAP_HASH)i, (FIO_MAP_TEST_KEY)i) ==
(FIO_MAP_TYPE)i,
"set-get overwrite roundtrip error for %zu",
i);
}
for (size_t i = 1; i < MEMBERS; ++i) {
FIO_ASSERT(
FIO_NAME(FIO_MAP_NAME, get)(&m, (FIO_MAP_HASH)i, (FIO_MAP_TEST_KEY)i) ==
(FIO_MAP_TYPE)i,
"get (overwrite) error for %zu",
i);
}
for (size_t i = 1; i < MEMBERS; ++i) {
FIO_ASSERT(FIO_NAME(FIO_MAP_NAME, count)(&m) == MEMBERS - 1,
"unexpected member count");
FIO_NAME(FIO_MAP_NAME, remove)
(&m, (FIO_MAP_HASH)i, (FIO_MAP_TEST_KEY)i, NULL);
FIO_ASSERT(FIO_NAME(FIO_MAP_NAME, count)(&m) == MEMBERS - 2,
"removing member didn't count removal");
#ifdef FIO_MAP_KEY
FIO_ASSERT((FIO_MAP_TYPE)i == FIO_NAME(FIO_MAP_NAME, set)(&m,
(FIO_MAP_HASH)i,
(FIO_MAP_KEY)i,
(FIO_MAP_TYPE)i,
NULL),
"re-insertion failed at %zu",
i);
#else
FIO_ASSERT((FIO_MAP_TYPE)i ==
FIO_NAME(FIO_MAP_NAME,
set)(&m, (FIO_MAP_HASH)i, (FIO_MAP_TYPE)i, NULL),
"re-insertion failed at %zu",
i);
#endif
FIO_ASSERT(FIO_NAME(FIO_MAP_NAME, get)(&m,
(FIO_MAP_HASH)i,
(FIO_MAP_TYPE)i) == (FIO_MAP_TYPE)i,
"remove-set-get roundtrip error for %zu",
i);
}
for (size_t i = 1; i < MEMBERS; ++i) {
FIO_ASSERT(
FIO_NAME(FIO_MAP_NAME, get)(&m, (FIO_MAP_HASH)i, (FIO_MAP_TEST_KEY)i) ==
(FIO_MAP_TYPE)i,
"get (remove/re-insert) error for %zu",
i);
}
if (FIO_NAME(FIO_MAP_NAME, capa)(&m) != old_capa) {
FIO_LOG_WARNING("capacity shouldn't change when re-inserting the same "
"number of items.");
}
{
size_t count = 0;
size_t tmp = total;
FIO_MAP_EACH(FIO_MAP_NAME, &m, i) {
++count;
tmp -= (size_t)(FIO_MAP_OBJ2TYPE(i->obj));
}
FIO_ASSERT(count + 1 == MEMBERS,
"FIO_MAP_EACH macro error, repetitions %zu != %zu",
count,
MEMBERS - 1);
FIO_ASSERT(
!tmp,
"FIO_MAP_EACH macro error total value %zu != 0 (%zu repetitions)",
tmp,
count);
tmp = total;
count = FIO_NAME(FIO_MAP_NAME,
each)(&m,
0,
FIO_NAME_TEST(stl, FIO_NAME(FIO_MAP_NAME, task)),
(void *)&tmp);
FIO_ASSERT(count + 1 == MEMBERS,
"each task error, repetitions %zu != %zu",
count,
MEMBERS - 1);
FIO_ASSERT(!tmp,
"each task error, total value %zu != 0 (%zu repetitions)",
tmp,
count);
}
FIO_NAME(FIO_MAP_NAME, destroy)(&m);
}
#undef FIO_MAP_TEST_KEY
#endif /* FIO_MAP_TEST */
/* *****************************************************************************
Map - cleanup
***************************************************************************** */
#undef FIO_MAP_PTR
#undef FIO_MAP_NAME
#undef FIO_UMAP_NAME
#undef FIO_OMAP_NAME
#undef FIO_MAP_DESTROY_AFTER_COPY
#undef FIO_MAP_HASH
#undef FIO_MAP_HASH_FIX
#undef FIO_MAP_HASH_FIXED
#undef FIO_MAP_HASH_INVALID
#undef FIO_MAP_HASH_IS_INVALID
#undef FIO_MAP_HASH_FN
#undef FIO_MAP_HASH_GET_HASH
#undef FIO_MAP_HASH_CACHED
#undef FIO_MAP_INDEX_CALC
#undef FIO_MAP_INDEX_INVALID
#undef FIO_MAP_INDEX_UNUSED
#undef FIO_MAP_INDEX_USED_BIT
#undef FIO_MAP_ORDERED
#undef FIO_MAP_KEY
#undef FIO_MAP_KEY_CMP
#undef FIO_MAP_KEY_COPY
#undef FIO_MAP_KEY_DESTROY
#undef FIO_MAP_KEY_DESTROY_SIMPLE
#undef FIO_MAP_KEY_DISCARD
#undef FIO_MAP_KEY_INVALID
#undef FIO_MAP_MAX_ELEMENTS
#undef FIO_MAP_MAX_FULL_COLLISIONS
#undef FIO_MAP_MAX_SEEK
#undef FIO_MAP_EVICT_LRU
#undef FIO_MAP_SHOULD_OVERWRITE
#undef FIO_MAP_OBJ
#undef FIO_MAP_OBJ2KEY
#undef FIO_MAP_OBJ2TYPE
#undef FIO_MAP_OBJ_CMP
#undef FIO_MAP_OBJ_COPY
#undef FIO_MAP_OBJ_DESTROY
#undef FIO_MAP_OBJ_DESTROY_AFTER
#undef FIO_MAP_OBJ_DISCARD
#undef FIO_MAP_OBJ_INVALID
#undef FIO_MAP_OBJ_KEY
#undef FIO_MAP_OBJ_KEY_CMP
#undef FIO_MAP_S
#undef FIO_MAP_SEEK_AS_ARRAY_LOG_LIMIT
#undef FIO_MAP_SIZE_TYPE
#undef FIO_MAP_TYPE
#undef FIO_MAP_TYPE_CMP
#undef FIO_MAP_TYPE_COPY
#undef FIO_MAP_TYPE_COPY_SIMPLE
#undef FIO_MAP_TYPE_DESTROY
#undef FIO_MAP_TYPE_DESTROY_SIMPLE
#undef FIO_MAP_TYPE_DISCARD
#undef FIO_MAP_TYPE_INVALID
#undef FIO_MAP_BIG
#undef FIO_MAP_HASH
#undef FIO_MAP_INDEX_USED_BIT
#undef FIO_MAP_TYPE
#undef FIO_MAP_TYPE_INVALID
#undef FIO_MAP_TYPE_COPY
#undef FIO_MAP_TYPE_COPY_SIMPLE
#undef FIO_MAP_TYPE_DESTROY
#undef FIO_MAP_TYPE_DESTROY_SIMPLE
#undef FIO_MAP_TYPE_DISCARD
#undef FIO_MAP_TYPE_CMP
#undef FIO_MAP_DESTROY_AFTER_COPY
#undef FIO_MAP_KEY
#undef FIO_MAP_KEY_INVALID
#undef FIO_MAP_KEY_COPY
#undef FIO_MAP_KEY_DESTROY
#undef FIO_MAP_KEY_DESTROY_SIMPLE
#undef FIO_MAP_KEY_DISCARD
#undef FIO_MAP_KEY_CMP
#undef FIO_MAP_OBJ
#undef FIO_MAP_OBJ_KEY
#undef FIO_MAP_OBJ_INVALID
#undef FIO_MAP_OBJ_COPY
#undef FIO_MAP_OBJ_DESTROY
#undef FIO_MAP_OBJ_CMP
#undef FIO_MAP_OBJ_KEY_CMP
#undef FIO_MAP_OBJ2KEY
#undef FIO_MAP_OBJ2TYPE
#undef FIO_MAP_OBJ_DISCARD
#undef FIO_MAP_DESTROY_AFTER_COPY
#undef FIO_MAP_OBJ_DESTROY_AFTER
#undef FIO_MAP_MAX_SEEK
#undef FIO_MAP_MAX_FULL_COLLISIONS
#undef FIO_MAP_CUCKOO_STEPS
#undef FIO_MAP_EVICT_LRU
#undef FIO_MAP_CAPA
#undef FIO_MAP_MEMORY_SIZE
#undef FIO_MAP___IMAP_FREE
#undef FIO_MAP___IMAP_DELETED
#undef FIO_MAP_TEST
|
janbiedermann/cstl
|
stl_slices/800 fiobj.h
|
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#include "000 header.h" /* Development inclusion - ignore line */
#include "003 atomics.h" /* Development inclusion - ignore line */
#include "004 bitwise.h" /* Development inclusion - ignore line */
#include "005 riskyhash.h" /* Development inclusion - ignore line */
#include "006 atol.h" /* Development inclusion - ignore line */
#include "051 json.h" /* Development inclusion - ignore line */
#include "201 array.h" /* Development inclusion - ignore line */
#include "210 hashmap.h" /* Development inclusion - ignore line */
#include "220 string.h" /* Development inclusion - ignore line */
#include "299 reference counter.h" /* Development inclusion - ignore line */
#include "700 cleanup.h" /* Development inclusion - ignore line */
#define FIO_FIOBJ /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
FIOBJ - soft (dynamic) types
FIOBJ - dynamic types
These are dynamic types that use pointer tagging for fast type identification.
Pointer tagging on 64 bit systems allows for 3 bits at the lower bits. On most
32 bit systems this is also true due to allocator alignment. When in doubt, use
the provided custom allocator.
To keep the 64bit memory address alignment on 32bit systems, a 32bit metadata
integer is added when a virtual function table is missing. This doesn't effect
memory consumption on 64 bit systems and uses 4 bytes on 32 bit systems.
Note: this code is placed at the end of the STL file, since it leverages most of
the SLT features and could be affected by their inclusion.
***************************************************************************** */
#if defined(FIO_FIOBJ) && !defined(H___FIOBJ___H)
#define H___FIOBJ___H
/* *****************************************************************************
FIOBJ compilation settings (type names and JSON nesting limits).
Type Naming Macros for FIOBJ types. By default, results in:
- fiobj_true()
- fiobj_false()
- fiobj_null()
- fiobj_num_new() ... (etc')
- fiobj_float_new() ... (etc')
- fiobj_str_new() ... (etc')
- fiobj_array_new() ... (etc')
- fiobj_hash_new() ... (etc')
***************************************************************************** */
#define FIOBJ___NAME_TRUE true
#define FIOBJ___NAME_FALSE false
#define FIOBJ___NAME_NULL null
#define FIOBJ___NAME_NUMBER num
#define FIOBJ___NAME_FLOAT float
#define FIOBJ___NAME_STRING str
#define FIOBJ___NAME_ARRAY array
#define FIOBJ___NAME_HASH hash
#ifndef FIOBJ_MAX_NESTING
/**
* Sets the limit on nesting level transversal by recursive functions.
*
* This effects JSON output / input and the `fiobj_each2` function since they
* are recursive.
*
* HOWEVER: this value will NOT effect the recursive `fiobj_free` which could
* (potentially) expload the stack if given melformed input such as cyclic data
* structures.
*
* Values should be less than 32K.
*/
#define FIOBJ_MAX_NESTING 512
#endif
/* make sure roundtrips work */
#ifndef JSON_MAX_DEPTH
#define JSON_MAX_DEPTH FIOBJ_MAX_NESTING
#endif
#ifndef FIOBJ_JSON_APPEND
#define FIOBJ_JSON_APPEND 1
#endif
/* *****************************************************************************
General Requirements / Macros
***************************************************************************** */
#define FIO_ATOL 1
#define FIO_ATOMIC 1
#include __FILE__
#ifdef FIOBJ_EXTERN
#define FIOBJ_FUNC
#define FIOBJ_IFUNC
#define FIOBJ_EXTERN_OBJ extern
#define FIOBJ_EXTERN_OBJ_IMP __attribute__((weak))
#else /* FIO_EXTERN */
#define FIOBJ_FUNC static __attribute__((unused))
#define FIOBJ_IFUNC static inline __attribute__((unused))
#define FIOBJ_EXTERN_OBJ static __attribute__((unused))
#define FIOBJ_EXTERN_OBJ_IMP static __attribute__((unused))
#ifndef FIOBJ_EXTERN_COMPLETE /* force implementation, emitting static data */
#define FIOBJ_EXTERN_COMPLETE 2
#endif /* FIOBJ_EXTERN_COMPLETE */
#endif /* FIO_EXTERN */
#ifdef FIO_LOG_PRINT__
#define FIOBJ_LOG_PRINT__(...) FIO_LOG_PRINT__(__VA_ARGS__)
#else
#define FIOBJ_LOG_PRINT__(...)
#endif
#ifdef __cplusplus /* C++ doesn't allow declarations for static variables */
#undef FIOBJ_EXTERN_OBJ
#undef FIOBJ_EXTERN_OBJ_IMP
#define FIOBJ_EXTERN_OBJ extern "C"
#define FIOBJ_EXTERN_OBJ_IMP extern "C" __attribute__((weak))
#endif
/* *****************************************************************************
Dedicated memory allocator for FIOBJ types? (recommended for locality)
***************************************************************************** */
#ifdef FIOBJ_MALLOC
#define FIO_MEMORY_NAME fiobj_mem
#ifndef FIO_MEMORY_SYS_ALLOCATION_SIZE_LOG
/* 4Mb per system call */
#define FIO_MEMORY_SYS_ALLOCATION_SIZE_LOG 22
#endif
#ifndef FIO_MEMORY_BLOCKS_PER_ALLOCATION_LOG
/* fight fragmentation */
#define FIO_MEMORY_BLOCKS_PER_ALLOCATION_LOG 4
#endif
#ifndef FIO_MEMORY_ALIGN_LOG
/* align on 8 bytes, it's enough */
#define FIO_MEMORY_ALIGN_LOG 3
#endif
#ifndef FIO_MEMORY_CACHE_SLOTS
/* cache up to 64Mb */
#define FIO_MEMORY_CACHE_SLOTS 16
#endif
#ifndef FIO_MEMORY_ENABLE_BIG_ALLOC
/* for big arrays / maps */
#define FIO_MEMORY_ENABLE_BIG_ALLOC 1
#endif
#ifndef FIO_MEMORY_ARENA_COUNT
/* CPU core arena count */
#define FIO_MEMORY_ARENA_COUNT -1
#endif
#ifndef FIO_MEMORY_USE_PTHREAD_MUTEX
/* yes, well...*/
#define FIO_MEMORY_USE_PTHREAD_MUTEX 1
#endif
/* make sure functions are exported if requested */
#ifdef FIOBJ_EXTERN
#define FIO_EXTERN
#if defined(FIOBJ_EXTERN_COMPLETE) && !defined(FIO_EXTERN_COMPLETE)
#define FIO_EXTERN_COMPLETE 2
#endif
#endif
#include __FILE__
#define FIOBJ_MEM_REALLOC(ptr, old_size, new_size, copy_len) \
FIO_NAME(fiobj_mem, realloc2)((ptr), (new_size), (copy_len))
#define FIOBJ_MEM_FREE(ptr, size) FIO_NAME(fiobj_mem, free)((ptr))
#define FIOBJ_MEM_REALLOC_IS_SAFE 0
#else
FIO_IFUNC void *FIO_NAME(fiobj_mem, realloc2)(void *ptr,
size_t new_size,
size_t copy_len) {
return FIO_MEM_REALLOC(ptr, new_size, new_size, copy_len);
(void)copy_len; /* might be unused */
}
FIO_IFUNC void FIO_NAME(fiobj_mem, free)(void *ptr) { FIO_MEM_FREE(ptr, -1); }
#define FIOBJ_MEM_REALLOC FIO_MEM_REALLOC
#define FIOBJ_MEM_FREE FIO_MEM_FREE
#define FIOBJ_MEM_REALLOC_IS_SAFE FIO_MEM_REALLOC_IS_SAFE
#endif /* FIOBJ_MALLOC */
/* *****************************************************************************
Debugging / Leak Detection
***************************************************************************** */
#if defined(TEST) || defined(DEBUG) || defined(FIO_LEAK_COUNTER)
#define FIOBJ_MARK_MEMORY 1
#endif
#if FIOBJ_MARK_MEMORY
size_t __attribute__((weak)) FIOBJ_MARK_MEMORY_ALLOC_COUNTER;
size_t __attribute__((weak)) FIOBJ_MARK_MEMORY_FREE_COUNTER;
#define FIOBJ_MARK_MEMORY_ALLOC() \
fio_atomic_add(&FIOBJ_MARK_MEMORY_ALLOC_COUNTER, 1)
#define FIOBJ_MARK_MEMORY_FREE() \
fio_atomic_add(&FIOBJ_MARK_MEMORY_FREE_COUNTER, 1)
#define FIOBJ_MARK_MEMORY_PRINT() \
FIOBJ_LOG_PRINT__( \
((FIOBJ_MARK_MEMORY_ALLOC_COUNTER == FIOBJ_MARK_MEMORY_FREE_COUNTER) \
? 4 /* FIO_LOG_LEVEL_INFO */ \
: 3 /* FIO_LOG_LEVEL_WARNING */), \
((FIOBJ_MARK_MEMORY_ALLOC_COUNTER == FIOBJ_MARK_MEMORY_FREE_COUNTER) \
? "INFO: total FIOBJ allocations: %zu (%zu/%zu)" \
: "WARNING: LEAKED! FIOBJ allocations: %zu (%zu/%zu)"), \
FIOBJ_MARK_MEMORY_ALLOC_COUNTER - FIOBJ_MARK_MEMORY_FREE_COUNTER, \
FIOBJ_MARK_MEMORY_FREE_COUNTER, \
FIOBJ_MARK_MEMORY_ALLOC_COUNTER)
#define FIOBJ_MARK_MEMORY_ENABLED 1
#else
#define FIOBJ_MARK_MEMORY_ALLOC_COUNTER 0 /* when testing unmarked FIOBJ */
#define FIOBJ_MARK_MEMORY_FREE_COUNTER 0 /* when testing unmarked FIOBJ */
#define FIOBJ_MARK_MEMORY_ALLOC()
#define FIOBJ_MARK_MEMORY_FREE()
#define FIOBJ_MARK_MEMORY_PRINT()
#define FIOBJ_MARK_MEMORY_ENABLED 0
#endif
/* *****************************************************************************
The FIOBJ Type
***************************************************************************** */
/** Use the FIOBJ type for dynamic types. */
typedef struct FIOBJ_s {
struct FIOBJ_s *compiler_validation_type;
} * FIOBJ;
/** FIOBJ type enum for common / primitive types. */
typedef enum {
FIOBJ_T_NUMBER = 0x01, /* 0b001 3 bits taken for small numbers */
FIOBJ_T_PRIMITIVE = 2, /* 0b010 a lonely second bit signifies a primitive */
FIOBJ_T_STRING = 3, /* 0b011 */
FIOBJ_T_ARRAY = 4, /* 0b100 */
FIOBJ_T_HASH = 5, /* 0b101 */
FIOBJ_T_FLOAT = 6, /* 0b110 */
FIOBJ_T_OTHER = 7, /* 0b111 dynamic type - test content */
} fiobj_class_en;
#define FIOBJ_T_NULL 2 /* 0b010 a lonely second bit signifies a primitive */
#define FIOBJ_T_TRUE 18 /* 0b010 010 - primitive value */
#define FIOBJ_T_FALSE 34 /* 0b100 010 - primitive value */
/** Use the macros to avoid future API changes. */
#define FIOBJ_TYPE(o) fiobj_type(o)
/** Use the macros to avoid future API changes. */
#define FIOBJ_TYPE_IS(o, type) (fiobj_type(o) == type)
/** Identifies an invalid type identifier (returned from FIOBJ_TYPE(o) */
#define FIOBJ_T_INVALID 0
/** Identifies an invalid object */
#define FIOBJ_INVALID 0
/** Tests if the object is (probably) a valid FIOBJ */
#define FIOBJ_IS_INVALID(o) (((uintptr_t)(o)&7UL) == 0)
#define FIOBJ_TYPE_CLASS(o) ((fiobj_class_en)(((uintptr_t)(o)) & 7UL))
#define FIOBJ_PTR_TAG(o, klass) ((uintptr_t)((uintptr_t)(o) | (klass)))
#define FIOBJ_PTR_UNTAG(o) ((uintptr_t)((uintptr_t)(o) & (~7ULL)))
#define FIOBJ_PTR_TAG_VALIDATE(o) ((uintptr_t)((uintptr_t)(o) & (7ULL)))
/** Returns an objects type. This isn't limited to known types. */
FIO_IFUNC size_t fiobj_type(FIOBJ o);
/* *****************************************************************************
FIOBJ Memory Management
***************************************************************************** */
/** Increases an object's reference count (or copies) and returns it. */
FIO_IFUNC FIOBJ fiobj_dup(FIOBJ o);
/** Decreases an object's reference count or frees it. */
FIO_IFUNC void fiobj_free(FIOBJ o);
/* *****************************************************************************
FIOBJ Data / Info
***************************************************************************** */
/** Compares two objects. */
FIO_IFUNC unsigned char FIO_NAME_BL(fiobj, eq)(FIOBJ a, FIOBJ b);
/** Returns a temporary String representation for any FIOBJ object. */
FIO_IFUNC fio_str_info_s FIO_NAME2(fiobj, cstr)(FIOBJ o);
/** Returns an integer representation for any FIOBJ object. */
FIO_IFUNC intptr_t FIO_NAME2(fiobj, i)(FIOBJ o);
/** Returns a float (double) representation for any FIOBJ object. */
FIO_IFUNC double FIO_NAME2(fiobj, f)(FIOBJ o);
/* *****************************************************************************
FIOBJ Containers (iteration)
***************************************************************************** */
/**
* Performs a task for each element held by the FIOBJ object.
*
* If `task` returns -1, the `each` loop will break (stop).
*
* Returns the "stop" position - the number of elements processed + `start_at`.
*/
FIO_SFUNC uint32_t fiobj_each1(FIOBJ o,
int32_t start_at,
int (*task)(FIOBJ child, void *arg),
void *arg);
/**
* Performs a task for the object itself and each element held by the FIOBJ
* object or any of it's elements (a deep task).
*
* The order of performance is by order of appearance, as if all nesting levels
* were flattened.
*
* If `task` returns -1, the `each` loop will break (stop).
*
* Returns the number of elements processed.
*/
FIOBJ_FUNC uint32_t fiobj_each2(FIOBJ o,
int (*task)(FIOBJ child, void *arg),
void *arg);
/* *****************************************************************************
FIOBJ Primitives (NULL, True, False)
***************************************************************************** */
/** Returns the `true` primitive. */
FIO_IFUNC FIOBJ FIO_NAME(fiobj, FIOBJ___NAME_TRUE)(void) {
return (FIOBJ)(FIOBJ_T_TRUE);
}
/** Returns the `false` primitive. */
FIO_IFUNC FIOBJ FIO_NAME(fiobj, FIOBJ___NAME_FALSE)(void) {
return (FIOBJ)(FIOBJ_T_FALSE);
}
/** Returns the `nil` / `null` primitive. */
FIO_IFUNC FIOBJ FIO_NAME(fiobj, FIOBJ___NAME_NULL)(void) {
return (FIOBJ)(FIOBJ_T_NULL);
}
/* *****************************************************************************
FIOBJ Type - Extendability (FIOBJ_T_OTHER)
***************************************************************************** */
/** FIOBJ types can be extended using virtual function tables. */
typedef struct {
/**
* MUST return a unique number to identify object type.
*
* Numbers (type IDs) under 100 are reserved. Numbers under 40 are illegal.
*/
size_t type_id;
/** Test for equality between two objects with the same `type_id` */
unsigned char (*is_eq)(FIOBJ restrict a, FIOBJ restrict b);
/** Converts an object to a String */
fio_str_info_s (*to_s)(FIOBJ o);
/** Converts an object to an integer */
intptr_t (*to_i)(FIOBJ o);
/** Converts an object to a double */
double (*to_f)(FIOBJ o);
/** Returns the number of exposed elements held by the object, if any. */
uint32_t (*count)(FIOBJ o);
/** Iterates the exposed elements held by the object. See `fiobj_each1`. */
uint32_t (*each1)(FIOBJ o,
int32_t start_at,
int (*task)(FIOBJ child, void *arg),
void *arg);
/**
* Decreases the reference count and/or frees the object, calling `free2` for
* any nested objects.
*
* Returns 0 if the object is still alive or 1 if the object was freed. The
* return value is currently ignored, but this might change in the future.
*/
int (*free2)(FIOBJ o);
} FIOBJ_class_vtable_s;
FIOBJ_EXTERN_OBJ const FIOBJ_class_vtable_s FIOBJ___OBJECT_CLASS_VTBL;
#define FIO_REF_CONSTRUCTOR_ONLY 1
#define FIO_REF_NAME fiobj_object
#define FIO_REF_TYPE void *
#define FIO_REF_METADATA const FIOBJ_class_vtable_s *
#define FIO_REF_METADATA_INIT(m) \
do { \
m = &FIOBJ___OBJECT_CLASS_VTBL; \
FIOBJ_MARK_MEMORY_ALLOC(); \
} while (0)
#define FIO_REF_METADATA_DESTROY(m) \
do { \
FIOBJ_MARK_MEMORY_FREE(); \
} while (0)
#define FIO_PTR_TAG(p) FIOBJ_PTR_TAG(p, FIOBJ_T_OTHER)
#define FIO_PTR_UNTAG(p) FIOBJ_PTR_UNTAG(p)
#define FIO_PTR_TAG_TYPE FIOBJ
#define FIO_MEM_REALLOC_ FIOBJ_MEM_REALLOC
#define FIO_MEM_FREE_ FIOBJ_MEM_FREE
#define FIO_MEM_REALLOC_IS_SAFE_ FIOBJ_MEM_REALLOC_IS_SAFE
/* make sure functions are exported if requested */
#ifdef FIOBJ_EXTERN
#define FIO_EXTERN
#if defined(FIOBJ_EXTERN_COMPLETE) && !defined(FIO_EXTERN_COMPLETE)
#define FIO_EXTERN_COMPLETE 2
#endif
#endif
#include __FILE__
/* *****************************************************************************
FIOBJ Integers
***************************************************************************** */
/** Creates a new Number object. */
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), new)(intptr_t i);
/** Reads the number from a FIOBJ Number. */
FIO_IFUNC intptr_t FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), i)(FIOBJ i);
/** Reads the number from a FIOBJ Number, fitting it in a double. */
FIO_IFUNC double FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), f)(FIOBJ i);
/** Returns a String representation of the number (in base 10). */
FIOBJ_FUNC fio_str_info_s FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER),
cstr)(FIOBJ i);
/** Frees a FIOBJ number. */
FIO_IFUNC void FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), free)(FIOBJ i);
FIOBJ_EXTERN_OBJ const FIOBJ_class_vtable_s FIOBJ___NUMBER_CLASS_VTBL;
/* *****************************************************************************
FIOBJ Floats
***************************************************************************** */
/** Creates a new Float (double) object. */
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), new)(double i);
/** Reads the number from a FIOBJ Float rounding it to an integer. */
FIO_IFUNC intptr_t FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), i)(FIOBJ i);
/** Reads the value from a FIOBJ Float, as a double. */
FIO_IFUNC double FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), f)(FIOBJ i);
/** Returns a String representation of the float. */
FIOBJ_FUNC fio_str_info_s FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT),
cstr)(FIOBJ i);
/** Frees a FIOBJ Float. */
FIO_IFUNC void FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), free)(FIOBJ i);
FIOBJ_EXTERN_OBJ const FIOBJ_class_vtable_s FIOBJ___FLOAT_CLASS_VTBL;
/* *****************************************************************************
FIOBJ Strings
***************************************************************************** */
#define FIO_STR_NAME FIO_NAME(fiobj, FIOBJ___NAME_STRING)
#define FIO_STR_OPTIMIZE_EMBEDDED 1
#define FIO_REF_NAME FIO_NAME(fiobj, FIOBJ___NAME_STRING)
#define FIO_REF_CONSTRUCTOR_ONLY 1
#define FIO_REF_DESTROY(s) \
do { \
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), destroy)((FIOBJ)&s); \
FIOBJ_MARK_MEMORY_FREE(); \
} while (0)
#define FIO_REF_INIT(s_) \
do { \
s_ = (FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), s))FIO_STR_INIT; \
FIOBJ_MARK_MEMORY_ALLOC(); \
} while (0)
#if SIZE_T_MAX == 0xFFFFFFFF /* for 32bit system pointer alignment */
#define FIO_REF_METADATA uint32_t
#endif
#define FIO_PTR_TAG(p) FIOBJ_PTR_TAG(p, FIOBJ_T_STRING)
#define FIO_PTR_UNTAG(p) FIOBJ_PTR_UNTAG(p)
#define FIO_PTR_TAG_TYPE FIOBJ
#define FIO_MEM_REALLOC_ FIOBJ_MEM_REALLOC
#define FIO_MEM_FREE_ FIOBJ_MEM_FREE
#define FIO_MEM_REALLOC_IS_SAFE_ FIOBJ_MEM_REALLOC_IS_SAFE
/* make sure functions are exported if requested */
#ifdef FIOBJ_EXTERN
#define FIO_EXTERN
#if defined(FIOBJ_EXTERN_COMPLETE) && !defined(FIO_EXTERN_COMPLETE)
#define FIO_EXTERN_COMPLETE 2
#endif
#endif
#include __FILE__
/* Creates a new FIOBJ string object, copying the data to the new string. */
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING),
new_cstr)(const char *ptr, size_t len) {
FIOBJ s = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), new)();
FIO_ASSERT_ALLOC(FIOBJ_PTR_UNTAG(s));
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)(s, ptr, len);
return s;
}
/* Creates a new FIOBJ string object with (at least) the requested capacity. */
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING),
new_buf)(size_t capa) {
FIOBJ s = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), new)();
FIO_ASSERT_ALLOC(FIOBJ_PTR_UNTAG(s));
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), reserve)(s, capa);
return s;
}
/* Creates a new FIOBJ string object, copying the origin (`fiobj2cstr`). */
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING),
new_copy)(FIOBJ original) {
FIOBJ s = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), new)();
FIO_ASSERT_ALLOC(FIOBJ_PTR_UNTAG(s));
fio_str_info_s i = FIO_NAME2(fiobj, cstr)(original);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)(s, i.buf, i.len);
return s;
}
/** Returns information about the string. Same as fiobj_str_info(). */
FIO_IFUNC fio_str_info_s FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING),
cstr)(FIOBJ s) {
return FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), info)(s);
}
/**
* Creates a temporary FIOBJ String object on the stack.
*
* String data might be allocated dynamically.
*/
#define FIOBJ_STR_TEMP_VAR(str_name) \
struct { \
uint64_t i1; \
uint64_t i2; \
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), s) s; \
} FIO_NAME(str_name, __auto_mem_tmp) = {0x7f7f7f7f7f7f7f7fULL, \
0x7f7f7f7f7f7f7f7fULL, \
FIO_STR_INIT}; \
FIOBJ str_name = \
(FIOBJ)(((uintptr_t) & (FIO_NAME(str_name, __auto_mem_tmp).s)) | \
FIOBJ_T_STRING);
/**
* Creates a temporary FIOBJ String object on the stack, initialized with a
* static string.
*
* String data might be allocated dynamically.
*/
#define FIOBJ_STR_TEMP_VAR_STATIC(str_name, buf_, len_) \
struct { \
uint64_t i1; \
uint64_t i2; \
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), s) s; \
} FIO_NAME(str_name, \
__auto_mem_tmp) = {0x7f7f7f7f7f7f7f7fULL, \
0x7f7f7f7f7f7f7f7fULL, \
FIO_STR_INIT_STATIC2((buf_), (len_))}; \
FIOBJ str_name = \
(FIOBJ)(((uintptr_t) & (FIO_NAME(str_name, __auto_mem_tmp).s)) | \
FIOBJ_T_STRING);
/**
* Creates a temporary FIOBJ String object on the stack, initialized with a
* static string.
*
* String data might be allocated dynamically.
*/
#define FIOBJ_STR_TEMP_VAR_EXISTING(str_name, buf_, len_, capa_) \
struct { \
uint64_t i1; \
uint64_t i2; \
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), s) s; \
} FIO_NAME(str_name, __auto_mem_tmp) = { \
0x7f7f7f7f7f7f7f7fULL, \
0x7f7f7f7f7f7f7f7fULL, \
FIO_STR_INIT_EXISTING((buf_), (len_), (capa_))}; \
FIOBJ str_name = \
(FIOBJ)(((uintptr_t) & (FIO_NAME(str_name, __auto_mem_tmp).s)) | \
FIOBJ_T_STRING);
/** Resets a temporary FIOBJ String, freeing and any resources allocated. */
#define FIOBJ_STR_TEMP_DESTROY(str_name) \
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), destroy)(str_name);
/* *****************************************************************************
FIOBJ Arrays
***************************************************************************** */
#define FIO_ARRAY_NAME FIO_NAME(fiobj, FIOBJ___NAME_ARRAY)
#define FIO_REF_NAME FIO_NAME(fiobj, FIOBJ___NAME_ARRAY)
#define FIO_REF_CONSTRUCTOR_ONLY 1
#define FIO_REF_DESTROY(a) \
do { \
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), destroy)((FIOBJ)&a); \
FIOBJ_MARK_MEMORY_FREE(); \
} while (0)
#define FIO_REF_INIT(a) \
do { \
a = (FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), s))FIO_ARRAY_INIT; \
FIOBJ_MARK_MEMORY_ALLOC(); \
} while (0)
#if SIZE_T_MAX == 0xFFFFFFFF /* for 32bit system pointer alignment */
#define FIO_REF_METADATA uint32_t
#endif
#define FIO_ARRAY_TYPE FIOBJ
#define FIO_ARRAY_TYPE_CMP(a, b) FIO_NAME_BL(fiobj, eq)((a), (b))
#define FIO_ARRAY_TYPE_DESTROY(o) fiobj_free(o)
#define FIO_ARRAY_TYPE_CONCAT_COPY(dest, obj) \
do { \
dest = fiobj_dup(obj); \
} while (0)
#define FIO_PTR_TAG(p) FIOBJ_PTR_TAG(p, FIOBJ_T_ARRAY)
#define FIO_PTR_UNTAG(p) FIOBJ_PTR_UNTAG(p)
#define FIO_PTR_TAG_TYPE FIOBJ
#define FIO_MEM_REALLOC_ FIOBJ_MEM_REALLOC
#define FIO_MEM_FREE_ FIOBJ_MEM_FREE
#define FIO_MEM_REALLOC_IS_SAFE_ FIOBJ_MEM_REALLOC_IS_SAFE
/* make sure functions are exported if requested */
#ifdef FIOBJ_EXTERN
#define FIO_EXTERN
#if defined(FIOBJ_EXTERN_COMPLETE) && !defined(FIO_EXTERN_COMPLETE)
#define FIO_EXTERN_COMPLETE 2
#endif
#endif
#include __FILE__
/* *****************************************************************************
FIOBJ Hash Maps
***************************************************************************** */
#define FIO_OMAP_NAME FIO_NAME(fiobj, FIOBJ___NAME_HASH)
#define FIO_REF_NAME FIO_NAME(fiobj, FIOBJ___NAME_HASH)
#define FIO_REF_CONSTRUCTOR_ONLY 1
#define FIO_REF_DESTROY(a) \
do { \
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), destroy)((FIOBJ)&a); \
FIOBJ_MARK_MEMORY_FREE(); \
} while (0)
#define FIO_REF_INIT(a) \
do { \
a = (FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), s))FIO_MAP_INIT; \
FIOBJ_MARK_MEMORY_ALLOC(); \
} while (0)
#if SIZE_T_MAX == 0xFFFFFFFF /* for 32bit system pointer alignment */
#define FIO_REF_METADATA uint32_t
#endif
#define FIO_MAP_TYPE FIOBJ
#define FIO_MAP_TYPE_DESTROY(o) fiobj_free(o)
#define FIO_MAP_TYPE_DISCARD(o) fiobj_free(o)
#define FIO_MAP_KEY FIOBJ
#define FIO_MAP_KEY_CMP(a, b) FIO_NAME_BL(fiobj, eq)((a), (b))
#define FIO_MAP_KEY_COPY(dest, o) (dest = fiobj_dup(o))
#define FIO_MAP_KEY_DESTROY(o) fiobj_free(o)
#define FIO_PTR_TAG(p) FIOBJ_PTR_TAG(p, FIOBJ_T_HASH)
#define FIO_PTR_UNTAG(p) FIOBJ_PTR_UNTAG(p)
#define FIO_PTR_TAG_TYPE FIOBJ
#define FIO_MEM_REALLOC_ FIOBJ_MEM_REALLOC
#define FIO_MEM_FREE_ FIOBJ_MEM_FREE
#define FIO_MEM_REALLOC_IS_SAFE_ FIOBJ_MEM_REALLOC_IS_SAFE
/* make sure functions are exported if requested */
#ifdef FIOBJ_EXTERN
#define FIO_EXTERN
#if defined(FIOBJ_EXTERN_COMPLETE) && !defined(FIO_EXTERN_COMPLETE)
#define FIO_EXTERN_COMPLETE 2
#endif
#endif
#include __FILE__
/** Calculates an object's hash value for a specific hash map object. */
FIO_IFUNC uint64_t FIO_NAME2(fiobj, hash)(FIOBJ target_hash, FIOBJ object_key);
/** Inserts a value to a hash map, with a default hash value calculation. */
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
set2)(FIOBJ hash, FIOBJ key, FIOBJ value);
/**
* Inserts a value to a hash map, with a default hash value calculation.
*
* If the key already exists in the Hash Map, the value will be freed instead.
*/
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
set_if_missing2)(FIOBJ hash, FIOBJ key, FIOBJ value);
/** Finds a value in a hash map, with a default hash value calculation. */
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), get2)(FIOBJ hash,
FIOBJ key);
/** Removes a value from a hash map, with a default hash value calculation. */
FIO_IFUNC int FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
remove2)(FIOBJ hash, FIOBJ key, FIOBJ *old);
/**
* Sets a value in a hash map, allocating the key String and automatically
* calculating the hash value.
*/
FIO_IFUNC
FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
set3)(FIOBJ hash, const char *key, size_t len, FIOBJ value);
/**
* Finds a value in the hash map, using a temporary String and automatically
* calculating the hash value.
*/
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
get3)(FIOBJ hash, const char *buf, size_t len);
/**
* Removes a value in a hash map, using a temporary String and automatically
* calculating the hash value.
*/
FIO_IFUNC int FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
remove3)(FIOBJ hash,
const char *buf,
size_t len,
FIOBJ *old);
/* *****************************************************************************
FIOBJ JSON support
***************************************************************************** */
/**
* Returns a JSON valid FIOBJ String, representing the object.
*
* If `dest` is an existing String, the formatted JSON data will be appended to
* the existing string.
*/
FIO_IFUNC FIOBJ FIO_NAME2(fiobj, json)(FIOBJ dest, FIOBJ o, uint8_t beautify);
/**
* Updates a Hash using JSON data.
*
* Parsing errors and non-dictionary object JSON data are silently ignored,
* attempting to update the Hash as much as possible before any errors
* encountered.
*
* Conflicting Hash data is overwritten (preferring the new over the old).
*
* Returns the number of bytes consumed. On Error, 0 is returned and no data is
* consumed.
*/
FIOBJ_FUNC size_t FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
update_json)(FIOBJ hash, fio_str_info_s str);
/** Helper function, calls `fiobj_hash_update_json` with string information */
FIO_IFUNC size_t FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
update_json2)(FIOBJ hash, char *ptr, size_t len);
/**
* Parses a C string for JSON data. If `consumed` is not NULL, the `size_t`
* variable will contain the number of bytes consumed before the parser stopped
* (due to either error or end of a valid JSON data segment).
*
* Returns a FIOBJ object matching the JSON valid C string `str`.
*
* If the parsing failed (no complete valid JSON data) `FIOBJ_INVALID` is
* returned.
*/
FIOBJ_FUNC FIOBJ fiobj_json_parse(fio_str_info_s str, size_t *consumed);
/** Helper macro, calls `fiobj_json_parse` with string information */
#define fiobj_json_parse2(data_, len_, consumed) \
fiobj_json_parse((fio_str_info_s){.buf = data_, .len = len_}, consumed)
/**
* Uses JavaScript style notation to find data in an object structure.
*
* For example, "[0].name" will return the "name" property of the first object
* in an array object.
*
* Returns a temporary reference to the object or FIOBJ_INVALID on an error.
*
* Use `fiobj_dup` to collect an actual reference to the returned object.
*/
FIOBJ_FUNC FIOBJ fiobj_json_find(FIOBJ object, fio_str_info_s notation);
/**
* Uses JavaScript style notation to find data in an object structure.
*
* For example, "[0].name" will return the "name" property of the first object
* in an array object.
*
* Returns a temporary reference to the object or FIOBJ_INVALID on an error.
*
* Use `fiobj_dup` to collect an actual reference to the returned object.
*/
#define fiobj_json_find2(object, str, length) \
fiobj_json_find(object, (fio_str_info_s){.buf = str, .len = length})
/* *****************************************************************************
FIOBJ - Implementation - Inline / Macro like fucntions
***************************************************************************** */
/* *****************************************************************************
The FIOBJ Type
***************************************************************************** */
/** Returns an objects type. This isn't limited to known types. */
FIO_IFUNC size_t fiobj_type(FIOBJ o) {
switch (FIOBJ_TYPE_CLASS(o)) {
case FIOBJ_T_PRIMITIVE:
switch ((uintptr_t)(o)) {
case FIOBJ_T_NULL:
return FIOBJ_T_NULL;
case FIOBJ_T_TRUE:
return FIOBJ_T_TRUE;
case FIOBJ_T_FALSE:
return FIOBJ_T_FALSE;
};
return FIOBJ_T_INVALID;
case FIOBJ_T_NUMBER:
return FIOBJ_T_NUMBER;
case FIOBJ_T_FLOAT:
return FIOBJ_T_FLOAT;
case FIOBJ_T_STRING:
return FIOBJ_T_STRING;
case FIOBJ_T_ARRAY:
return FIOBJ_T_ARRAY;
case FIOBJ_T_HASH:
return FIOBJ_T_HASH;
case FIOBJ_T_OTHER:
return (*fiobj_object_metadata(o))->type_id;
}
if (!o)
return FIOBJ_T_NULL;
return FIOBJ_T_INVALID;
}
/* *****************************************************************************
FIOBJ Memory Management
***************************************************************************** */
/** Increases an object's reference count (or copies) and returns it. */
FIO_IFUNC FIOBJ fiobj_dup(FIOBJ o) {
switch (FIOBJ_TYPE_CLASS(o)) {
case FIOBJ_T_PRIMITIVE: /* fallthrough */
case FIOBJ_T_NUMBER: /* fallthrough */
case FIOBJ_T_FLOAT: /* fallthrough */
return o;
case FIOBJ_T_STRING: /* fallthrough */
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), dup)(o);
break;
case FIOBJ_T_ARRAY: /* fallthrough */
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), dup)(o);
break;
case FIOBJ_T_HASH: /* fallthrough */
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), dup)(o);
break;
case FIOBJ_T_OTHER: /* fallthrough */
fiobj_object_dup(o);
}
return o;
}
/** Decreases an object's reference count or frees it. */
FIO_IFUNC void fiobj_free(FIOBJ o) {
switch (FIOBJ_TYPE_CLASS(o)) {
case FIOBJ_T_PRIMITIVE: /* fallthrough */
case FIOBJ_T_NUMBER: /* fallthrough */
case FIOBJ_T_FLOAT:
return;
case FIOBJ_T_STRING:
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), free)(o);
return;
case FIOBJ_T_ARRAY:
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), free)(o);
return;
case FIOBJ_T_HASH:
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), free)(o);
return;
case FIOBJ_T_OTHER:
(*fiobj_object_metadata(o))->free2(o);
return;
}
}
/* *****************************************************************************
FIOBJ Data / Info
***************************************************************************** */
/** Internal: compares two nestable objects. */
FIOBJ_FUNC unsigned char fiobj___test_eq_nested(FIOBJ restrict a,
FIOBJ restrict b);
/** Compares two objects. */
FIO_IFUNC unsigned char FIO_NAME_BL(fiobj, eq)(FIOBJ a, FIOBJ b) {
if (a == b)
return 1;
if (FIOBJ_TYPE_CLASS(a) != FIOBJ_TYPE_CLASS(b))
return 0;
switch (FIOBJ_TYPE_CLASS(a)) {
case FIOBJ_T_PRIMITIVE:
case FIOBJ_T_NUMBER: /* fallthrough */
case FIOBJ_T_FLOAT: /* fallthrough */
return a == b;
case FIOBJ_T_STRING:
return FIO_NAME_BL(FIO_NAME(fiobj, FIOBJ___NAME_STRING), eq)(a, b);
case FIOBJ_T_ARRAY:
return fiobj___test_eq_nested(a, b);
case FIOBJ_T_HASH:
return fiobj___test_eq_nested(a, b);
case FIOBJ_T_OTHER:
if ((*fiobj_object_metadata(a))->count(a) ||
(*fiobj_object_metadata(b))->count(b)) {
if ((*fiobj_object_metadata(a))->count(a) !=
(*fiobj_object_metadata(b))->count(b))
return 0;
return fiobj___test_eq_nested(a, b);
}
return (*fiobj_object_metadata(a))->type_id ==
(*fiobj_object_metadata(b))->type_id &&
(*fiobj_object_metadata(a))->is_eq(a, b);
}
return 0;
}
#define FIOBJ2CSTR_BUFFER_LIMIT 4096
__thread char __attribute__((weak))
fiobj___2cstr___buffer__perthread[FIOBJ2CSTR_BUFFER_LIMIT];
/** Returns a temporary String representation for any FIOBJ object. */
FIO_IFUNC fio_str_info_s FIO_NAME2(fiobj, cstr)(FIOBJ o) {
switch (FIOBJ_TYPE_CLASS(o)) {
case FIOBJ_T_PRIMITIVE:
switch ((uintptr_t)(o)) {
case FIOBJ_T_NULL:
return (fio_str_info_s){.buf = (char *)"null", .len = 4};
case FIOBJ_T_TRUE:
return (fio_str_info_s){.buf = (char *)"true", .len = 4};
case FIOBJ_T_FALSE:
return (fio_str_info_s){.buf = (char *)"false", .len = 5};
};
return (fio_str_info_s){.buf = (char *)""};
case FIOBJ_T_NUMBER:
return FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), cstr)(o);
case FIOBJ_T_FLOAT:
return FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), cstr)(o);
case FIOBJ_T_STRING:
return FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), info)(o);
case FIOBJ_T_ARRAY: /* fallthrough */
case FIOBJ_T_HASH: {
FIOBJ j = FIO_NAME2(fiobj, json)(FIOBJ_INVALID, o, 0);
if (!j || FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(j) >=
FIOBJ2CSTR_BUFFER_LIMIT) {
fiobj_free(j);
return (fio_str_info_s){.buf = (FIOBJ_TYPE_CLASS(o) == FIOBJ_T_ARRAY
? (char *)"[...]"
: (char *)"{...}"),
.len = 5};
}
fio_str_info_s i = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), info)(j);
FIO_MEMCPY(fiobj___2cstr___buffer__perthread, i.buf, i.len + 1);
fiobj_free(j);
i.buf = fiobj___2cstr___buffer__perthread;
return i;
}
case FIOBJ_T_OTHER:
return (*fiobj_object_metadata(o))->to_s(o);
}
if (!o)
return (fio_str_info_s){.buf = (char *)"null", .len = 4};
return (fio_str_info_s){.buf = (char *)""};
}
/** Returns an integer representation for any FIOBJ object. */
FIO_IFUNC intptr_t FIO_NAME2(fiobj, i)(FIOBJ o) {
fio_str_info_s tmp;
switch (FIOBJ_TYPE_CLASS(o)) {
case FIOBJ_T_PRIMITIVE:
switch ((uintptr_t)(o)) {
case FIOBJ_T_NULL:
return 0;
case FIOBJ_T_TRUE:
return 1;
case FIOBJ_T_FALSE:
return 0;
};
return -1;
case FIOBJ_T_NUMBER:
return FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), i)(o);
case FIOBJ_T_FLOAT:
return FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), i)(o);
case FIOBJ_T_STRING:
tmp = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), info)(o);
if (!tmp.len)
return 0;
return fio_atol(&tmp.buf);
case FIOBJ_T_ARRAY:
return FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), count)(o);
case FIOBJ_T_HASH:
return FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), count)(o);
case FIOBJ_T_OTHER:
return (*fiobj_object_metadata(o))->to_i(o);
}
if (!o)
return 0;
return -1;
}
/** Returns a float (double) representation for any FIOBJ object. */
FIO_IFUNC double FIO_NAME2(fiobj, f)(FIOBJ o) {
fio_str_info_s tmp;
switch (FIOBJ_TYPE_CLASS(o)) {
case FIOBJ_T_PRIMITIVE:
switch ((uintptr_t)(o)) {
case FIOBJ_T_FALSE: /* fallthrough */
case FIOBJ_T_NULL:
return 0.0;
case FIOBJ_T_TRUE:
return 1.0;
};
return -1.0;
case FIOBJ_T_NUMBER:
return FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), f)(o);
case FIOBJ_T_FLOAT:
return FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), f)(o);
case FIOBJ_T_STRING:
tmp = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), info)(o);
if (!tmp.len)
return 0;
return (double)fio_atof(&tmp.buf);
case FIOBJ_T_ARRAY:
return (double)FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), count)(o);
case FIOBJ_T_HASH:
return (double)FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), count)(o);
case FIOBJ_T_OTHER:
return (*fiobj_object_metadata(o))->to_f(o);
}
if (!o)
return 0.0;
return -1.0;
}
/* *****************************************************************************
FIOBJ Integers
***************************************************************************** */
#define FIO_REF_NAME fiobj___bignum
#define FIO_REF_TYPE intptr_t
#define FIO_REF_METADATA const FIOBJ_class_vtable_s *
#define FIO_REF_METADATA_INIT(m) \
do { \
m = &FIOBJ___NUMBER_CLASS_VTBL; \
FIOBJ_MARK_MEMORY_ALLOC(); \
} while (0)
#define FIO_REF_METADATA_DESTROY(m) \
do { \
FIOBJ_MARK_MEMORY_FREE(); \
} while (0)
#define FIO_PTR_TAG(p) FIOBJ_PTR_TAG(p, FIOBJ_T_OTHER)
#define FIO_PTR_UNTAG(p) FIOBJ_PTR_UNTAG(p)
#define FIO_PTR_TAG_TYPE FIOBJ
#define FIO_MEM_REALLOC_ FIOBJ_MEM_REALLOC
#define FIO_MEM_FREE_ FIOBJ_MEM_FREE
#define FIO_MEM_REALLOC_IS_SAFE_ FIOBJ_MEM_REALLOC_IS_SAFE
#include __FILE__
#define FIO_NUMBER_ENCODE(i) (((uintptr_t)(i) << 3) | FIOBJ_T_NUMBER)
#define FIO_NUMBER_REVESE(i) \
((intptr_t)(((uintptr_t)(i) >> 3) | \
((((uintptr_t)(i) >> ((sizeof(uintptr_t) * 8) - 1)) * \
((uintptr_t)3 << ((sizeof(uintptr_t) * 8) - 3))))))
/** Creates a new Number object. */
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER),
new)(intptr_t i) {
FIOBJ o = (FIOBJ)FIO_NUMBER_ENCODE(i);
if (FIO_NUMBER_REVESE(o) == i)
return o;
o = fiobj___bignum_new2();
FIO_PTR_MATH_RMASK(intptr_t, o, 3)[0] = i;
return o;
}
/** Reads the number from a FIOBJ number. */
FIO_IFUNC intptr_t FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), i)(FIOBJ i) {
if (FIOBJ_TYPE_CLASS(i) == FIOBJ_T_NUMBER)
return FIO_NUMBER_REVESE(i);
return FIO_PTR_MATH_RMASK(intptr_t, i, 3)[0];
}
/** Reads the number from a FIOBJ number, fitting it in a double. */
FIO_IFUNC double FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), f)(FIOBJ i) {
return (double)FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), i)(i);
}
/** Frees a FIOBJ number. */
FIO_IFUNC void FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), free)(FIOBJ i) {
if (FIOBJ_TYPE_CLASS(i) == FIOBJ_T_NUMBER)
return;
fiobj___bignum_free2(i);
return;
}
#undef FIO_NUMBER_ENCODE
#undef FIO_NUMBER_REVESE
/* *****************************************************************************
FIOBJ Floats
***************************************************************************** */
#define FIO_REF_NAME fiobj___bigfloat
#define FIO_REF_TYPE double
#define FIO_REF_METADATA const FIOBJ_class_vtable_s *
#define FIO_REF_METADATA_INIT(m) \
do { \
m = &FIOBJ___FLOAT_CLASS_VTBL; \
FIOBJ_MARK_MEMORY_ALLOC(); \
} while (0)
#define FIO_REF_METADATA_DESTROY(m) \
do { \
FIOBJ_MARK_MEMORY_FREE(); \
} while (0)
#define FIO_PTR_TAG(p) FIOBJ_PTR_TAG(p, FIOBJ_T_OTHER)
#define FIO_PTR_UNTAG(p) FIOBJ_PTR_UNTAG(p)
#define FIO_PTR_TAG_TYPE FIOBJ
#define FIO_MEM_REALLOC_ FIOBJ_MEM_REALLOC
#define FIO_MEM_FREE_ FIOBJ_MEM_FREE
#define FIO_MEM_REALLOC_IS_SAFE_ FIOBJ_MEM_REALLOC_IS_SAFE
#include __FILE__
/** Creates a new Float object. */
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), new)(double i) {
FIOBJ ui;
if (sizeof(double) <= sizeof(FIOBJ)) {
union {
double d;
uintptr_t i;
} punned;
punned.i = 0; /* dead code, but leave it, just in case */
punned.d = i;
if ((punned.i & 7) == 0) {
return (FIOBJ)(punned.i | FIOBJ_T_FLOAT);
}
}
ui = fiobj___bigfloat_new2();
FIO_PTR_MATH_RMASK(double, ui, 3)[0] = i;
return ui;
}
/** Reads the integer part from a FIOBJ Float. */
FIO_IFUNC intptr_t FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), i)(FIOBJ i) {
return (intptr_t)floor(FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), f)(i));
}
/** Reads the number from a FIOBJ number, fitting it in a double. */
FIO_IFUNC double FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), f)(FIOBJ i) {
if (sizeof(double) <= sizeof(FIOBJ) && FIOBJ_TYPE_CLASS(i) == FIOBJ_T_FLOAT) {
union {
double d;
uint64_t i;
} punned;
punned.d = 0; /* dead code, but leave it, just in case */
punned.i = (uint64_t)(uintptr_t)i;
punned.i = ((uint64_t)(uintptr_t)i & (~(uintptr_t)7ULL));
return punned.d;
}
return FIO_PTR_MATH_RMASK(double, i, 3)[0];
}
/** Frees a FIOBJ number. */
FIO_IFUNC void FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), free)(FIOBJ i) {
if (FIOBJ_TYPE_CLASS(i) == FIOBJ_T_FLOAT)
return;
fiobj___bigfloat_free2(i);
return;
}
/* *****************************************************************************
FIOBJ Basic Iteration
***************************************************************************** */
/**
* Performs a task for each element held by the FIOBJ object.
*
* If `task` returns -1, the `each` loop will break (stop).
*
* Returns the "stop" position - the number of elements processed + `start_at`.
*/
FIO_SFUNC uint32_t fiobj_each1(FIOBJ o,
int32_t start_at,
int (*task)(FIOBJ child, void *arg),
void *arg) {
switch (FIOBJ_TYPE_CLASS(o)) {
case FIOBJ_T_PRIMITIVE: /* fallthrough */
case FIOBJ_T_NUMBER: /* fallthrough */
case FIOBJ_T_STRING: /* fallthrough */
case FIOBJ_T_FLOAT:
return 0;
case FIOBJ_T_ARRAY:
return FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY),
each)(o, start_at, task, arg);
case FIOBJ_T_HASH:
return FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
each)(o, start_at, task, arg);
case FIOBJ_T_OTHER:
return (*fiobj_object_metadata(o))->each1(o, start_at, task, arg);
}
return 0;
}
/* *****************************************************************************
FIOBJ Hash Maps
***************************************************************************** */
/** Calculates an object's hash value for a specific hash map object. */
FIO_IFUNC uint64_t FIO_NAME2(fiobj, hash)(FIOBJ target_hash, FIOBJ o) {
switch (FIOBJ_TYPE_CLASS(o)) {
case FIOBJ_T_PRIMITIVE:
return fio_risky_hash(&o,
sizeof(o),
(uint64_t)(uintptr_t)target_hash + (uintptr_t)o);
case FIOBJ_T_NUMBER: {
uintptr_t tmp = FIO_NAME2(fiobj, i)(o);
return fio_risky_hash(&tmp, sizeof(tmp), (uint64_t)(uintptr_t)target_hash);
}
case FIOBJ_T_FLOAT: {
double tmp = FIO_NAME2(fiobj, f)(o);
return fio_risky_hash(&tmp, sizeof(tmp), (uint64_t)(uintptr_t)target_hash);
}
case FIOBJ_T_STRING: /* fallthrough */
return FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING),
hash)(o, (uint64_t)(uintptr_t)target_hash);
case FIOBJ_T_ARRAY: {
uint64_t h = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), count)(o);
h += fio_risky_hash(&h,
sizeof(h),
(uint64_t)(uintptr_t)target_hash + FIOBJ_T_ARRAY);
{
FIOBJ *a = FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), ptr)(o);
const size_t count =
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), count)(o);
if (a) {
for (size_t i = 0; i < count; ++i) {
h += FIO_NAME2(fiobj, hash)(target_hash + FIOBJ_T_ARRAY + i, a[i]);
}
}
}
return h;
}
case FIOBJ_T_HASH: {
uint64_t h = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), count)(o);
size_t c = 0;
h += fio_risky_hash(&h,
sizeof(h),
(uint64_t)(uintptr_t)target_hash + FIOBJ_T_HASH);
FIO_MAP_EACH(FIO_NAME(fiobj, FIOBJ___NAME_HASH), o, pos) {
h += FIO_NAME2(fiobj, hash)(target_hash + FIOBJ_T_HASH + (c++),
pos->obj.key);
h += FIO_NAME2(fiobj, hash)(target_hash + FIOBJ_T_HASH + (c++),
pos->obj.value);
}
return h;
}
case FIOBJ_T_OTHER: {
/* TODO: can we avoid "stringifying" the object? */
fio_str_info_s tmp = (*fiobj_object_metadata(o))->to_s(o);
return fio_risky_hash(tmp.buf, tmp.len, (uint64_t)(uintptr_t)target_hash);
}
}
return 0;
}
/** Inserts a value to a hash map, with a default hash value calculation. */
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
set2)(FIOBJ hash, FIOBJ key, FIOBJ value) {
return FIO_NAME(
FIO_NAME(fiobj, FIOBJ___NAME_HASH),
set)(hash, FIO_NAME2(fiobj, hash)(hash, key), key, value, NULL);
}
/**
* Inserts a value to a hash map, with a default hash value calculation.
*
* If the key already exists in the Hash Map, the value will be freed instead.
*/
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
set_if_missing2)(FIOBJ hash, FIOBJ key, FIOBJ value) {
return FIO_NAME(
FIO_NAME(fiobj, FIOBJ___NAME_HASH),
set_if_missing)(hash, FIO_NAME2(fiobj, hash)(hash, key), key, value);
}
/** Finds a value in a hash map, automatically calculating the hash value. */
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), get2)(FIOBJ hash,
FIOBJ key) {
if (FIOBJ_TYPE_CLASS(hash) != FIOBJ_T_HASH)
return FIOBJ_INVALID;
return FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
get)(hash, FIO_NAME2(fiobj, hash)(hash, key), key);
}
/** Removes a value from a hash map, with a default hash value calculation. */
FIO_IFUNC int FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
remove2)(FIOBJ hash, FIOBJ key, FIOBJ *old) {
return FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
remove)(hash, FIO_NAME2(fiobj, hash)(hash, key), key, old);
}
/**
* Sets a String value in a hash map, allocating the String and automatically
* calculating the hash value.
*/
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
set3)(FIOBJ hash,
const char *key,
size_t len,
FIOBJ value) {
FIOBJ tmp = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), new)();
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)(tmp, (char *)key, len);
FIOBJ v = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
set)(hash,
fio_risky_hash(key, len, (uint64_t)(uintptr_t)hash),
tmp,
value,
NULL);
fiobj_free(tmp);
return v;
}
/**
* Finds a String value in a hash map, using a temporary String and
* automatically calculating the hash value.
*/
FIO_IFUNC FIOBJ FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
get3)(FIOBJ hash, const char *buf, size_t len) {
if (FIOBJ_TYPE_CLASS(hash) != FIOBJ_T_HASH)
return FIOBJ_INVALID;
FIOBJ_STR_TEMP_VAR_STATIC(tmp, buf, len);
FIOBJ v = FIO_NAME(
FIO_NAME(fiobj, FIOBJ___NAME_HASH),
get)(hash, fio_risky_hash(buf, len, (uint64_t)(uintptr_t)hash), tmp);
return v;
}
/**
* Removes a String value in a hash map, using a temporary String and
* automatically calculating the hash value.
*/
FIO_IFUNC int FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
remove3)(FIOBJ hash,
const char *buf,
size_t len,
FIOBJ *old) {
FIOBJ_STR_TEMP_VAR_STATIC(tmp, buf, len);
int r = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
remove)(hash,
fio_risky_hash(buf, len, (uint64_t)(uintptr_t)hash),
tmp,
old);
FIOBJ_STR_TEMP_DESTROY(tmp);
return r;
}
/** Updates a hash using information from another Hash. */
FIO_IFUNC void FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), update)(FIOBJ dest,
FIOBJ src) {
if (FIOBJ_TYPE_CLASS(dest) != FIOBJ_T_HASH ||
FIOBJ_TYPE_CLASS(src) != FIOBJ_T_HASH)
return;
FIO_MAP_EACH(FIO_NAME(fiobj, FIOBJ___NAME_HASH), src, i) {
if (i->obj.key == FIOBJ_INVALID ||
FIOBJ_TYPE_CLASS(i->obj.key) == FIOBJ_T_NULL) {
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), remove2)
(dest, i->obj.key, NULL);
continue;
}
register FIOBJ tmp;
switch (FIOBJ_TYPE_CLASS(i->obj.value)) {
case FIOBJ_T_ARRAY:
/* TODO? decide if we should merge elements or overwrite...? */
tmp =
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), get2)(dest, i->obj.key);
if (FIOBJ_TYPE_CLASS(tmp) == FIOBJ_T_ARRAY) {
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), concat)
(tmp, i->obj.value);
continue;
}
break;
case FIOBJ_T_HASH:
tmp =
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), get2)(dest, i->obj.key);
if (FIOBJ_TYPE_CLASS(tmp) == FIOBJ_T_HASH)
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), update)
(dest, i->obj.value);
else break;
continue;
case FIOBJ_T_NUMBER: /* fallthrough */
case FIOBJ_T_PRIMITIVE: /* fallthrough */
case FIOBJ_T_STRING: /* fallthrough */
case FIOBJ_T_FLOAT: /* fallthrough */
case FIOBJ_T_OTHER:
break;
}
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), set2)
(dest, i->obj.key, fiobj_dup(i->obj.value));
}
}
/* *****************************************************************************
FIOBJ JSON support (inline functions)
***************************************************************************** */
typedef struct {
FIOBJ json;
size_t level;
uint8_t beautify;
} fiobj___json_format_internal__s;
/* internal helper funnction for recursive JSON formatting. */
FIOBJ_FUNC void fiobj___json_format_internal__(
fiobj___json_format_internal__s *,
FIOBJ);
/** Helper function, calls `fiobj_hash_update_json` with string information */
FIO_IFUNC size_t FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
update_json2)(FIOBJ hash, char *ptr, size_t len) {
return FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
update_json)(hash, (fio_str_info_s){.buf = ptr, .len = len});
}
/**
* Returns a JSON valid FIOBJ String, representing the object.
*
* If `dest` is an existing String, the formatted JSON data will be appended to
* the existing string.
*/
FIO_IFUNC FIOBJ FIO_NAME2(fiobj, json)(FIOBJ dest, FIOBJ o, uint8_t beautify) {
fiobj___json_format_internal__s args =
(fiobj___json_format_internal__s){.json = dest, .beautify = beautify};
if (FIOBJ_TYPE_CLASS(dest) != FIOBJ_T_STRING)
args.json = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), new)();
fiobj___json_format_internal__(&args, o);
return args.json;
}
/* *****************************************************************************
FIOBJ - Implementation
***************************************************************************** */
#ifdef FIOBJ_EXTERN_COMPLETE
/* *****************************************************************************
FIOBJ Basic Object vtable
***************************************************************************** */
FIOBJ_EXTERN_OBJ_IMP const FIOBJ_class_vtable_s FIOBJ___OBJECT_CLASS_VTBL = {
.type_id = 99, /* type IDs below 100 are reserved. */
};
/* *****************************************************************************
FIOBJ Complex Iteration
***************************************************************************** */
typedef struct {
FIOBJ obj;
size_t pos;
} fiobj____stack_element_s;
#define FIO_ARRAY_NAME fiobj____active_stack
#define FIO_ARRAY_TYPE fiobj____stack_element_s
#define FIO_ARRAY_COPY(dest, src) \
do { \
(dest).obj = fiobj_dup((src).obj); \
(dest).pos = (src).pos; \
} while (0)
#define FIO_ARRAY_TYPE_CMP(a, b) (a).obj == (b).obj
#define FIO_ARRAY_DESTROY(o) fiobj_free(o)
#define FIO_MEM_REALLOC_ FIOBJ_MEM_REALLOC
#define FIO_MEM_FREE_ FIOBJ_MEM_FREE
#define FIO_MEM_REALLOC_IS_SAFE_ FIOBJ_MEM_REALLOC_IS_SAFE
#include __FILE__
#define FIO_ARRAY_TYPE_CMP(a, b) (a).obj == (b).obj
#define FIO_ARRAY_NAME fiobj____stack
#define FIO_ARRAY_TYPE fiobj____stack_element_s
#define FIO_MEM_REALLOC_ FIOBJ_MEM_REALLOC
#define FIO_MEM_FREE_ FIOBJ_MEM_FREE
#define FIO_MEM_REALLOC_IS_SAFE_ FIOBJ_MEM_REALLOC_IS_SAFE
#include __FILE__
typedef struct {
int (*task)(FIOBJ, void *);
void *arg;
FIOBJ next;
size_t count;
fiobj____stack_s stack;
uint32_t end;
uint8_t stop;
} fiobj_____each2_data_s;
FIO_SFUNC uint32_t fiobj____each2_element_count(FIOBJ o) {
switch (FIOBJ_TYPE_CLASS(o)) {
case FIOBJ_T_PRIMITIVE: /* fallthrough */
case FIOBJ_T_NUMBER: /* fallthrough */
case FIOBJ_T_STRING: /* fallthrough */
case FIOBJ_T_FLOAT:
return 0;
case FIOBJ_T_ARRAY:
return FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), count)(o);
case FIOBJ_T_HASH:
return FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), count)(o);
case FIOBJ_T_OTHER: /* fallthrough */
return (*fiobj_object_metadata(o))->count(o);
}
return 0;
}
FIO_SFUNC int fiobj____each2_wrapper_task(FIOBJ child, void *arg) {
fiobj_____each2_data_s *d = (fiobj_____each2_data_s *)arg;
d->stop = (d->task(child, d->arg) == -1);
++d->count;
if (d->stop)
return -1;
uint32_t c = fiobj____each2_element_count(child);
if (c) {
d->next = child;
d->end = c;
return -1;
}
return 0;
}
/**
* Performs a task for the object itself and each element held by the FIOBJ
* object or any of it's elements (a deep task).
*
* The order of performance is by order of appearance, as if all nesting levels
* were flattened.
*
* If `task` returns -1, the `each` loop will break (stop).
*
* Returns the number of elements processed.
*/
FIOBJ_FUNC uint32_t fiobj_each2(FIOBJ o,
int (*task)(FIOBJ child, void *arg),
void *arg) {
/* TODO - move to recursion with nesting limiter? */
fiobj_____each2_data_s d = {
.task = task,
.arg = arg,
.next = FIOBJ_INVALID,
.stack = FIO_ARRAY_INIT,
};
fiobj____stack_element_s i = {.obj = o, .pos = 0};
uint32_t end = fiobj____each2_element_count(o);
fiobj____each2_wrapper_task(i.obj, &d);
while (!d.stop && i.obj && i.pos < end) {
i.pos = fiobj_each1(i.obj, i.pos, fiobj____each2_wrapper_task, &d);
if (d.next != FIOBJ_INVALID) {
if (fiobj____stack_count(&d.stack) + 1 > FIOBJ_MAX_NESTING) {
FIO_LOG_ERROR("FIOBJ nesting level too deep (%u)."
"`fiobj_each2` stopping loop early.",
(unsigned int)fiobj____stack_count(&d.stack));
d.stop = 1;
continue;
}
fiobj____stack_push(&d.stack, i);
i.pos = 0;
i.obj = d.next;
d.next = FIOBJ_INVALID;
end = d.end;
} else {
/* re-collect end position to acommodate for changes */
end = fiobj____each2_element_count(i.obj);
}
while (i.pos >= end && fiobj____stack_count(&d.stack)) {
fiobj____stack_pop(&d.stack, &i);
end = fiobj____each2_element_count(i.obj);
}
};
fiobj____stack_destroy(&d.stack);
return d.count;
}
/* *****************************************************************************
FIOBJ Hash / Array / Other (enumerable) Equality test.
***************************************************************************** */
FIO_SFUNC __thread size_t fiobj___test_eq_nested_level = 0;
/** Internal: compares two nestable objects. */
FIOBJ_FUNC unsigned char fiobj___test_eq_nested(FIOBJ restrict a,
FIOBJ restrict b) {
if (a == b)
return 1;
if (FIOBJ_TYPE_CLASS(a) != FIOBJ_TYPE_CLASS(b))
return 0;
if (fiobj____each2_element_count(a) != fiobj____each2_element_count(b))
return 0;
if (!fiobj____each2_element_count(a))
return 1;
if (fiobj___test_eq_nested_level >= FIOBJ_MAX_NESTING)
return 0;
++fiobj___test_eq_nested_level;
switch (FIOBJ_TYPE_CLASS(a)) {
case FIOBJ_T_PRIMITIVE:
case FIOBJ_T_NUMBER: /* fallthrough */
case FIOBJ_T_FLOAT: /* fallthrough */
case FIOBJ_T_STRING: /* fallthrough */
/* should never happen... this function is for enumerable objects */
return a == b;
case FIOBJ_T_ARRAY:
/* test each array member with matching index */
{
const size_t count = fiobj____each2_element_count(a);
for (size_t i = 0; i < count; ++i) {
if (!FIO_NAME_BL(fiobj, eq)(
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), get)(a, i),
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), get)(b, i)))
goto unequal;
}
}
goto equal;
case FIOBJ_T_HASH:
FIO_MAP_EACH(FIO_NAME(fiobj, FIOBJ___NAME_HASH), a, pos) {
FIOBJ val = fiobj_hash_get2(b, pos->obj.key);
if (!FIO_NAME_BL(fiobj, eq)(val, pos->obj.value))
goto equal;
}
goto equal;
case FIOBJ_T_OTHER:
return (*fiobj_object_metadata(a))->is_eq(a, b);
}
equal:
--fiobj___test_eq_nested_level;
return 1;
unequal:
--fiobj___test_eq_nested_level;
return 0;
}
/* *****************************************************************************
FIOBJ general helpers
***************************************************************************** */
FIO_SFUNC __thread char fiobj___tmp_buffer[256];
FIO_SFUNC uint32_t fiobj___count_noop(FIOBJ o) {
return 0;
(void)o;
}
/* *****************************************************************************
FIOBJ Integers (bigger numbers)
***************************************************************************** */
FIO_IFUNC unsigned char FIO_NAME_BL(fiobj___num, eq)(FIOBJ restrict a,
FIOBJ restrict b) {
return FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), i)(a) ==
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), i)(b);
}
FIOBJ_FUNC fio_str_info_s FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER),
cstr)(FIOBJ i) {
size_t len = fio_ltoa(fiobj___tmp_buffer,
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), i)(i),
10);
fiobj___tmp_buffer[len] = 0;
return (fio_str_info_s){.buf = fiobj___tmp_buffer, .len = len};
}
FIOBJ_EXTERN_OBJ_IMP const FIOBJ_class_vtable_s FIOBJ___NUMBER_CLASS_VTBL = {
/**
* MUST return a unique number to identify object type.
*
* Numbers (IDs) under 100 are reserved.
*/
.type_id = FIOBJ_T_NUMBER,
/** Test for equality between two objects with the same `type_id` */
.is_eq = FIO_NAME_BL(fiobj___num, eq),
/** Converts an object to a String */
.to_s = FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), cstr),
/** Converts and object to an integer */
.to_i = FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), i),
/** Converts and object to a float */
.to_f = FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), f),
/** Returns the number of exposed elements held by the object, if any. */
.count = fiobj___count_noop,
/** Iterates the exposed elements held by the object. See `fiobj_each1`. */
.each1 = NULL,
/** Deallocates the element (but NOT any of it's exposed elements). */
.free2 = fiobj___bignum_free2,
};
/* *****************************************************************************
FIOBJ Floats (bigger / smaller doubles)
***************************************************************************** */
FIO_SFUNC unsigned char FIO_NAME_BL(fiobj___float, eq)(FIOBJ restrict a,
FIOBJ restrict b) {
unsigned char r = 0;
union {
uint64_t u;
double f;
} da, db;
da.f = FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), f)(a);
db.f = FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), f)(b);
/* regular equality? */
r |= da.f == db.f;
/* test for small rounding errors (4 bit difference) on normalize floats */
r |= !((da.u ^ db.u) & UINT64_C(0xFFFFFFFFFFFFFFF0)) &&
(da.u & UINT64_C(0x7FF0000000000000));
/* test for small ULP: */
r |= (((da.u > db.u) ? da.u - db.u : db.u - da.u) < 2);
/* test for +-0 */
r |= !((da.u | db.u) & UINT64_C(0x7FFFFFFFFFFFFFFF));
return r;
}
FIOBJ_FUNC fio_str_info_s FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT),
cstr)(FIOBJ i) {
size_t len = fio_ftoa(fiobj___tmp_buffer,
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), f)(i),
10);
fiobj___tmp_buffer[len] = 0;
return (fio_str_info_s){.buf = fiobj___tmp_buffer, .len = len};
}
FIOBJ_EXTERN_OBJ_IMP const FIOBJ_class_vtable_s FIOBJ___FLOAT_CLASS_VTBL = {
/**
* MUST return a unique number to identify object type.
*
* Numbers (IDs) under 100 are reserved.
*/
.type_id = FIOBJ_T_FLOAT,
/** Test for equality between two objects with the same `type_id` */
.is_eq = FIO_NAME_BL(fiobj___float, eq),
/** Converts an object to a String */
.to_s = FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), cstr),
/** Converts and object to an integer */
.to_i = FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), i),
/** Converts and object to a float */
.to_f = FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), f),
/** Returns the number of exposed elements held by the object, if any. */
.count = fiobj___count_noop,
/** Iterates the exposed elements held by the object. See `fiobj_each1`. */
.each1 = NULL,
/** Deallocates the element (but NOT any of it's exposed elements). */
.free2 = fiobj___bigfloat_free2,
};
/* *****************************************************************************
FIOBJ JSON support - output
***************************************************************************** */
FIO_IFUNC void fiobj___json_format_internal_beauty_pad(FIOBJ json,
size_t level) {
size_t pos = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(json);
fio_str_info_s tmp = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING),
resize)(json, (level << 1) + pos + 2);
tmp.buf[pos++] = '\r';
tmp.buf[pos++] = '\n';
for (size_t i = 0; i < level; ++i) {
tmp.buf[pos++] = ' ';
tmp.buf[pos++] = ' ';
}
}
FIOBJ_FUNC void fiobj___json_format_internal__(
fiobj___json_format_internal__s *args,
FIOBJ o) {
switch (FIOBJ_TYPE(o)) {
case FIOBJ_T_TRUE: /* fallthrough */
case FIOBJ_T_FALSE: /* fallthrough */
case FIOBJ_T_NULL: /* fallthrough */
case FIOBJ_T_NUMBER: /* fallthrough */
case FIOBJ_T_FLOAT: /* fallthrough */
{
fio_str_info_s info = FIO_NAME2(fiobj, cstr)(o);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)
(args->json, info.buf, info.len);
return;
}
case FIOBJ_T_STRING: /* fallthrough */
default: {
fio_str_info_s info = FIO_NAME2(fiobj, cstr)(o);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)(args->json, "\"", 1);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write_escape)
(args->json, info.buf, info.len);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)(args->json, "\"", 1);
return;
}
case FIOBJ_T_ARRAY:
if (args->level == FIOBJ_MAX_NESTING) {
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)
(args->json, "[ ]", 3);
return;
}
{
++args->level;
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)(args->json, "[", 1);
const uint32_t len =
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), count)(o);
for (size_t i = 0; i < len; ++i) {
if (args->beautify) {
fiobj___json_format_internal_beauty_pad(args->json, args->level);
}
FIOBJ child = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), get)(o, i);
fiobj___json_format_internal__(args, child);
if (i + 1 < len)
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)
(args->json, ",", 1);
}
--args->level;
if (args->beautify) {
fiobj___json_format_internal_beauty_pad(args->json, args->level);
}
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)(args->json, "]", 1);
}
return;
case FIOBJ_T_HASH:
if (args->level == FIOBJ_MAX_NESTING) {
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)
(args->json, "{ }", 3);
return;
}
{
++args->level;
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)(args->json, "{", 1);
size_t i = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), count)(o);
if (i) {
FIO_MAP_EACH(FIO_NAME(fiobj, FIOBJ___NAME_HASH), o, couplet) {
if (args->beautify) {
fiobj___json_format_internal_beauty_pad(args->json, args->level);
}
fio_str_info_s info = FIO_NAME2(fiobj, cstr)(couplet->obj.key);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)
(args->json, "\"", 1);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write_escape)
(args->json, info.buf, info.len);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)
(args->json, "\":", 2);
fiobj___json_format_internal__(args, couplet->obj.value);
if (--i)
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)
(args->json, ",", 1);
}
}
--args->level;
if (args->beautify) {
fiobj___json_format_internal_beauty_pad(args->json, args->level);
}
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)(args->json, "}", 1);
}
return;
}
}
/* *****************************************************************************
FIOBJ JSON parsing
***************************************************************************** */
#define FIO_JSON
#include __FILE__
/* FIOBJ JSON parser */
typedef struct {
fio_json_parser_s p;
FIOBJ key;
FIOBJ top;
FIOBJ target;
FIOBJ stack[JSON_MAX_DEPTH + 1];
uint8_t so; /* stack offset */
} fiobj_json_parser_s;
static inline void fiobj_json_add2parser(fiobj_json_parser_s *p, FIOBJ o) {
if (p->top) {
if (FIOBJ_TYPE_CLASS(p->top) == FIOBJ_T_HASH) {
if (p->key) {
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), set2)(p->top, p->key, o);
fiobj_free(p->key);
p->key = FIOBJ_INVALID;
} else {
p->key = o;
}
} else {
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(p->top, o);
}
} else {
p->top = o;
}
}
/** a NULL object was detected */
static inline void fio_json_on_null(fio_json_parser_s *p) {
fiobj_json_add2parser((fiobj_json_parser_s *)p,
FIO_NAME(fiobj, FIOBJ___NAME_NULL)());
}
/** a TRUE object was detected */
static inline void fio_json_on_true(fio_json_parser_s *p) {
fiobj_json_add2parser((fiobj_json_parser_s *)p,
FIO_NAME(fiobj, FIOBJ___NAME_TRUE)());
}
/** a FALSE object was detected */
static inline void fio_json_on_false(fio_json_parser_s *p) {
fiobj_json_add2parser((fiobj_json_parser_s *)p,
FIO_NAME(fiobj, FIOBJ___NAME_FALSE)());
}
/** a Numberl was detected (long long). */
static inline void fio_json_on_number(fio_json_parser_s *p, long long i) {
fiobj_json_add2parser((fiobj_json_parser_s *)p,
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), new)(i));
}
/** a Float was detected (double). */
static inline void fio_json_on_float(fio_json_parser_s *p, double f) {
fiobj_json_add2parser((fiobj_json_parser_s *)p,
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), new)(f));
}
/** a String was detected (int / float). update `pos` to point at ending */
static inline void fio_json_on_string(fio_json_parser_s *p,
const void *start,
size_t len) {
FIOBJ str = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), new)();
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write_unescape)
(str, start, len);
fiobj_json_add2parser((fiobj_json_parser_s *)p, str);
}
/** a dictionary object was detected */
static inline int fio_json_on_start_object(fio_json_parser_s *p) {
fiobj_json_parser_s *pr = (fiobj_json_parser_s *)p;
if (pr->target) {
/* push NULL, don't free the objects */
pr->stack[pr->so++] = FIOBJ_INVALID;
pr->top = pr->target;
pr->target = FIOBJ_INVALID;
} else {
FIOBJ hash;
#if FIOBJ_JSON_APPEND
hash = FIOBJ_INVALID;
if (pr->key && FIOBJ_TYPE_CLASS(pr->top) == FIOBJ_T_HASH) {
hash =
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), get2)(pr->top, pr->key);
}
if (FIOBJ_TYPE_CLASS(hash) != FIOBJ_T_HASH) {
hash = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), new)();
fiobj_json_add2parser(pr, hash);
} else {
fiobj_free(pr->key);
pr->key = FIOBJ_INVALID;
}
#else
hash = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), new)();
fiobj_json_add2parser(pr, hash);
#endif
pr->stack[pr->so++] = pr->top;
pr->top = hash;
}
return 0;
}
/** a dictionary object closure detected */
static inline void fio_json_on_end_object(fio_json_parser_s *p) {
fiobj_json_parser_s *pr = (fiobj_json_parser_s *)p;
if (pr->key) {
FIO_LOG_WARNING("(JSON parsing) malformed JSON, "
"ignoring dangling Hash key.");
fiobj_free(pr->key);
pr->key = FIOBJ_INVALID;
}
pr->top = FIOBJ_INVALID;
if (pr->so)
pr->top = pr->stack[--pr->so];
}
/** an array object was detected */
static int fio_json_on_start_array(fio_json_parser_s *p) {
fiobj_json_parser_s *pr = (fiobj_json_parser_s *)p;
FIOBJ ary = FIOBJ_INVALID;
if (pr->target != FIOBJ_INVALID) {
if (FIOBJ_TYPE_CLASS(pr->target) != FIOBJ_T_ARRAY)
return -1;
ary = pr->target;
pr->target = FIOBJ_INVALID;
}
#if FIOBJ_JSON_APPEND
if (pr->key && FIOBJ_TYPE_CLASS(pr->top) == FIOBJ_T_HASH) {
ary = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), get2)(pr->top, pr->key);
}
if (FIOBJ_TYPE_CLASS(ary) != FIOBJ_T_ARRAY) {
ary = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), new)();
fiobj_json_add2parser(pr, ary);
} else {
fiobj_free(pr->key);
pr->key = FIOBJ_INVALID;
}
#else
FIOBJ ary = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), new)();
fiobj_json_add2parser(pr, ary);
#endif
pr->stack[pr->so++] = pr->top;
pr->top = ary;
return 0;
}
/** an array closure was detected */
static inline void fio_json_on_end_array(fio_json_parser_s *p) {
fiobj_json_parser_s *pr = (fiobj_json_parser_s *)p;
pr->top = FIOBJ_INVALID;
if (pr->so)
pr->top = pr->stack[--pr->so];
}
/** the JSON parsing is complete */
static void fio_json_on_json(fio_json_parser_s *p) {
(void)p; /* nothing special... right? */
}
/** the JSON parsing is complete */
static inline void fio_json_on_error(fio_json_parser_s *p) {
fiobj_json_parser_s *pr = (fiobj_json_parser_s *)p;
fiobj_free(pr->stack[0]);
fiobj_free(pr->key);
*pr = (fiobj_json_parser_s){.top = FIOBJ_INVALID};
FIO_LOG_DEBUG("JSON on_error callback called.");
}
/**
* Updates a Hash using JSON data.
*
* Parsing errors and non-dictionary object JSON data are silently ignored,
* attempting to update the Hash as much as possible before any errors
* encountered.
*
* Conflicting Hash data is overwritten (preferring the new over the old).
*
* Returns the number of bytes consumed. On Error, 0 is returned and no data is
* consumed.
*/
FIOBJ_FUNC size_t FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH),
update_json)(FIOBJ hash, fio_str_info_s str) {
if (hash == FIOBJ_INVALID)
return 0;
fiobj_json_parser_s p = {.top = FIOBJ_INVALID, .target = hash};
size_t consumed = fio_json_parse(&p.p, str.buf, str.len);
fiobj_free(p.key);
if (p.top != hash)
fiobj_free(p.top);
return consumed;
}
/** Returns a JSON valid FIOBJ String, representing the object. */
FIOBJ_FUNC FIOBJ fiobj_json_parse(fio_str_info_s str, size_t *consumed_p) {
fiobj_json_parser_s p = {.top = FIOBJ_INVALID};
register const size_t consumed = fio_json_parse(&p.p, str.buf, str.len);
if (consumed_p) {
*consumed_p = consumed;
}
if (!consumed || p.p.depth) {
if (p.top) {
FIO_LOG_DEBUG("WARNING - JSON failed secondary validation, no on_error");
}
#ifdef DEBUG
FIOBJ s = FIO_NAME2(fiobj, json)(FIOBJ_INVALID, p.top, 0);
FIO_LOG_DEBUG("JSON data being deleted:\n%s",
FIO_NAME2(fiobj, cstr)(s).buf);
fiobj_free(s);
#endif
fiobj_free(p.stack[0]);
p.top = FIOBJ_INVALID;
}
fiobj_free(p.key);
return p.top;
}
/** Uses JSON (JavaScript) notation to find data in an object structure. Returns
* a temporary object. */
FIOBJ_FUNC FIOBJ fiobj_json_find(FIOBJ o, fio_str_info_s n) {
for (;;) {
top:
if (!n.len)
return o;
switch (FIOBJ_TYPE_CLASS(o)) {
case FIOBJ_T_ARRAY: {
if (n.len <= 2 || n.buf[0] != '[' || n.buf[1] < '0' || n.buf[1] > '9')
return FIOBJ_INVALID;
size_t i = 0;
++n.buf;
--n.len;
while (n.len && fio_c2i(n.buf[0]) < 10) {
i = (i * 10) + fio_c2i(n.buf[0]);
++n.buf;
--n.len;
}
if (!n.len || n.buf[0] != ']')
return FIOBJ_INVALID;
o = fiobj_array_get(o, i);
++n.buf;
--n.len;
if (n.len) {
if (n.buf[0] == '.') {
++n.buf;
--n.len;
} else if (n.buf[0] != '[') {
return FIOBJ_INVALID;
}
continue;
}
return o;
}
case FIOBJ_T_HASH: {
FIOBJ tmp = fiobj_hash_get3(o, n.buf, n.len);
if (tmp != FIOBJ_INVALID)
return tmp;
char *end = n.buf + n.len - 1;
while (end > n.buf) {
while (end > n.buf && end[0] != '.' && end[0] != '[')
--end;
if (end == n.buf)
return FIOBJ_INVALID;
const size_t t_len = end - n.buf;
tmp = fiobj_hash_get3(o, n.buf, t_len);
if (tmp != FIOBJ_INVALID) {
o = tmp;
n.len -= t_len + (end[0] == '.');
n.buf = end + (end[0] == '.');
goto top;
}
--end;
}
} /* fallthrough */
default:
return FIOBJ_INVALID;
}
}
}
/* *****************************************************************************
FIOBJ and JSON testing
***************************************************************************** */
#ifdef FIO_TEST_CSTL
FIO_SFUNC int FIO_NAME_TEST(stl, fiobj_task)(FIOBJ o, void *e_) {
static size_t index = 0;
if (o == FIOBJ_INVALID && !e_) {
index = 0;
return -1;
}
int *expect = (int *)e_;
if (expect[index] == -1) {
FIO_ASSERT(FIOBJ_TYPE(o) == FIOBJ_T_ARRAY,
"each2 ordering issue [%zu] (array).",
index);
} else {
FIO_ASSERT(FIO_NAME2(fiobj, i)(o) == expect[index],
"each2 ordering issue [%zu] (number) %ld != %d",
index,
FIO_NAME2(fiobj, i)(o),
expect[index]);
}
++index;
return 0;
}
FIO_SFUNC void FIO_NAME_TEST(stl, fiobj)(void) {
FIOBJ o = FIOBJ_INVALID;
if (!FIOBJ_MARK_MEMORY_ENABLED) {
FIO_LOG_WARNING("FIOBJ defined without allocation counter. "
"Tests might not be complete.");
}
/* primitives - (in)sanity */
{
fprintf(stderr, "* Testing FIOBJ primitives.\n");
FIO_ASSERT(FIOBJ_TYPE(o) == FIOBJ_T_NULL,
"invalid FIOBJ type should be FIOBJ_T_NULL.");
FIO_ASSERT(!FIO_NAME_BL(fiobj, eq)(o, FIO_NAME(fiobj, FIOBJ___NAME_NULL)()),
"invalid FIOBJ is NOT a fiobj_null().");
FIO_ASSERT(!FIO_NAME_BL(fiobj, eq)(FIO_NAME(fiobj, FIOBJ___NAME_TRUE)(),
FIO_NAME(fiobj, FIOBJ___NAME_NULL)()),
"fiobj_true() is NOT fiobj_null().");
FIO_ASSERT(!FIO_NAME_BL(fiobj, eq)(FIO_NAME(fiobj, FIOBJ___NAME_FALSE)(),
FIO_NAME(fiobj, FIOBJ___NAME_NULL)()),
"fiobj_false() is NOT fiobj_null().");
FIO_ASSERT(!FIO_NAME_BL(fiobj, eq)(FIO_NAME(fiobj, FIOBJ___NAME_FALSE)(),
FIO_NAME(fiobj, FIOBJ___NAME_TRUE)()),
"fiobj_false() is NOT fiobj_true().");
FIO_ASSERT(FIOBJ_TYPE(FIO_NAME(fiobj, FIOBJ___NAME_NULL)()) == FIOBJ_T_NULL,
"fiobj_null() type should be FIOBJ_T_NULL.");
FIO_ASSERT(FIOBJ_TYPE(FIO_NAME(fiobj, FIOBJ___NAME_TRUE)()) == FIOBJ_T_TRUE,
"fiobj_true() type should be FIOBJ_T_TRUE.");
FIO_ASSERT(FIOBJ_TYPE(FIO_NAME(fiobj, FIOBJ___NAME_FALSE)()) ==
FIOBJ_T_FALSE,
"fiobj_false() type should be FIOBJ_T_FALSE.");
FIO_ASSERT(FIO_NAME_BL(fiobj, eq)(FIO_NAME(fiobj, FIOBJ___NAME_NULL)(),
FIO_NAME(fiobj, FIOBJ___NAME_NULL)()),
"fiobj_null() should be equal to self.");
FIO_ASSERT(FIO_NAME_BL(fiobj, eq)(FIO_NAME(fiobj, FIOBJ___NAME_TRUE)(),
FIO_NAME(fiobj, FIOBJ___NAME_TRUE)()),
"fiobj_true() should be equal to self.");
FIO_ASSERT(FIO_NAME_BL(fiobj, eq)(FIO_NAME(fiobj, FIOBJ___NAME_FALSE)(),
FIO_NAME(fiobj, FIOBJ___NAME_FALSE)()),
"fiobj_false() should be equal to self.");
}
{
fprintf(stderr, "* Testing FIOBJ integers.\n");
uint8_t allocation_flags = 0;
for (uint8_t bit = 0; bit < (sizeof(intptr_t) * 8); ++bit) {
uintptr_t i = (uintptr_t)1 << bit;
o = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), new)((intptr_t)i);
FIO_ASSERT(FIO_NAME2(fiobj, i)(o) == (intptr_t)i,
"Number not reversible at bit %d (%zd != %zd)!",
(int)bit,
(ssize_t)FIO_NAME2(fiobj, i)(o),
(ssize_t)i);
allocation_flags |= (FIOBJ_TYPE_CLASS(o) == FIOBJ_T_NUMBER) ? 1 : 2;
fiobj_free(o);
}
FIO_ASSERT(allocation_flags == 3,
"no bits are allocated / no allocations optimized away (%d)",
(int)allocation_flags);
}
{
fprintf(stderr, "* Testing FIOBJ floats.\n");
uint8_t allocation_flags = 0;
for (uint8_t bit = 0; bit < (sizeof(double) * 8); ++bit) {
union {
double d;
uint64_t i;
} punned;
punned.i = (uint64_t)1 << bit;
o = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), new)(punned.d);
FIO_ASSERT(FIO_NAME2(fiobj, f)(o) == punned.d,
"Float not reversible at bit %d (%lf != %lf)!",
(int)bit,
FIO_NAME2(fiobj, f)(o),
punned.d);
allocation_flags |= (FIOBJ_TYPE_CLASS(o) == FIOBJ_T_FLOAT) ? 1 : 2;
fiobj_free(o);
}
FIO_ASSERT(allocation_flags == 3,
"no bits are allocated / no allocations optimized away (%d)",
(int)allocation_flags);
}
{
fprintf(stderr, "* Testing FIOBJ each2.\n");
FIOBJ a = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), new)();
o = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), new)();
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(o, a);
for (int i = 1; i < 10; ++i) // 1, 2, 3 ... 10
{
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)
(a, FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), new)(i));
if (i % 3 == 0) {
a = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), new)();
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(o, a);
}
}
int expectation[] =
{-1 /* array */, -1, 1, 2, 3, -1, 4, 5, 6, -1, 7, 8, 9, -1};
size_t c =
fiobj_each2(o, FIO_NAME_TEST(stl, fiobj_task), (void *)expectation);
FIO_ASSERT(c == FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), count)(o) +
9 + 1,
"each2 repetition count error");
fiobj_free(o);
FIO_NAME_TEST(stl, fiobj_task)(FIOBJ_INVALID, NULL);
}
{
fprintf(stderr, "* Testing FIOBJ JSON handling.\n");
char json[] =
" "
"\n# comment 1"
"\n// comment 2"
"\n/* comment 3 */"
"{\"true\":true,\"false\":false,\"null\":null,\"array\":[1,2,3,4.2,"
"\"five\"],"
"\"string\":\"hello\\tjson\\bworld!\\r\\n\",\"hash\":{\"true\":true,"
"\"false\":false},\"array2\":[1,2,3,4.2,\"five\",{\"hash\":true},[{"
"\"hash\":{\"true\":true}}]]}";
o = fiobj_json_parse2(json, strlen(json), NULL);
FIO_ASSERT(o, "JSON parsing failed - no data returned.");
FIO_ASSERT(fiobj_json_find2(o, (char *)"array2[6][0].hash.true", 22) ==
fiobj_true(),
"fiobj_json_find2 failed");
FIOBJ j = FIO_NAME2(fiobj, json)(FIOBJ_INVALID, o, 0);
#ifdef DEBUG
fprintf(stderr, "JSON: %s\n", FIO_NAME2(fiobj, cstr)(j).buf);
#endif
FIO_ASSERT(FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(j) ==
strlen(json + 61),
"JSON roundtrip failed (length error).");
FIO_ASSERT(!memcmp(json + 61,
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(j),
strlen(json + 61)),
"JSON roundtrip failed (data error).");
fiobj_free(o);
fiobj_free(j);
o = FIOBJ_INVALID;
}
{
fprintf(stderr, "* Testing FIOBJ array equality test (fiobj_is_eq).\n");
FIOBJ a1 = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), new)();
FIOBJ a2 = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), new)();
FIOBJ n1 = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), new)();
FIOBJ n2 = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), new)();
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(a1, fiobj_null());
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(a2, fiobj_null());
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(n1, fiobj_true());
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(n2, fiobj_true());
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(a1, n1);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(a2, n2);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)
(a1, FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), new_cstr)("test", 4));
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)
(a2, FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), new_cstr)("test", 4));
FIO_ASSERT(FIO_NAME_BL(fiobj, eq)(a1, a2), "equal arrays aren't equal?");
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(n1, fiobj_null());
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(n2, fiobj_false());
FIO_ASSERT(!FIO_NAME_BL(fiobj, eq)(a1, a2), "unequal arrays are equal?");
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), remove)(n1, -1, NULL);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), remove)(n2, -1, NULL);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), remove)(a1, 0, NULL);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), remove)(a2, -1, NULL);
FIO_ASSERT(!FIO_NAME_BL(fiobj, eq)(a1, a2), "unequal arrays are equal?");
fiobj_free(a1);
fiobj_free(a2);
}
{
fprintf(stderr, "* Testing FIOBJ array ownership.\n");
FIOBJ a = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), new)();
for (int i = 1; i <= TEST_REPEAT; ++i) {
FIOBJ tmp = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING),
new_cstr)("number: ", 8);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write_i)(tmp, i);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(a, tmp);
}
FIOBJ shifted = FIOBJ_INVALID;
FIOBJ popped = FIOBJ_INVALID;
FIOBJ removed = FIOBJ_INVALID;
FIOBJ set = FIOBJ_INVALID;
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), shift)(a, &shifted);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), pop)(a, &popped);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), set)
(a, 1, FIO_NAME(fiobj, FIOBJ___NAME_TRUE)(), &set);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), remove)(a, 2, &removed);
fiobj_free(a);
if (1) {
FIO_ASSERT(
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(popped) ==
strlen("number: " FIO_MACRO2STR(TEST_REPEAT)) &&
!memcmp(
"number: " FIO_MACRO2STR(TEST_REPEAT),
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(popped),
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(popped)),
"Object popped from Array lost it's value %s",
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(popped));
FIO_ASSERT(FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(shifted) ==
9 &&
!memcmp("number: 1",
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING),
ptr)(shifted),
9),
"Object shifted from Array lost it's value %s",
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(shifted));
FIO_ASSERT(
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(set) == 9 &&
!memcmp("number: 3",
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(set),
9),
"Object retrieved from Array using fiobj_array_set() lost it's "
"value %s",
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(set));
FIO_ASSERT(
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(removed) == 9 &&
!memcmp(
"number: 4",
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(removed),
9),
"Object retrieved from Array using fiobj_array_set() lost it's "
"value %s",
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(removed));
}
fiobj_free(shifted);
fiobj_free(popped);
fiobj_free(set);
fiobj_free(removed);
}
{
fprintf(stderr, "* Testing FIOBJ array ownership after concat.\n");
FIOBJ a1, a2;
a1 = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), new)();
a2 = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), new)();
for (int i = 0; i < TEST_REPEAT; ++i) {
FIOBJ str = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), new)();
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write_i)(str, i);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(a1, str);
}
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), concat)(a2, a1);
fiobj_free(a1);
for (int i = 0; i < TEST_REPEAT; ++i) {
FIOBJ_STR_TEMP_VAR(tmp);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write_i)(tmp, i);
FIO_ASSERT(
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), get)(a2, i)) ==
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(tmp),
"string length zeroed out - string freed?");
FIO_ASSERT(
!memcmp(
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(tmp),
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), get)(a2, i)),
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(tmp)),
"string data error - string freed?");
FIOBJ_STR_TEMP_DESTROY(tmp);
}
fiobj_free(a2);
}
{
fprintf(stderr, "* Testing FIOBJ hash ownership.\n");
o = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), new)();
for (int i = 1; i <= TEST_REPEAT; ++i) {
FIOBJ tmp = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING),
new_cstr)("number: ", 8);
FIOBJ k = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), new)(i);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write_i)(tmp, i);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), set2)(o, k, tmp);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), set_if_missing2)
(o, k, fiobj_dup(tmp));
fiobj_free(k);
}
FIOBJ set = FIOBJ_INVALID;
FIOBJ removed = FIOBJ_INVALID;
FIOBJ k = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), new)(1);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), remove2)(o, k, &removed);
fiobj_free(k);
k = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), new)(2);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), set)
(o, fiobj2hash(o, k), k, FIO_NAME(fiobj, FIOBJ___NAME_TRUE)(), &set);
fiobj_free(k);
FIO_ASSERT(set, "fiobj_hash_set2 didn't copy information to old pointer?");
FIO_ASSERT(removed,
"fiobj_hash_remove2 didn't copy information to old pointer?");
// fiobj_hash_set(o, uintptr_t hash, FIOBJ key, FIOBJ value, FIOBJ *old)
FIO_ASSERT(
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(removed) ==
strlen("number: 1") &&
!memcmp(
"number: 1",
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(removed),
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(removed)),
"Object removed from Hash lost it's value %s",
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(removed));
FIO_ASSERT(
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(set) ==
strlen("number: 2") &&
!memcmp("number: 2",
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(set),
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(set)),
"Object removed from Hash lost it's value %s",
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(set));
fiobj_free(removed);
fiobj_free(set);
fiobj_free(o);
}
#if FIOBJ_MARK_MEMORY
{
fprintf(stderr, "* Testing FIOBJ for memory leaks.\n");
FIOBJ a = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), new)();
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), reserve)(a, 64);
for (uint8_t bit = 0; bit < (sizeof(intptr_t) * 8); ++bit) {
uintptr_t i = (uintptr_t)1 << bit;
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)
(a, FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_NUMBER), new)((intptr_t)i));
}
FIOBJ h = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), new)();
FIOBJ key = FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), new)();
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)(key, "array", 5);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), set2)(h, key, a);
FIO_ASSERT(FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_HASH), get2)(h, key) == a,
"FIOBJ Hash retrival failed");
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)(a, key);
if (0) {
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)
(a, FIO_NAME(fiobj, FIOBJ___NAME_NULL)());
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)
(a, FIO_NAME(fiobj, FIOBJ___NAME_TRUE)());
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)
(a, FIO_NAME(fiobj, FIOBJ___NAME_FALSE)());
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_ARRAY), push)
(a, FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_FLOAT), new)(0.42));
FIOBJ json = FIO_NAME2(fiobj, json)(FIOBJ_INVALID, h, 0);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write)(json, "\n", 1);
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), reserve)
(json,
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(json)
<< 1); /* prevent memory realloc */
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), write_escape)
(json,
FIO_NAME2(FIO_NAME(fiobj, FIOBJ___NAME_STRING), ptr)(json),
FIO_NAME(FIO_NAME(fiobj, FIOBJ___NAME_STRING), len)(json) - 1);
fprintf(stderr, "%s\n", FIO_NAME2(fiobj, cstr)(json).buf);
fiobj_free(json);
}
fiobj_free(h);
FIO_ASSERT(FIOBJ_MARK_MEMORY_ALLOC_COUNTER ==
FIOBJ_MARK_MEMORY_FREE_COUNTER,
"FIOBJ leak detected (freed %zu/%zu)",
FIOBJ_MARK_MEMORY_FREE_COUNTER,
FIOBJ_MARK_MEMORY_ALLOC_COUNTER);
}
#endif
fprintf(stderr, "* Passed.\n");
}
#endif /* FIO_TEST_CSTL */
/* *****************************************************************************
FIOBJ cleanup
***************************************************************************** */
#endif /* FIOBJ_EXTERN_COMPLETE */
#undef FIOBJ_FUNC
#undef FIOBJ_IFUNC
#undef FIOBJ_EXTERN
#undef FIOBJ_EXTERN_COMPLETE
#undef FIOBJ_EXTERN_OBJ
#undef FIOBJ_EXTERN_OBJ_IMP
#endif /* FIO_FIOBJ */
#undef FIO_FIOBJ
|
janbiedermann/cstl
|
stl_slices/007 threads.h
|
<reponame>janbiedermann/cstl<gh_stars>0
/* *****************************************************************************
Copyright: <NAME>, 2019-2021
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H /* Development inclusion - ignore line */
#define FIO_THREADS /* Development inclusion - ignore line */
#include "000 header.h" /* Development inclusion - ignore line */
#include "003 atomics.h" /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
Simple Portable Threads
***************************************************************************** */
#if defined(FIO_THREADS) && !defined(H___FIO_THREADS___H)
#define H___FIO_THREADS___H
/* *****************************************************************************
Module Settings
At this point, define any MACROs and customaizable settings avsailable to the
developer.
***************************************************************************** */
#if FIO_OS_POSIX
#include <pthread.h>
#include <sched.h>
typedef pthread_t fio_thread_t;
typedef pthread_mutex_t fio_thread_mutex_t;
/** Used this macro for static initialization. */
#define FIO_THREAD_MUTEX_INIT PTHREAD_MUTEX_INITIALIZER
#elif FIO_OS_WIN
#include <synchapi.h>
typedef HANDLE fio_thread_t;
typedef HANDLE fio_thread_mutex_t;
/** Used this macro for static initialization. */
#define FIO_THREAD_MUTEX_INIT ((fio_thread_mutex_t)0)
#else
#error facil.io Simple Portable Threads require a POSIX system or Windows
#endif
#ifdef FIO_THREADS_BYO
#define FIO_IFUNC_T
#else
#define FIO_IFUNC_T FIO_IFUNC
#endif
#ifdef FIO_THREADS_MUTEX_BYO
#define FIO_IFUNC_M
#else
#define FIO_IFUNC_M FIO_IFUNC
#endif
/* *****************************************************************************
Module API
***************************************************************************** */
/** Starts a new thread, returns 0 on success and -1 on failure. */
FIO_IFUNC_T int fio_thread_create(fio_thread_t *t,
void *(*fn)(void *),
void *arg);
/** Waits for the thread to finish. */
FIO_IFUNC_T int fio_thread_join(fio_thread_t t);
/** Detaches the thread, so thread resources are freed automatically. */
FIO_IFUNC_T int fio_thread_detach(fio_thread_t t);
/** Ends the current running thread. */
FIO_IFUNC_T void fio_thread_exit(void);
/* Returns non-zero if both threads refer to the same thread. */
FIO_IFUNC_T int fio_thread_equal(fio_thread_t a, fio_thread_t b);
/** Returns the current thread. */
FIO_IFUNC_T fio_thread_t fio_thread_current(void);
/** Yields thread execution. */
FIO_IFUNC_T void fio_thread_yield(void);
/**
* Initializes a simple Mutex.
*
* Or use the static initialization value: FIO_THREAD_MUTEX_INIT
*/
FIO_IFUNC_M int fio_thread_mutex_init(fio_thread_mutex_t *m);
/** Locks a simple Mutex, returning -1 on error. */
FIO_IFUNC_M int fio_thread_mutex_lock(fio_thread_mutex_t *m);
/** Attempts to lock a simple Mutex, returning zero on success. */
FIO_IFUNC_M int fio_thread_mutex_trylock(fio_thread_mutex_t *m);
/** Unlocks a simple Mutex, returning zero on success or -1 on error. */
FIO_IFUNC_M int fio_thread_mutex_unlock(fio_thread_mutex_t *m);
/** Destroys the simple Mutex (cleanup). */
FIO_IFUNC_M void fio_thread_mutex_destroy(fio_thread_mutex_t *m);
/* *****************************************************************************
POSIX Implementation - inlined static functions
***************************************************************************** */
#if FIO_OS_POSIX
#ifndef FIO_THREADS_BYO
// clang-format off
/** Starts a new thread, returns 0 on success and -1 on failure. */
FIO_IFUNC int fio_thread_create(fio_thread_t *t, void *(*fn)(void *), void *arg) { return pthread_create(t, NULL, fn, arg); }
FIO_IFUNC int fio_thread_join(fio_thread_t t) { return pthread_join(t, NULL); }
/** Detaches the thread, so thread resources are freed automatically. */
FIO_IFUNC int fio_thread_detach(fio_thread_t t) { return pthread_detach(t); }
/** Ends the current running thread. */
FIO_IFUNC void fio_thread_exit(void) { pthread_exit(NULL); }
/* Returns non-zero if both threads refer to the same thread. */
FIO_IFUNC int fio_thread_equal(fio_thread_t a, fio_thread_t b) { return pthread_equal(a, b); }
/** Returns the current thread. */
FIO_IFUNC fio_thread_t fio_thread_current(void) { return pthread_self(); }
/** Yields thread execution. */
FIO_IFUNC void fio_thread_yield(void) { sched_yield(); }
#endif /* FIO_THREADS_BYO */
#ifndef FIO_THREADS_MUTEX_BYO
/** Initializes a simple Mutex. */
FIO_IFUNC int fio_thread_mutex_init(fio_thread_mutex_t *m) { return pthread_mutex_init(m, NULL); }
/** Locks a simple Mutex, returning -1 on error. */
FIO_IFUNC int fio_thread_mutex_lock(fio_thread_mutex_t *m) { return pthread_mutex_lock(m); }
/** Attempts to lock a simple Mutex, returning zero on success. */
FIO_IFUNC int fio_thread_mutex_trylock(fio_thread_mutex_t *m) { return pthread_mutex_trylock(m); }
/** Unlocks a simple Mutex, returning zero on success or -1 on error. */
FIO_IFUNC int fio_thread_mutex_unlock(fio_thread_mutex_t *m) { return pthread_mutex_unlock(m); }
/** Destroys the simple Mutex (cleanup). */
FIO_IFUNC void fio_thread_mutex_destroy(fio_thread_mutex_t *m) { pthread_mutex_destroy(m); *m = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER; }
#endif /* FIO_THREADS_MUTEX_BYO */
// clang-format on
/* *****************************************************************************
Windows Implementation - inlined static functions
***************************************************************************** */
#elif FIO_OS_WIN
#include <process.h>
#ifndef FIO_THREADS_BYO
// clang-format off
/** Starts a new thread, returns 0 on success and -1 on failure. */
FIO_IFUNC int fio_thread_create(fio_thread_t *t, void *(*fn)(void *), void *arg) { *t = (HANDLE)_beginthreadex(NULL, 0, (void(*)(void *))(uintptr_t)fn, 0, arg, NULL); return (!!t) - 1; }
FIO_IFUNC int fio_thread_join(fio_thread_t t) {
int r = 0;
if (WaitForSingleObject(t, INFINITE) == WAIT_FAILED) {
errno = GetLastError();
r = -1;
} else
CloseHandle(t);
return r;
}
/** Detaches the thread, so thread resources are freed automatically. */
FIO_IFUNC int fio_thread_detach(fio_thread_t t) { return CloseHandle(t) - 1; }
/** Ends the current running thread. */
FIO_IFUNC void fio_thread_exit(void) { _endthread(); }
/* Returns non-zero if both threads refer to the same thread. */
FIO_IFUNC int fio_thread_equal(fio_thread_t a, fio_thread_t b) { return GetThreadId(a) == GetThreadId(b); }
/** Returns the current thread. */
FIO_IFUNC fio_thread_t fio_thread_current(void) { return GetCurrentThread(); }
/** Yields thread execution. */
FIO_IFUNC void fio_thread_yield(void) { Sleep(0); }
#endif /* FIO_THREADS_BYO */
#ifndef FIO_THREADS_MUTEX_BYO
SFUNC int fio___thread_mutex_lazy_init(fio_thread_mutex_t *m);
FIO_IFUNC int fio_thread_mutex_init(fio_thread_mutex_t *m) { return ((*m = CreateMutexW(NULL, FALSE, NULL)) != NULL) - 1; }
/** Unlocks a simple Mutex, returning zero on success or -1 on error. */
FIO_IFUNC int fio_thread_mutex_unlock(fio_thread_mutex_t *m) { return ((m && *m) ? ReleaseMutex(*m) : 0) -1; }
/** Destroys the simple Mutex (cleanup). */
FIO_IFUNC void fio_thread_mutex_destroy(fio_thread_mutex_t *m) { CloseHandle(*m); *m = FIO_THREAD_MUTEX_INIT; }
// clang-format on
/** Locks a simple Mutex, returning -1 on error. */
FIO_IFUNC int fio_thread_mutex_lock(fio_thread_mutex_t *m) {
if (!*m && fio___thread_mutex_lazy_init(m))
return -1;
return (WaitForSingleObject((*m), INFINITE) == WAIT_OBJECT_0) - 1;
}
/** Attempts to lock a simple Mutex, returning zero on success. */
FIO_IFUNC int fio_thread_mutex_trylock(fio_thread_mutex_t *m) {
if (!*m && fio___thread_mutex_lazy_init(m))
return -1;
return (WaitForSingleObject((*m), 0) == WAIT_OBJECT_0) - 1;
}
#endif
#endif /* FIO_THREADS_MUTEX_BYO */
/* *****************************************************************************
Module Implementation - possibly externed functions.
***************************************************************************** */
#ifdef FIO_EXTERN_COMPLETE
#if FIO_OS_WIN
#ifndef FIO_THREADS_MUTEX_BYO
/** Initializes a simple Mutex */
SFUNC int fio___thread_mutex_lazy_init(fio_thread_mutex_t *m) {
static fio_lock_i lock = FIO_LOCK_INIT;
/* lazy initialization */
fio_lock(&lock);
if (!*m) { /* retest, as this may chave changed... */
*m = CreateMutexW(NULL, FALSE, NULL);
}
fio_unlock(&lock);
return (!!m) - 1;
}
#endif /* FIO_THREADS_MUTEX_BYO */
#endif /* FIO_OS_WIN */
/* *****************************************************************************
Module Testing
***************************************************************************** */
#ifdef FIO_TEST_CSTL
FIO_SFUNC void FIO_NAME_TEST(stl, threads)(void) {
/*
* TODO? test module here
*/
}
#endif /* FIO_TEST_CSTL */
/* *****************************************************************************
Module Cleanup
***************************************************************************** */
#endif /* FIO_EXTERN_COMPLETE */
#undef FIO_MODULE_PTR
#endif /* FIO_THREADS */
#undef FIO_THREADS
|
thegmarlow/TagTrack-
|
src/pru_adc.c
|
<gh_stars>10-100
/*
* beaglebone_pru_adc - fast analog sensor capture for BeagleBone Black
*
* @author <NAME>
* @email: <EMAIL>
*/
#include <Python.h>
#include <stddef.h>
#include "prussdrv.h"
#include "pruss_intc_mapping.h"
#include "firmware.h"
typedef struct {
PyObject_HEAD
locals_t locals;
int started;
int closed;
} Capture;
static void Capture_dealloc(Capture *self) {
if (!self->closed) {
self->closed = 1;
prussdrv_exit();
}
Py_TYPE(self)->tp_free((PyObject*)self);
}
static int Capture_init(Capture *self, PyObject *args, PyObject *kwds) {
tpruss_intc_initdata pruss_intc_initdata = PRUSS_INTC_INITDATA;
int rc;
self->closed = 1; // consider closed unless successfully init everything
rc = prussdrv_init ();
if (rc != 0) {
PyErr_SetString(PyExc_IOError, "Failed to init PRUSSDRV driver");
return -1;
}
rc = prussdrv_open(0);
if (rc != 0) {
PyErr_SetString(PyExc_IOError, "Failed to open PRU 0");
prussdrv_exit();
return -1;
}
rc = prussdrv_pruintc_init(&pruss_intc_initdata); // Get the interrupt initialized
if (rc != 0) {
PyErr_SetString(PyExc_IOError, "Failed to initialize interrupts");
prussdrv_exit();
return -1;
}
memset(&self->locals, 0, sizeof(self->locals));
self->locals.eyecatcher = EYECATCHER;
self->locals.enc.encoder0 = 0xff; // assigning out-of-range pin number disables encoder logic
self->locals.enc.encoder1 = 0xff; // ditto
self->locals.enc_local[0].threshold = 2000;
self->locals.enc_local[0].speed = INITIAL_ACC_VAL;
self->locals.enc_local[0].acc = INITIAL_ACC_VAL;
self->locals.enc_local[1].threshold = 2000;
self->locals.enc_local[1].speed = INITIAL_ACC_VAL;
self->locals.enc_local[1].acc = INITIAL_ACC_VAL;
rc = prussdrv_pru_write_memory(0, 0, (unsigned int *) &self->locals, sizeof(self->locals));
if (rc < 0) {
PyErr_SetString(PyExc_IOError, "Failed to write local memory block");
prussdrv_exit();
return -1;
}
self->closed = 0;
return 0;
}
static PyObject *Capture_start(Capture *self, PyObject *args, PyObject *kwds) {
int rc;
char *filename = NULL;
if (!PyArg_ParseTuple(args, "s", &filename)) { // Parse the PRU number
return NULL;
}
if (self->started) {
PyErr_SetString(PyExc_IOError, "Already started");
return NULL;
}
rc = prussdrv_exec_program (0, filename); // Load and execute the program
if (rc != 0) {
PyErr_SetString(PyExc_IOError, "Failed to exec firmware");
return NULL;
}
self->started = 1; // true
Py_RETURN_NONE;
}
static PyObject *Capture_wait(Capture *self) {
if (!self->started) {
PyErr_SetString(PyExc_IOError, "Not started");
return NULL;
}
prussdrv_pru_wait_event(0); // Wait for the event. This blocks the thread.
prussdrv_pru_clear_event(0, 0); // Clear the event. FIXME: parameter meaning???
Py_RETURN_NONE;
}
static PyObject *Capture_close(Capture *self, PyObject *args, PyObject *kwds) {
if (!self->closed) {
self->closed = 1; // true
prussdrv_exit();
}
Py_RETURN_NONE;
}
static PyMethodDef Capture_methods[] = {
{"start", (PyCFunction) Capture_start, METH_VARARGS, "Starts capturing ADC data"},
{"wait", (PyCFunction) Capture_wait, METH_NOARGS, "Waits for PRU0 interrupt"},
{"close", (PyCFunction) Capture_close, METH_NOARGS, "closes Capture object"},
{NULL} /* Sentinel */
};
static PyTypeObject CaptureType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"_pru_adc.Capture", /*tp_name*/
sizeof(Capture), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)Capture_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"fast ADC capture object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
Capture_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc) Capture_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
static PyMethodDef module_methods[] = {
{ NULL, NULL, 0, NULL }
};
PyMODINIT_FUNC init_pru_adc() {
PyObject *module = NULL;
CaptureType.tp_new = PyType_GenericNew;
if (PyType_Ready(&CaptureType) < 0)
return;
module = Py_InitModule3("_pru_adc", module_methods, "");
if (module == NULL) {
return;
}
Py_INCREF(&CaptureType);
PyModule_AddObject(module, "Capture", (PyObject *) &CaptureType);
}
|
thegmarlow/TagTrack-
|
src/firmware.h
|
#ifndef _FIRMWARE_H
#define _FIRMWARE_H
typedef unsigned int word;
typedef unsigned short halfword;
typedef unsigned char byte;
typedef struct {
word threshold; // threshold used for detecting wheel encoder ticks
word raw; // raw value of encoder
word min; // min value for current half-tick
word max; // max value for current half-tick
word ticks; // count of encoder ticks
word speed; // width of last encoder tick in "timer" units, aka inverse speed
#define INITIAL_ACC_VAL (0x7fffffff)
word acc; // work area for speed computation
word delay; // activation delay, in timer units.
word uptick_time; // work area for computing uptick delay
word downtick_time; // work area for computing downtick delay
word reserved[6];
} enc_local_t;
/*
* Local memory of the firmware
*/
typedef struct {
#define EYECATCHER (0xbeef1965)
word eyecatcher; // eyecacher (for sanity checks)
word timer; // timer: counts number of ADC reads
word flags; // runtime flags. write 1 to exit capture loop
struct {
word addr; // address of DDR memory bank
word offset; // byte offset into local memory to capture for `scope mode
word length; // byte size of available DDR mem bank (non-zero triggers `scope capture)
} scope;
word reserved0;
word ema_pow; // exponent for EMA averaging: ema += (value - ema/2^ema_pow)
word ain_ema[8]; // captured and EMA-averaged values of all 8 ADC pins
struct {
byte encoder0; // pin number of first wheel encoder ENC0 (0-7)
byte encoder1; // pin number of second wheel encoder ENC1 (0-7)
byte reserved[2];
} enc;
enc_local_t enc_local[2]; // local work memory for each wheel encoder
word cap_delay; // extra delay to control capture frequency
} locals_t;
#endif
|
kotcrab/xdelta-wasm
|
native/xdelta3-wasm.c
|
#include "xdelta3.h"
#include <emscripten.h>
#include <stdio.h>
#include <sys/stat.h>
size_t readSource(void* buffer, size_t offset, size_t size) {
return EM_ASM_INT({ return readSource($0, $1, $2); }, buffer, offset, size);
}
size_t readPatch(void* buffer, size_t offset, size_t size) {
return EM_ASM_INT({ return readPatch($0, $1, $2); }, buffer, offset, size);
}
void writeOutput(void* buffer, size_t size) {
EM_ASM({outputFile($0, $1)}, buffer, size);
}
void reportError(const char* buffer) {
EM_ASM({reportError($0)}, buffer);
}
int processData(int bufferSize) {
if (bufferSize < XD3_ALLOCSIZE) {
bufferSize = XD3_ALLOCSIZE;
}
int ret;
xd3_config config;
xd3_stream stream;
xd3_source source;
xd3_init_config(&config, XD3_ADLER32);
memset(&stream, 0, sizeof(stream));
memset(&source, 0, sizeof(source));
xd3_config_stream(&stream, &config);
config.winsize = bufferSize;
// Init input
source.blksize = bufferSize;
source.curblk = malloc(source.blksize);
source.onblk = readSource((void*)source.curblk, 0, source.blksize);
source.curblkno = 0;
xd3_set_source(&stream, &source);
void* inputBuffer = malloc(bufferSize);
// Main loop
size_t patchPos = 0;
size_t patchRead;
do {
patchRead = readPatch(inputBuffer, patchPos, bufferSize);
patchPos += patchRead;
if (patchRead < bufferSize) {
xd3_set_flags(&stream, XD3_FLUSH | stream.flags);
}
xd3_avail_input(&stream, inputBuffer, patchRead);
process:
ret = xd3_decode_input(&stream);
switch (ret) {
case XD3_INPUT: {
continue;
}
case XD3_OUTPUT: {
writeOutput(stream.next_out, stream.avail_out);
xd3_consume_output(&stream);
goto process;
}
case XD3_GETSRCBLK: {
source.onblk = readSource((void*)source.curblk, source.blksize * source.getblkno, source.blksize);
source.curblkno = source.getblkno;
goto process;
}
case XD3_GOTHEADER: {
goto process;
}
case XD3_WINSTART: {
goto process;
}
case XD3_WINFINISH: {
goto process;
}
default: {
reportError(stream.msg);
fprintf(stderr, "Error: Xdelta message: %s\n", stream.msg);
return ret;
}
}
} while (patchRead == bufferSize);
free(inputBuffer);
free((void*)source.curblk);
xd3_close_stream(&stream);
xd3_free_stream(&stream);
return 0;
};
int main(int argc, char* argv[]) {
printf("In main()\n");
int ret = processData(0x10000);
if (ret) {
fprintf(stderr, "Decode error: %d\n", ret);
return ret;
}
printf("Decode OK!\n");
return 0;
}
|
jmckell/Test-One
|
usb/usbview/display.c
|
/*++
Copyright (c) 1997-2011 Microsoft Corporation
Module Name:
DISPLAY.C
Abstract:
This source file contains the routines which update the edit control
to display information about the selected USB device.
Environment:
user mode
Revision History:
04-25-97 : created
03-28-03 : extensive changes to support new USBVCD
03-28-08 : extensive changes to support new USB Video Class 1.1
--*/
/*****************************************************************************
I N C L U D E S
*****************************************************************************/
#include "uvcview.h"
#include "h264.h"
#include <usb200.h>
#include "vndrlist.h"
#include "langidlist.h"
/*****************************************************************************
D E F I N E S
*****************************************************************************/
#define BUFFERALLOCINCREMENT 0x10000
#define BUFFERMINFREESPACE 0x1000
/*****************************************************************************
T Y P E D E F S
*****************************************************************************/
//
// Hardcoded information about specific EHCI controllers
//
typedef struct _EHCI_CONTROLLER_DATA
{
USHORT VendorID;
USHORT DeviceID;
UCHAR DebugPortNumber;
} EHCI_CONTROLLER_DATA, *PEHCI_CONTROLLER_DATA;
/*****************************************************************************
G L O B A L S P R I V A T E T O T H I S F I L E
*****************************************************************************/
// Workspace for text info which is used to update the edit control
//
CHAR *TextBuffer = NULL;
UINT TextBufferLen = 0;
UINT TextBufferPos = 0;
STRINGLIST slPowerState [] =
{
{WdmUsbPowerNotMapped, "S? (unmapped) ", ""},
{WdmUsbPowerSystemUnspecified, "S? (unspecified)", ""},
{WdmUsbPowerSystemWorking, "S0 (working) ", ""},
{WdmUsbPowerSystemSleeping1, "S1 (sleep) ", ""},
{WdmUsbPowerSystemSleeping2, "S2 (sleep) ", ""},
{WdmUsbPowerSystemSleeping3, "S3 (sleep) ", ""},
{WdmUsbPowerSystemHibernate, "S4 (Hibernate) ", ""},
{WdmUsbPowerSystemShutdown, "S5 (shutdown) ", ""},
{WdmUsbPowerDeviceUnspecified, "D? (unspecified)", ""},
{WdmUsbPowerDeviceD0, "D0 ", ""},
{WdmUsbPowerDeviceD1, "D1 ", ""},
{WdmUsbPowerDeviceD2, "D2 ", ""},
{WdmUsbPowerDeviceD3, "D3 ", ""},
};
STRINGLIST slControllerFlavor[] =
{
{ USB_HcGeneric, "USB_HcGeneric", "" },
{ OHCI_Generic, "OHCI_Generic", "" },
{ OHCI_Hydra, "OHCI_Hydra", "" },
{ OHCI_NEC, "OHCI_NEC", "" },
{ UHCI_Generic, "UHCI_Generic", "" },
{ UHCI_Piix4, "UHCI_Piix4", "" },
{ UHCI_Piix3, "UHCI_Piix3", "" },
{ UHCI_Ich2, "UHCI_Ich2", "" },
{ UHCI_Reserved204, "UHCI_Reserved204", "" },
{ UHCI_Ich1, "UHCI_Ich1", "" },
{ UHCI_Ich3m, "UHCI_Ich3m", "" },
{ UHCI_Ich4, "UHCI_Ich4", "" },
{ UHCI_Ich5, "UHCI_Ich5", "" },
{ UHCI_Ich6, "UHCI_Ich6", "" },
{ UHCI_Intel, "UHCI_Intel", "" },
{ UHCI_VIA, "UHCI_VIA", "" },
{ UHCI_VIA_x01, "UHCI_VIA_x01", "" },
{ UHCI_VIA_x02, "UHCI_VIA_x02", "" },
{ UHCI_VIA_x03, "UHCI_VIA_x03", "" },
{ UHCI_VIA_x04, "UHCI_VIA_x04", "" },
{ UHCI_VIA_x0E_FIFO, "UHCI_VIA_x0E_FIFO", "" },
{ EHCI_Generic, "EHCI_Generic", "" },
{ EHCI_NEC, "EHCI_NEC", "" },
{ EHCI_Lucent, "EHCI_Lucent", "" },
{ EHCI_NVIDIA_Tegra2, "EHCI_NVIDIA_Tegra2", "" },
{ EHCI_NVIDIA_Tegra3, "EHCI_NVIDIA_Tegra3", "" },
{ EHCI_Intel_Medfield, "EHCI_Intel_Medfield", "" }
};
//
// For supporting pre Win8 versions of Windows, a hardcoded list is maintained for determining
// debug port numbers. As usbport.inf is augmented with new host controllers, this list should
// be updated.
//
// The following entries do not have a debug port:
// PCI\VEN_8086&DEV_0806 - "Intel(R) SM35 Express Chipset USB2 Enhanced Host Controller MPH - 0806"
// PCI\VEN_8086&DEV_0811 - "Intel(R) SM35 Express Chipset USB2 Enhanced Host Controller SPM - 0811"
//
EHCI_CONTROLLER_DATA EhciControllerData[] =
{
{0x8086, 0x24CD, 1}, // ICH4 - Intel(R) 82801DB/DBM USB 2.0 Enhanced Host Controller - 24CD
{0x8086, 0x24DD, 1}, // ICH5 - Intel(R) 82801EB USB2 Enhanced Host Controller - 24DD
{0x8086, 0x25AD, 1}, // ICH5 - Intel(R) 6300ESB USB2 Enhanced Host Controller - 25AD
{0x8086, 0x265C, 1}, // ICH6 - Intel(R) 82801FB/FBM USB2 Enhanced Host Controller - 265C
{0x8086, 0x268C, 1}, // Intel(R) 631xESB/6321ESB/3100 Chipset USB2 Enhanced Host Controller - 268C
{0x8086, 0x27CC, 1}, // ICH7 - Intel(R) 82801G (ICH7 Family) USB2 Enhanced Host Controller - 27CC
{0x8086, 0x2836, 1}, // ICH8 - Intel(R) ICH8 Family USB2 Enhanced Host Controller - 2836
{0x8086, 0x283A, 1}, // ICH8 - Intel(R) ICH8 Family USB2 Enhanced Host Controller - 283A
{0x8086, 0x293A, 1}, // ICH9 - Intel(R) ICH9 Family USB2 Enhanced Host Controller - 293A
{0x8086, 0x293C, 1}, // ICH9 - Intel(R) ICH9 Family USB2 Enhanced Host Controller - 293C
{0x8086, 0x3A3A, 1}, // ICH10 - Intel(R) ICH10 Family USB Enhanced Host Controller - 3A3A
{0x8086, 0x3A3C, 1}, // ICH10 - Intel(R) ICH10 Family USB Enhanced Host Controller - 3A3C
{0x8086, 0x3A6A, 1}, // ICH10 - Intel(R) ICH10 Family USB Enhanced Host Controller - 3A6A
{0x8086, 0x3A6C, 1}, // ICH10 - Intel(R) ICH10 Family USB Enhanced Host Controller - 3A6C
{0x8086, 0x3B34, 2}, // 5 series - Intel(R) 5 Series/3400 Series Chipset Family USB Enhanced Host Controller - 3B34
{0x8086, 0x3B36, 2}, // 5 series - Intel(R) 5 Series/3400 Series Chipset Family USB Universal Host Controller - 3B36
{0x8086, 0x1C26, 2}, // 6 series - Intel(R) 6 Series/C200 Series Chipset Family USB Enhanced Host Controller - 1C26
{0x8086, 0x1C2D, 2}, // 6 series - Intel(R) 6 Series/C200 Series Chipset Family USB Enhanced Host Controller - 1C2D
{0x8086, 0x1D26, 2}, // Intel(R) C600/X79 series chipset USB2 Enhanced Host Controller #1 - 1D26
{0x8086, 0x1D2D, 2}, // Intel(R) C600/X79 series chipset USB2 Enhanced Host Controller #2 - 1D2D
{0x8086, 0x268C, 1}, // Intel(R) 631xESB/6321ESB/3100 Chipset USB2 Enhanced Host Controller - 268C
{0x10DE, 0x00D8, 1},
{0,0,0},
};
/*****************************************************************************
L O C A L F U N C T I O N P R O T O T Y P E S
*****************************************************************************/
VOID
DisplayPortConnectorProperties (
_In_ PUSB_PORT_CONNECTOR_PROPERTIES PortConnectorProps,
_In_opt_ PUSB_NODE_CONNECTION_INFORMATION_EX_V2 ConnectionInfoV2
);
void
DisplayDevicePowerState (
_In_ PDEVICE_INFO_NODE DeviceInfoNode
);
VOID
DisplayHubInfo (
PUSB_HUB_INFORMATION HubInfo,
BOOL DisplayDescriptor
);
VOID
DisplayHubInfoEx (
PUSB_HUB_INFORMATION_EX HubInfoEx
);
VOID
DisplayHubCapabilityEx (
PUSB_HUB_CAPABILITIES_EX HubCapabilityEx
);
VOID
DisplayPowerState(
PUSB_POWER_INFO pUPI
);
VOID
DisplayConnectionInfo (
_In_ PUSB_NODE_CONNECTION_INFORMATION_EX ConnectInfo,
_In_ PUSBDEVICEINFO info,
_In_ PSTRING_DESCRIPTOR_NODE StringDescs,
_In_opt_ PUSB_NODE_CONNECTION_INFORMATION_EX_V2 ConnectionInfoV2
);
VOID
DisplayPipeInfo (
ULONG NumPipes,
USB_PIPE_INFO *PipeInfo
);
VOID
DisplayConfigDesc (
PUSBDEVICEINFO info,
PUSB_CONFIGURATION_DESCRIPTOR ConfigDesc,
PSTRING_DESCRIPTOR_NODE StringDescs
);
VOID
DisplayBosDescriptor (
PUSBDEVICEINFO info,
PUSB_BOS_DESCRIPTOR BosDesc,
PSTRING_DESCRIPTOR_NODE StringDescs
);
VOID
DisplayBillboardCapabilityDescriptor (
PUSBDEVICEINFO info,
PUSB_DEVICE_CAPABILITY_BILLBOARD_DESCRIPTOR billboardCapDesc,
PSTRING_DESCRIPTOR_NODE StringDescs
);
VOID
DisplayDeviceQualifierDescriptor (
PUSB_DEVICE_QUALIFIER_DESCRIPTOR DevQualDesc
);
VOID
DisplayConfigurationDescriptor (
PUSBDEVICEINFO info,
PUSB_CONFIGURATION_DESCRIPTOR ConfigDesc,
PSTRING_DESCRIPTOR_NODE StringDescs
);
VOID
DisplayInterfaceDescriptor (
PUSB_INTERFACE_DESCRIPTOR InterfaceDesc,
PSTRING_DESCRIPTOR_NODE StringDescs,
DEVICE_POWER_STATE LatestDevicePowerState
);
VOID
DisplayEndpointDescriptor (
_In_ PUSB_ENDPOINT_DESCRIPTOR
EndpointDesc,
_In_opt_ PUSB_SUPERSPEED_ENDPOINT_COMPANION_DESCRIPTOR
EpCompDesc,
_In_opt_ PUSB_SUPERSPEEDPLUS_ISOCH_ENDPOINT_COMPANION_DESCRIPTOR
SspIsochCompDesc,
_In_ UCHAR InterfaceClass,
_In_ BOOLEAN EpCompDescAvail
);
VOID
DisplaySuperSpeedPlusIsochEndpointCompanionDescriptor(
_In_ PUSB_SUPERSPEEDPLUS_ISOCH_ENDPOINT_COMPANION_DESCRIPTOR SspIsochEpCompDesc
);
VOID
DisplayEndointCompanionDescriptor (
_In_ PUSB_SUPERSPEED_ENDPOINT_COMPANION_DESCRIPTOR EpCompDesc,
_In_opt_ PUSB_SUPERSPEEDPLUS_ISOCH_ENDPOINT_COMPANION_DESCRIPTOR
SspIsochEpCompDesc,
_In_ UCHAR DescType
);
VOID
DisplayHidDescriptor (
PUSB_HID_DESCRIPTOR HidDesc
);
VOID
DisplayOTGDescriptor (
PUSB_OTG_DESCRIPTOR OTGDesc
);
void
InitializePerDeviceSettings (
PUSBDEVICEINFO info
);
UINT
IsUVCDevice (
PUSBDEVICEINFO info
);
VOID
DisplayIADDescriptor (
PUSB_IAD_DESCRIPTOR IADDesc,
PSTRING_DESCRIPTOR_NODE StringDescs,
int nInterfaces,
DEVICE_POWER_STATE LatestDevicePowerState
);
VOID
DisplayUSEnglishStringDescriptor (
UCHAR Index,
PSTRING_DESCRIPTOR_NODE USStringDescs,
DEVICE_POWER_STATE LatestDevicePowerState
);
VOID
DisplayUnknownDescriptor (
PUSB_COMMON_DESCRIPTOR CommonDesc
);
VOID
DisplayRemainingUnknownDescriptor(
PUCHAR DescriptorData,
ULONG Start,
ULONG Stop
);
PCHAR
GetVendorString (
USHORT idVendor
);
PCHAR
GetLangIDString (
USHORT idLang
);
UINT
GetConfigurationSize (
PUSBDEVICEINFO info
);
UINT
GetInterfaceCount (
PUSBDEVICEINFO info
);
/*****************************************************************************
L O C A L F U N C T I O N S
*****************************************************************************/
/*****************************************************************************
NextDescriptor()
*****************************************************************************/
//__forceinline
PUSB_COMMON_DESCRIPTOR
NextDescriptor(
_In_ PUSB_COMMON_DESCRIPTOR Descriptor
)
{
if (Descriptor->bLength == 0)
{
return NULL;
}
return (PUSB_COMMON_DESCRIPTOR)((PUCHAR)Descriptor + Descriptor->bLength);
}
/*****************************************************************************
GetNextDescriptor()
*****************************************************************************/
PUSB_COMMON_DESCRIPTOR
GetNextDescriptor(
_In_reads_bytes_(TotalLength)
PUSB_COMMON_DESCRIPTOR FirstDescriptor,
_In_
ULONG TotalLength,
_In_
PUSB_COMMON_DESCRIPTOR StartDescriptor,
_In_ long
DescriptorType
)
{
PUSB_COMMON_DESCRIPTOR currentDescriptor = NULL;
PUSB_COMMON_DESCRIPTOR endDescriptor = NULL;
endDescriptor = (PUSB_COMMON_DESCRIPTOR)((PUCHAR)FirstDescriptor + TotalLength);
if (StartDescriptor >= endDescriptor ||
NextDescriptor(StartDescriptor)>= endDescriptor)
{
return NULL;
}
if (DescriptorType == -1) // -1 means any type
{
return NextDescriptor(StartDescriptor);
}
currentDescriptor = StartDescriptor;
while (((currentDescriptor = NextDescriptor(currentDescriptor)) < endDescriptor)
&& currentDescriptor != NULL)
{
if (currentDescriptor->bDescriptorType == (UCHAR)DescriptorType)
{
return currentDescriptor;
}
}
return NULL;
}
/*****************************************************************************
CreateTextBuffer()
*****************************************************************************/
BOOL
CreateTextBuffer (
)
{
// Allocate the buffer
//
TextBuffer = ALLOC(BUFFERALLOCINCREMENT);
if (TextBuffer == NULL)
{
OOPS();
return FALSE;
}
TextBufferLen = BUFFERALLOCINCREMENT;
// Reset the buffer position and terminate the buffer
//
memset(TextBuffer, 0, BUFFERALLOCINCREMENT);
TextBufferPos = 0;
return TRUE;
}
/*****************************************************************************
DestroyTextBuffer()
*****************************************************************************/
VOID
DestroyTextBuffer (
)
{
if (TextBuffer != NULL)
{
FREE(TextBuffer);
TextBuffer = NULL;
}
}
/*****************************************************************************
ResetTextBuffer()
*****************************************************************************/
BOOL
ResetTextBuffer (
)
{
// Fail if the text buffer has not been allocated
//
if (TextBuffer == NULL)
{
OOPS();
return FALSE;
}
// Reset the buffer position and terminate the buffer
//
*TextBuffer = 0;
TextBufferPos = 0;
return TRUE;
}
/*****************************************************************************
GetTextBufferPos()
*****************************************************************************/
UINT
GetTextBufferPos (
)
{
return TextBufferPos;
}
/*****************************************************************************
AppendTextBuffer()
*****************************************************************************/
VOID __cdecl
AppendTextBuffer (
LPCTSTR lpFormat,
...
)
{
va_list arglist;
HRESULT hr = S_OK;
int nPos = TextBufferPos;
char LocalTextBuffer[512];
va_start(arglist, lpFormat);
// Make sure we have a healthy amount of space free in the buffer,
// reallocating the buffer if necessary.
//
if (TextBufferLen - TextBufferPos < BUFFERMINFREESPACE)
{
CHAR *TextBufferTmp;
UINT uNewTextBufferLen = 0;
hr = UIntAdd(TextBufferLen, BUFFERALLOCINCREMENT, &uNewTextBufferLen);
if (hr != S_OK)
{
// we've exceeded DWORD length of (2^32)-1 for buffer
OOPS();
return;
}
TextBufferTmp = REALLOC(TextBuffer, uNewTextBufferLen);
if (TextBufferTmp != NULL)
{
TextBuffer = TextBufferTmp;
TextBufferLen += BUFFERALLOCINCREMENT; // update TextBufferLen to reflect the new, bigger size of the text buffer
}
else
{
// If GlobalReAlloc fails, the original memory is not freed,
// and the original handle and pointer are still valid.
//
OOPS();
return;
}
}
// Add the text to the end of the buffer
//
hr = StringCchVPrintf(LocalTextBuffer, sizeof(LocalTextBuffer), lpFormat, arglist);
if (SUCCEEDED(hr))
{
size_t cbMax = 512;
size_t pcb = 0;
// Ensure TextBuffer is zero terminated
// The text buffer size is specified by TextBufferLen.
// the text buffer size will be bigger than BUFFERALLOCINCREMENT if the buffer has been reallocated more than
// once (which would happen if it had to be made bigger to hold more text)
hr = StringCbLength((LPCTSTR) TextBuffer,
TextBufferLen, // the maximum number of bytes allowed in TextBuffer.
&pcb);
if (FAILED(hr)) // buffer is not null-terminated, go ahead and do that
{
TextBuffer[TextBufferLen-1] = 0;
}
hr = StringCbLength((LPCTSTR) LocalTextBuffer, cbMax, &pcb);
if (SUCCEEDED(hr))
{
StringCbCatN(TextBuffer, TextBufferLen, LocalTextBuffer, pcb);
// Increment the text position by the number of charcters we just added to it.
TextBufferPos += (UINT) pcb;
}
// If DebugLog flag set, send output to the debugger
//
if (gLogDebug)
{
OutputDebugString(TextBuffer + nPos); // print the string just added to the text buffer
}
}
}
//*****************************************************************************
//
// GetTextBuffer
//
// Returns the display text buffer
//
//*****************************************************************************
PCHAR GetTextBuffer(void)
{
return (TextBuffer);
}
//*****************************************************************************
//
// GetEhciDebugPort
//
// Returns debug port value if present for EHCI controller. 0 if its not present
//
//*****************************************************************************
ULONG GetEhciDebugPort(ULONG vendorId, ULONG deviceId)
{
int i = 0;
ULONG debugPort = 0;
for (i = 0; EhciControllerData[i].VendorID != 0; i++)
{
if (vendorId == EhciControllerData[i].VendorID &&
deviceId == EhciControllerData[i].DeviceID)
{
debugPort = EhciControllerData[i].DebugPortNumber;
break;
}
}
return debugPort;
}
//*****************************************************************************
//
// UpdateTreeItemDeviceInfo
//
// hTreeItem - Handle of selected TreeView item for which information should
// be added to the TextBuffer global
//
// The functions returns error status if AppendTextBuffer() used in Display*() functions
// fails. The display text would be missing or truncated in such cases.
//*****************************************************************************
HRESULT
UpdateTreeItemDeviceInfo(
HWND hTreeWnd,
HTREEITEM hTreeItem
)
{
TV_ITEM tvi;
PVOID info;
ULONG i;
HRESULT hr = S_OK;
PCHAR tviName = NULL;
SetLastError(0);
#ifndef H264_SUPPORT
UNREFERENCED_PARAMETER(bShowVersion)
#endif
#ifdef H264_SUPPORT
ResetErrorCounts();
#endif
tviName = ALLOC(256);
if(NULL == tviName)
{
OOPS();
hr = E_OUTOFMEMORY;
return hr;
}
//
// Get the name of the TreeView item, along with the a pointer to the
// info we stored about the item in the item's lParam.
//
tvi.mask = TVIF_HANDLE | TVIF_TEXT | TVIF_PARAM;
tvi.hItem = hTreeItem;
tvi.pszText = (LPSTR) tviName;
tvi.cchTextMax = 256;
TreeView_GetItem(hTreeWnd,
&tvi);
info = (PVOID)tvi.lParam;
AppendTextBuffer(tviName);
AppendTextBuffer("\r\n");
//
// If we didn't store any info for the item, just display the item's
// name, else display the info we stored for the item.
//
if (NULL != info)
{
PUSB_NODE_INFORMATION HubInfo = NULL;
PCHAR HubName = NULL;
PUSB_NODE_CONNECTION_INFORMATION_EX ConnectionInfo = NULL;
PUSB_DESCRIPTOR_REQUEST ConfigDesc = NULL;
PSTRING_DESCRIPTOR_NODE StringDescs = NULL;
PUSB_HUB_INFORMATION_EX HubInfoEx = NULL;
PUSB_HUB_CAPABILITIES_EX HubCapabilityEx = NULL;
PUSB_PORT_CONNECTOR_PROPERTIES PortConnectorProps = NULL;
PUSB_NODE_CONNECTION_INFORMATION_EX_V2 ConnectionInfoV2 = NULL;
PUSB_DESCRIPTOR_REQUEST BosDesc = NULL;
PDEVICE_INFO_NODE DeviceInfoNode = NULL;
// The TextBuffer has the TreeView name; add 2 lines for display
AppendTextBuffer("\r\n\r\n");
switch (*(PUSBDEVICEINFOTYPE)info)
{
case HostControllerInfo:
{
HTREEITEM rootHubItem = NULL;
BOOL dbgPortFound = FALSE;
AppendTextBuffer("DriverKey: %s\r\n",
((PUSBHOSTCONTROLLERINFO)info)->DriverKey);
AppendTextBuffer("VendorID: %04X\r\n",
((PUSBHOSTCONTROLLERINFO)info)->VendorID);
AppendTextBuffer("DeviceID: %04X\r\n",
((PUSBHOSTCONTROLLERINFO)info)->DeviceID);
AppendTextBuffer("SubSysID: %08X\r\n",
((PUSBHOSTCONTROLLERINFO)info)->SubSysID);
AppendTextBuffer("Revision: %02X\r\n",
((PUSBHOSTCONTROLLERINFO)info)->Revision);
//
// Search for the debug port number. If running on Win8 or later,
// the USB_PORT_CONNECTOR_PROPERTIES structure will contain the
// port number. If that fails, the list of known host controllers
// with debug ports will be searched.
//
AppendTextBuffer("\r\nDebug Port Number: ");
rootHubItem = TreeView_GetChild(hTreeWnd, hTreeItem);
if (rootHubItem != NULL)
{
HTREEITEM portItem = NULL;
PVOID portInfo;
portItem = TreeView_GetChild(hTreeWnd, rootHubItem);
while (portItem != NULL)
{
tvi.mask = TVIF_PARAM;
tvi.hItem = portItem;
tvi.pszText = NULL;
tvi.cchTextMax = 0;
TreeView_GetItem(hTreeWnd, &tvi);
portInfo = (PVOID)tvi.lParam;
//
// Note that an empty port is a port without a device attached
// is still a DeviceInfo instance.
//
if ((*(PUSBDEVICEINFOTYPE)portInfo) == DeviceInfo)
{
ConnectionInfo = ((PUSBDEVICEINFO)portInfo)->ConnectionInfo;
PortConnectorProps = ((PUSBDEVICEINFO)portInfo)->PortConnectorProps;
}
else if ((*(PUSBDEVICEINFOTYPE)portInfo) == ExternalHubInfo)
{
ConnectionInfo = ((PUSBEXTERNALHUBINFO)portInfo)->ConnectionInfo;
PortConnectorProps = ((PUSBEXTERNALHUBINFO)portInfo)->PortConnectorProps;
}
if (ConnectionInfo != NULL &&
PortConnectorProps != NULL &&
PortConnectorProps->UsbPortProperties.PortIsDebugCapable)
{
dbgPortFound = TRUE;
AppendTextBuffer("%d\r\n", ((PUSBDEVICEINFO)portInfo)->ConnectionInfo->ConnectionIndex);
break;
}
portItem = TreeView_GetNextSibling(hTreeWnd, portItem);
}
//
// Resetting ConnectionInfo and PortConnectorProps to NULL so that they won't be erroneously
// be displayed below.
//
ConnectionInfo = NULL;
PortConnectorProps = NULL;
}
if (dbgPortFound == FALSE)
{
for (i = 0; EhciControllerData[i].VendorID; i++)
{
if (((PUSBHOSTCONTROLLERINFO)info)->VendorID ==
EhciControllerData[i].VendorID &&
((PUSBHOSTCONTROLLERINFO)info)->DeviceID ==
EhciControllerData[i].DeviceID)
{
dbgPortFound = TRUE;
AppendTextBuffer("%d\r\n", EhciControllerData[i].DebugPortNumber);
break;
}
}
}
if (dbgPortFound == FALSE)
{
AppendTextBuffer("None\r\n");
}
//
// Display bus/device/function to help with setting debug
// settings.
//
if (((PUSBHOSTCONTROLLERINFO)info)->BusDeviceFunctionValid)
{
AppendTextBuffer("Bus.Device.Function (in decimal): %d.%d.%d\r\n",
((PUSBHOSTCONTROLLERINFO)info)->BusNumber,
((PUSBHOSTCONTROLLERINFO)info)->BusDevice,
((PUSBHOSTCONTROLLERINFO)info)->BusFunction);
}
// Display the USB Host Controller Power State Info
{
PUSB_POWER_INFO pUPI = (PUSB_POWER_INFO) &((PUSBHOSTCONTROLLERINFO)info)->USBPowerInfo[0];
int nIndex = 0;
int nPowerState = WdmUsbPowerSystemWorking;
AppendTextBuffer("\r\nHost Controller Power State Mappings\r\n");
AppendTextBuffer("System State\t\tHost Controller\t\tRoot Hub\tUSB wakeup\tPowered\r\n");
for ( ; nPowerState < WdmUsbPowerSystemShutdown; nIndex++, nPowerState++, pUPI++)
{
DisplayPowerState(pUPI);
}
AppendTextBuffer("%s\t%s\r\n",
"Last Sleep State",
GetPowerStateString(pUPI->LastSystemSleepState)
);
}
break;
}
case RootHubInfo:
HubInfo = ((PUSBROOTHUBINFO)info)->HubInfo;
HubName = ((PUSBROOTHUBINFO)info)->HubName;
HubCapabilityEx = ((PUSBROOTHUBINFO)info)->HubCapabilityEx;
AppendTextBuffer("Root Hub: %s\r\n",
HubName);
break;
case ExternalHubInfo:
HubInfo = ((PUSBEXTERNALHUBINFO)info)->HubInfo;
HubName = ((PUSBEXTERNALHUBINFO)info)->HubName;
HubInfoEx = ((PUSBEXTERNALHUBINFO)info)->HubInfoEx;
HubCapabilityEx = ((PUSBEXTERNALHUBINFO)info)->HubCapabilityEx;
ConnectionInfo = ((PUSBEXTERNALHUBINFO)info)->ConnectionInfo;
ConnectionInfoV2 = ((PUSBEXTERNALHUBINFO)info)->ConnectionInfoV2;
PortConnectorProps = ((PUSBEXTERNALHUBINFO)info)->PortConnectorProps;
ConfigDesc = ((PUSBEXTERNALHUBINFO)info)->ConfigDesc;
StringDescs = ((PUSBEXTERNALHUBINFO)info)->StringDescs;
BosDesc = ((PUSBEXTERNALHUBINFO)info)->BosDesc;
DeviceInfoNode = ((PUSBEXTERNALHUBINFO)info)->DeviceInfoNode;
AppendTextBuffer("External Hub: %s\r\n",
HubName);
break;
case DeviceInfo:
ConnectionInfo = ((PUSBDEVICEINFO)info)->ConnectionInfo;
ConnectionInfoV2 = ((PUSBDEVICEINFO)info)->ConnectionInfoV2;
PortConnectorProps = ((PUSBDEVICEINFO)info)->PortConnectorProps;
ConfigDesc = ((PUSBDEVICEINFO)info)->ConfigDesc;
StringDescs = ((PUSBDEVICEINFO)info)->StringDescs;
BosDesc = ((PUSBDEVICEINFO)info)->BosDesc;
DeviceInfoNode = ((PUSBDEVICEINFO)info)->DeviceInfoNode;
break;
}
if (PortConnectorProps)
{
DisplayPortConnectorProperties(PortConnectorProps, ConnectionInfoV2);
}
if (DeviceInfoNode)
{
DisplayDevicePowerState(DeviceInfoNode);
}
if (HubInfo)
{
DisplayHubInfo(&HubInfo->u.HubInformation,
(HubInfoEx == NULL));
}
if (HubInfoEx)
{
DisplayHubInfoEx(HubInfoEx);
}
if(HubCapabilityEx)
{
DisplayHubCapabilityEx(HubCapabilityEx);
}
if (ConnectionInfo)
{
DisplayConnectionInfo(ConnectionInfo,
(PUSBDEVICEINFO)info,
StringDescs,
ConnectionInfoV2);
}
if (ConfigDesc)
{
DisplayConfigDesc((PUSBDEVICEINFO)info,
(PUSB_CONFIGURATION_DESCRIPTOR)(ConfigDesc + 1),
StringDescs);
}
if (BosDesc)
{
DisplayBosDescriptor((PUSBDEVICEINFO) info,
(PUSB_BOS_DESCRIPTOR) (BosDesc + 1),
StringDescs);
}
}
if(tviName != NULL)
{
FREE(tviName);
}
// AppendTextBuffer() which is used in Display*() functions uses GlobalRealloc() which can fail if realloc fails.
// Obtain last error code from GetLastError() and propagate the error to caller.
hr = HRESULT_FROM_WIN32(GetLastError());
return hr;
}
//*****************************************************************************
//
// UpdateEditControl()
//
// hTreeItem - Handle of selected TreeView item for which information should
// be displayed in the edit control.
//
//*****************************************************************************
VOID
UpdateEditControl (
HWND hEditWnd,
HWND hTreeWnd,
HTREEITEM hTreeItem
)
{
HRESULT hr = S_OK;
// Start with an empty text buffer.
//
if (!ResetTextBuffer())
{
return;
}
// Get the item information in global TextBuffer
hr = UpdateTreeItemDeviceInfo(hTreeWnd, hTreeItem);
if(FAILED(hr))
{
OOPS();
}
// All done formatting text buffer with info, now update the edit
// control with the contents of the text buffer
//
SetWindowText(hEditWnd, TextBuffer);
}
/*****************************************************************************
DisplayPortConnectorProperties()
PortConnectorProps - Info about the port connector properties.
*****************************************************************************/
void
DisplayPortConnectorProperties (
_In_ PUSB_PORT_CONNECTOR_PROPERTIES PortConnectorProps,
_In_opt_ PUSB_NODE_CONNECTION_INFORMATION_EX_V2 ConnectionInfoV2
)
{
AppendTextBuffer("Is Port User Connectable: %s\r\n",
PortConnectorProps->UsbPortProperties.PortIsUserConnectable
? "yes" : "no");
AppendTextBuffer("Is Port Debug Capable: %s\r\n",
PortConnectorProps->UsbPortProperties.PortIsDebugCapable
? "yes" : "no");
AppendTextBuffer("Companion Port Number: %d\r\n",
PortConnectorProps->CompanionPortNumber);
AppendTextBuffer("Companion Hub Symbolic Link Name: %ws\r\n",
PortConnectorProps->CompanionHubSymbolicLinkName);
if (ConnectionInfoV2 != NULL)
{
AppendTextBuffer("Protocols Supported:\r\n");
AppendTextBuffer(" USB 1.1: %s\r\n",
ConnectionInfoV2->SupportedUsbProtocols.Usb110
? "yes" : "no");
AppendTextBuffer(" USB 2.0: %s\r\n",
ConnectionInfoV2->SupportedUsbProtocols.Usb200
? "yes" : "no");
AppendTextBuffer(" USB 3.0: %s\r\n",
ConnectionInfoV2->SupportedUsbProtocols.Usb300
? "yes" : "no");
}
AppendTextBuffer("\r\n");
}
/*****************************************************************************
DisplayDevicePowerState()
DeviceInfoNode - Structure containing info used to acquire device state
*****************************************************************************/
void
DisplayDevicePowerState (
_In_ PDEVICE_INFO_NODE DeviceInfoNode
)
{
DEVICE_POWER_STATE powerState;
powerState = AcquireDevicePowerState(DeviceInfoNode);
AppendTextBuffer("Device Power State: ");
if (powerState >= PowerDeviceD0 && powerState <= PowerDeviceD3)
{
AppendTextBuffer("PowerDeviceD%d\r\n", powerState-1);
}
else
{
AppendTextBuffer("Invalid Device Power State Value %d\r\n", powerState);
}
AppendTextBuffer("\r\n");
}
/*****************************************************************************
DisplayHubDescriptorBase()
HubDescriptor - hub descriptor, could also be PUSB_30_HUB_DESCRIPTOR which has
these field in common at the beginning of the data structure:
- UCHAR bLength;
- UCHAR bDescriptorType;
- UCHAR bNumberOfPorts;
- USHORT wHubCharacteristics;
- UCHAR bPowerOnToPowerGood;
- UCHAR bHubControlCurrent;
*****************************************************************************/
VOID
DisplayHubDescriptorBase(
PUSB_HUB_DESCRIPTOR HubDescriptor
)
{
USHORT wHubChar = 0;
AppendTextBuffer("Number of Ports: %d\r\n",
HubDescriptor->bNumberOfPorts);
wHubChar = HubDescriptor->wHubCharacteristics;
switch (wHubChar & 0x0003)
{
case 0x0000:
AppendTextBuffer("Power switching: Ganged\r\n");
break;
case 0x0001:
AppendTextBuffer("Power switching: Individual\r\n");
break;
case 0x0002:
case 0x0003:
AppendTextBuffer("Power switching: None\r\n");
break;
}
switch (wHubChar & 0x0004)
{
case 0x0000:
AppendTextBuffer("Compound device: No\r\n");
break;
case 0x0004:
AppendTextBuffer("Compound device: Yes\r\n");
break;
}
switch (wHubChar & 0x0018)
{
case 0x0000:
AppendTextBuffer("Over-current Protection: Global\r\n");
break;
case 0x0008:
AppendTextBuffer("Over-current Protection: Individual\r\n");
break;
case 0x0010:
case 0x0018:
AppendTextBuffer("No Over-current Protection (Bus Power Only)\r\n");
break;
}
}
/*****************************************************************************
DisplayHubInfo()
HubInfo - Info about the hub.
*****************************************************************************/
VOID
DisplayHubInfo (
PUSB_HUB_INFORMATION HubInfo,
BOOL DisplayDescriptor
)
{
AppendTextBuffer("Hub Power: %s\r\n",
HubInfo->HubIsBusPowered ?
"Bus Power" : "Self Power");
if (DisplayDescriptor == TRUE)
{
DisplayHubDescriptorBase(&HubInfo->HubDescriptor);
}
}
/*****************************************************************************
DisplayHubInfoEx()
HubInfo - Extended info about the hub.
*****************************************************************************/
VOID
DisplayHubInfoEx (
PUSB_HUB_INFORMATION_EX HubInfoEx
)
{
AppendTextBuffer("Hub type: ");
switch (HubInfoEx->HubType) {
case UsbRootHub:
AppendTextBuffer("USB Root Hub\r\n");
break;
case Usb20Hub:
AppendTextBuffer("USB 2.0 Hub\r\n");
DisplayHubDescriptorBase((PUSB_HUB_DESCRIPTOR)&HubInfoEx->u.UsbHubDescriptor);
break;
case Usb30Hub:
AppendTextBuffer("USB 3.0 Hub\r\n");
//
// Note that the DisplayHubDescriptorBase will display the fields of either
// the legacy hub descriptor and the USB 3.0 descriptor which have the same
// offset
//
DisplayHubDescriptorBase((PUSB_HUB_DESCRIPTOR)&HubInfoEx->u.UsbHubDescriptor);
AppendTextBuffer("Packet Header Decode Latency: 0x%x\r\n", HubInfoEx->u.Usb30HubDescriptor.bHubHdrDecLat);
AppendTextBuffer("Delay: 0x%x ns\r\n", HubInfoEx->u.Usb30HubDescriptor.wHubDelay);
break;
default:
AppendTextBuffer("ERROR: Unknown hub type %d\r\n", HubInfoEx->HubType);
break;
}
AppendTextBuffer("\r\n");
}
/*****************************************************************************
DisplayHubCapabilityEx()
HubCapabilityInfo - Hub capability information
*****************************************************************************/
VOID
DisplayHubCapabilityEx (
PUSB_HUB_CAPABILITIES_EX HubCapabilityEx
)
{
if(HubCapabilityEx != NULL)
{
AppendTextBuffer("High speed capable: %s\r\n",
HubCapabilityEx->CapabilityFlags.HubIsHighSpeedCapable
? "Yes" : "No");
AppendTextBuffer("High speed: %s\r\n",
HubCapabilityEx->CapabilityFlags.HubIsHighSpeed
? "Yes" : "No");
AppendTextBuffer("Multiple transaction translations capable: %s\r\n",
HubCapabilityEx->CapabilityFlags.HubIsMultiTtCapable
? "Yes" : "No");
AppendTextBuffer("Performs multiple transaction translations simultaneously: %s\r\n",
HubCapabilityEx->CapabilityFlags.HubIsMultiTt
? "Yes" : "No");
AppendTextBuffer("Hub wakes when device is connected: %s\r\n",
HubCapabilityEx->CapabilityFlags.HubIsArmedWakeOnConnect
? "Yes" : "No");
AppendTextBuffer("Hub is bus powered: %s\r\n",
HubCapabilityEx->CapabilityFlags.HubIsBusPowered
? "Yes" : "No");
AppendTextBuffer("Hub is root: %s\r\n",
HubCapabilityEx->CapabilityFlags.HubIsRoot
? "Yes" : "No");
}
}
/*****************************************************************************
DisplayConnectionInfo()
ConnectInfo - Info about the connection.
PUSB_NODE_CONNECTION_INFORMATION_EX ConnectInfo,
PSTRING_DESCRIPTOR_NODE StringDescs
DisplayConnectionInfo(info->ConnectionInfo,
info->StringDescs);
DisplayConnectionInfo (
PUSB_NODE_CONNECTION_INFORMATION_EX ConnectInfo,
PSTRING_DESCRIPTOR_NODE StringDescs
)
*****************************************************************************/
VOID
DisplayConnectionInfo (
_In_ PUSB_NODE_CONNECTION_INFORMATION_EX ConnectInfo,
_In_ PUSBDEVICEINFO info,
_In_ PSTRING_DESCRIPTOR_NODE StringDescs,
_In_opt_ PUSB_NODE_CONNECTION_INFORMATION_EX_V2 ConnectionInfoV2
)
{
//@@DisplayConnectionInfo - Device Information
PCHAR VendorString = NULL;
UINT tog = 1;
UINT uIADcount = 0;
// No device connected
if (ConnectInfo->ConnectionStatus == NoDeviceConnected)
{
AppendTextBuffer("ConnectionStatus: NoDeviceConnected\r\n");
return;
}
// This is the entry point to the device display functions.
// First, save this device's PUSBDEVICEINFO address
// In a future version of this test, we will keep track of the the
// descriptor that we're parsing (# of bytes from beginning of info->configuration descriptor)
// Then we can linked descriptors by reading forward through the remaining descriptors
// while still keeping our place in this main DisplayConnectionInfo() and called
// functions.
//
// We also initialize some global flags in uvcview.h that are used to
// verify items in MJPEG, Uncompressed and Vendor Frame descriptors
//
InitializePerDeviceSettings(info);
if(gDoAnnotation)
{
AppendTextBuffer(" ---===>Device Information<===---\r\n");
if (ConnectInfo->DeviceDescriptor.iProduct)
{
DisplayUSEnglishStringDescriptor(ConnectInfo->DeviceDescriptor.iProduct,
StringDescs,
info->DeviceInfoNode != NULL? info->DeviceInfoNode->LatestDevicePowerState: PowerDeviceUnspecified);
}
AppendTextBuffer("\r\nConnectionStatus: %s\r\n",
ConnectionStatuses[ConnectInfo->ConnectionStatus]);
AppendTextBuffer("Current Config Value: 0x%02X",
ConnectInfo->CurrentConfigurationValue);
}
switch (ConnectInfo->Speed){
case UsbLowSpeed:
if(gDoAnnotation)
{
AppendTextBuffer(" -> Device Bus Speed: Low\r\n");
}
else
{
AppendTextBuffer("\r\n");
}
gDeviceSpeed = UsbLowSpeed;
break;
case UsbFullSpeed:
if(gDoAnnotation)
{
AppendTextBuffer(" -> Device Bus Speed: Full");
if (ConnectionInfoV2 != NULL)
{
if (ConnectionInfoV2->Flags.DeviceIsSuperSpeedPlusCapableOrHigher)
{
AppendTextBuffer(" (is SuperSpeedPlus or higher capable)\r\n");
}
else if (ConnectionInfoV2->Flags.DeviceIsSuperSpeedCapableOrHigher)
{
AppendTextBuffer(" (is SuperSpeed or higher capable)\r\n");
}
else
{
AppendTextBuffer(" (is not SuperSpeed or higher capable)\r\n");
}
}
else
{
AppendTextBuffer("\r\n");
}
}
else
{
AppendTextBuffer("\r\n");
}
gDeviceSpeed = UsbFullSpeed;
break;
case UsbHighSpeed:
if(gDoAnnotation)
{
AppendTextBuffer(" -> Device Bus Speed: High");
if (ConnectionInfoV2 != NULL)
{
if (ConnectionInfoV2->Flags.DeviceIsSuperSpeedPlusCapableOrHigher)
{
AppendTextBuffer(" (is SuperSpeedPlus or higher capable)\r\n");
}
else if (ConnectionInfoV2->Flags.DeviceIsSuperSpeedCapableOrHigher)
{
AppendTextBuffer(" (is SuperSpeed or higher capable)\r\n");
}
else
{
AppendTextBuffer(" (is not SuperSpeed or higher capable)\r\n");
}
}
else
{
AppendTextBuffer("\r\n");
}
}
else
{
AppendTextBuffer("\r\n");
}
gDeviceSpeed = UsbHighSpeed;
break;
case UsbSuperSpeed:
if(gDoAnnotation)
{
AppendTextBuffer(" -> Device Bus Speed: Super%s\r\n",
ConnectionInfoV2->Flags.DeviceIsOperatingAtSuperSpeedPlusOrHigher
? "SpeedPlus"
: "Speed");
}
else
{
AppendTextBuffer("\r\n");
}
gDeviceSpeed = UsbSuperSpeed;
break;
default:
if(gDoAnnotation){AppendTextBuffer(" -> Device Bus Speed: Unknown\r\n");}
else {AppendTextBuffer("\r\n");}
}
if(gDoAnnotation){
AppendTextBuffer("Device Address: 0x%02X\r\n",
ConnectInfo->DeviceAddress);
AppendTextBuffer("Open Pipes: %2d\r\n",
ConnectInfo->NumberOfOpenPipes);
}
// No open pipes means the USB stack has not loaded the device
if (ConnectInfo->NumberOfOpenPipes == 0)
{
AppendTextBuffer("*!*ERROR: No open pipes!\r\n");
}
AppendTextBuffer("\r\n ===>Device Descriptor<===\r\n");
//@@DisplayConnectionInfo - Device Descriptor
if (ConnectInfo->DeviceDescriptor.bLength != 18)
{
//@@TestCase A1.1
//@@ERROR
//@@Descriptor Field - bLength
//@@The declared length in the device descriptor is not equal to the
//@@ required length in the USB Device Specification
AppendTextBuffer("*!*ERROR: bLength of %d incorrect, should be %d\r\n",
ConnectInfo->DeviceDescriptor.bLength,
18);
OOPS();
}
AppendTextBuffer("bLength: 0x%02X\r\n",
ConnectInfo->DeviceDescriptor.bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
ConnectInfo->DeviceDescriptor.bDescriptorType);
//@@TestCase A1.2
//@@Not implemented - Priority 1
//@@Descriptor Field - bcdUSB
//@@Need to check that any UVC device is set to 0x0200 or later.
AppendTextBuffer("bcdUSB: 0x%04X\r\n",
ConnectInfo->DeviceDescriptor.bcdUSB);
AppendTextBuffer("bDeviceClass: 0x%02X",
ConnectInfo->DeviceDescriptor.bDeviceClass);
// Quit on these device failures
if ((ConnectInfo->ConnectionStatus == DeviceFailedEnumeration) ||
(ConnectInfo->ConnectionStatus == DeviceGeneralFailure))
{
AppendTextBuffer("\r\n*!*ERROR: Device enumeration failure\r\n");
return;
}
// Is this an IAD device?
uIADcount = IsIADDevice((PUSBDEVICEINFO) info);
if (uIADcount)
{
// this device configuration has 1 or more IAD descriptors
if (ConnectInfo->DeviceDescriptor.bDeviceClass == USB_MISCELLANEOUS_DEVICE)
{
tog = 0;
if (gDoAnnotation)
{
AppendTextBuffer(" -> This is a Multi-interface Function Code Device\r\n");
}
else
{
AppendTextBuffer("\r\n");
}
} else {
AppendTextBuffer("\r\n*!*ERROR: device class should be Multi-interface Function 0x%02X\r\n"\
" When IAD descriptor is used\r\n",
USB_MISCELLANEOUS_DEVICE);
}
// Is this a UVC device?
g_chUVCversion = IsUVCDevice((PUSBDEVICEINFO) info);
}
else
{
// this is not an IAD device
switch (ConnectInfo->DeviceDescriptor.bDeviceClass)
{
case USB_INTERFACE_CLASS_DEVICE:
if(gDoAnnotation)
{AppendTextBuffer(" -> This is an Interface Class Defined Device\r\n");}
else {AppendTextBuffer("\r\n");}
break;
case USB_COMMUNICATION_DEVICE:
tog = 0;
if(gDoAnnotation)
{AppendTextBuffer(" -> This is a Communication Device\r\n");}
else {AppendTextBuffer("\r\n");}
break;
case USB_HUB_DEVICE:
tog = 0;
if(gDoAnnotation)
{AppendTextBuffer(" -> This is a HUB Device\r\n");}
else {AppendTextBuffer("\r\n");}
break;
case USB_DIAGNOSTIC_DEVICE:
tog = 0;
if(gDoAnnotation)
{AppendTextBuffer(" -> This is a Diagnostic Device\r\n");}
else {AppendTextBuffer("\r\n");}
break;
case USB_WIRELESS_CONTROLLER_DEVICE:
tog = 0;
if(gDoAnnotation)
{AppendTextBuffer(" -> This is a Wireless Controller(Bluetooth) Device\r\n");}
else {AppendTextBuffer("\r\n");}
break;
case USB_VENDOR_SPECIFIC_DEVICE:
tog = 0;
if(gDoAnnotation)
{AppendTextBuffer(" -> This is a Vendor Specific Device\r\n");}
else {AppendTextBuffer("\r\n");}
break;
case USB_DEVICE_CLASS_BILLBOARD:
tog = 0;
if (gDoAnnotation)
{
AppendTextBuffer(" -> This is a billboard class device\r\n");
}
else { AppendTextBuffer("\r\n"); }
break;
case USB_MISCELLANEOUS_DEVICE:
tog = 0;
//@@TestCase A1.3
//@@ERROR
//@@Descriptor Field - bDeviceClass
//@@Multi-interface Function code used for non-IAD device
AppendTextBuffer("\r\n*!*ERROR: Multi-interface Function code %d used for "\
"device with no IAD descriptors\r\n",
ConnectInfo->DeviceDescriptor.bDeviceClass);
break;
default:
//@@TestCase A1.4
//@@ERROR
//@@Descriptor Field - bDeviceClass
//@@An unknown device class has been defined
AppendTextBuffer("\r\n*!*ERROR: unknown bDeviceClass %d\r\n",
ConnectInfo->DeviceDescriptor.bDeviceClass);
OOPS();
break;
}
}
AppendTextBuffer("bDeviceSubClass: 0x%02X",
ConnectInfo->DeviceDescriptor.bDeviceSubClass);
// check the subclass
if (uIADcount)
{
// this device configuration has 1 or more IAD descriptors
if (ConnectInfo->DeviceDescriptor.bDeviceSubClass == USB_COMMON_SUB_CLASS)
{
if (gDoAnnotation)
{
AppendTextBuffer(" -> This is the Common Class Sub Class\r\n");
} else
{
AppendTextBuffer("\r\n");
}
}
else
{
//@@TestCase A1.5
//@@ERROR
//@@Descriptor Field - bDeviceSubClass
//@@An invalid device sub class used for Multi-interface Function (IAD) device
AppendTextBuffer("\r\n*!*ERROR: device SubClass should be USB Common Sub Class %d\r\n"\
" When IAD descriptor is used\r\n",
USB_COMMON_SUB_CLASS);
OOPS();
}
}
else
{
// Not an IAD device, so all subclass values are invalid
if(ConnectInfo->DeviceDescriptor.bDeviceSubClass > 0x00 &&
ConnectInfo->DeviceDescriptor.bDeviceSubClass < 0xFF)
{
//@@TestCase A1.6
//@@ERROR
//@@Descriptor Field - bDeviceSubClass
//@@An invalid device sub class has been defined
AppendTextBuffer("\r\n*!*ERROR: bDeviceSubClass of %d is invalid\r\n",
ConnectInfo->DeviceDescriptor.bDeviceSubClass);
OOPS();
} else
{
AppendTextBuffer("\r\n");
}
}
AppendTextBuffer("bDeviceProtocol: 0x%02X",
ConnectInfo->DeviceDescriptor.bDeviceProtocol);
// check the protocol
if (uIADcount)
{
// this device configuration has 1 or more IAD descriptors
if (ConnectInfo->DeviceDescriptor.bDeviceProtocol == USB_IAD_PROTOCOL)
{
if (gDoAnnotation)
{
AppendTextBuffer(" -> This is the Interface Association Descriptor protocol\r\n");
}
else
{
AppendTextBuffer("\r\n");
}
}
else
{
//@@TestCase A1.7
//@@ERROR
//@@Descriptor Field - bDeviceSubClass
//@@An invalid device sub class used for Multi-interface Function (IAD) device
AppendTextBuffer("\r\n*!*ERROR: device Protocol should be USB IAD Protocol %d\r\n"\
" When IAD descriptor is used\r\n",
USB_IAD_PROTOCOL);
OOPS();
}
}
else
{
// Not an IAD device, so all subclass values are invalid
if(ConnectInfo->DeviceDescriptor.bDeviceProtocol > 0x00 &&
ConnectInfo->DeviceDescriptor.bDeviceProtocol < 0xFF && tog==1)
{
//@@TestCase A1.8
//@@ERROR
//@@Descriptor Field - bDeviceProtocol
//@@An invalid device protocol has been defined
AppendTextBuffer("\r\n*!*ERROR: bDeviceProtocol of %d is invalid\r\n",
ConnectInfo->DeviceDescriptor.bDeviceProtocol);
OOPS();
}
else
{
AppendTextBuffer("\r\n");
}
}
AppendTextBuffer("bMaxPacketSize0: 0x%02X",
ConnectInfo->DeviceDescriptor.bMaxPacketSize0);
if(gDoAnnotation)
{
AppendTextBuffer(" = (%d) Bytes\r\n",
ConnectInfo->DeviceDescriptor.bMaxPacketSize0);
}
else
{
AppendTextBuffer("\r\n");
}
switch (gDeviceSpeed){
case UsbLowSpeed:
if(ConnectInfo->DeviceDescriptor.bMaxPacketSize0 != 8)
{
//@@TestCase A1.9
//@@ERROR
//@@Descriptor Field - bMaxPacketSize0
//@@An invalid bMaxPacketSize0 has been defined for a low speed device
AppendTextBuffer("*!*ERROR: Low Speed Devices require bMaxPacketSize0 = 8\r\n");
OOPS();
}
break;
case UsbFullSpeed:
if(!(ConnectInfo->DeviceDescriptor.bMaxPacketSize0 == 8 ||
ConnectInfo->DeviceDescriptor.bMaxPacketSize0 == 16 ||
ConnectInfo->DeviceDescriptor.bMaxPacketSize0 == 32 ||
ConnectInfo->DeviceDescriptor.bMaxPacketSize0 == 64))
{
//@@TestCase A1.10
//@@ERROR
//@@Descriptor Field - bMaxPacketSize0
//@@An invalid bMaxPacketSize0 has been defined for a full speed device
AppendTextBuffer("*!*ERROR: Full Speed Devices require bMaxPacketSize0 = 8, 16, 32, or 64\r\n");
OOPS();
}
break;
case UsbHighSpeed:
if(ConnectInfo->DeviceDescriptor.bMaxPacketSize0 != 64)
{
//@@TestCase A1.11
//@@ERROR
//@@Descriptor Field - bMaxPacketSize0
//@@An invalid bMaxPacketSize0 has been defined for a high speed device
AppendTextBuffer("*!*ERROR: High Speed Devices require bMaxPacketSize0 = 64\r\n");
OOPS();
}
break;
case UsbSuperSpeed:
if(ConnectInfo->DeviceDescriptor.bMaxPacketSize0 != 9)
{
AppendTextBuffer("*!*ERROR: SuperSpeed Devices require bMaxPacketSize0 = 9 (512)\r\n");
OOPS();
}
break;
}
AppendTextBuffer("idVendor: 0x%04X",
ConnectInfo->DeviceDescriptor.idVendor);
if (gDoAnnotation)
{
VendorString = GetVendorString(ConnectInfo->DeviceDescriptor.idVendor);
if (VendorString != NULL)
{
AppendTextBuffer(" = %s\r\n",
VendorString);
}
}
else {AppendTextBuffer("\r\n");}
AppendTextBuffer("idProduct: 0x%04X\r\n",
ConnectInfo->DeviceDescriptor.idProduct);
AppendTextBuffer("bcdDevice: 0x%04X\r\n",
ConnectInfo->DeviceDescriptor.bcdDevice);
AppendTextBuffer("iManufacturer: 0x%02X\r\n",
ConnectInfo->DeviceDescriptor.iManufacturer);
if (ConnectInfo->DeviceDescriptor.iManufacturer && gDoAnnotation)
{
DisplayStringDescriptor(ConnectInfo->DeviceDescriptor.iManufacturer,
StringDescs,
info->DeviceInfoNode != NULL? info->DeviceInfoNode->LatestDevicePowerState: PowerDeviceUnspecified);
}
AppendTextBuffer("iProduct: 0x%02X\r\n",
ConnectInfo->DeviceDescriptor.iProduct);
if (ConnectInfo->DeviceDescriptor.iProduct && gDoAnnotation)
{
DisplayStringDescriptor(ConnectInfo->DeviceDescriptor.iProduct,
StringDescs,
info->DeviceInfoNode != NULL? info->DeviceInfoNode->LatestDevicePowerState: PowerDeviceUnspecified);
}
AppendTextBuffer("iSerialNumber: 0x%02X\r\n",
ConnectInfo->DeviceDescriptor.iSerialNumber);
if (ConnectInfo->DeviceDescriptor.iSerialNumber && gDoAnnotation)
{
DisplayStringDescriptor(ConnectInfo->DeviceDescriptor.iSerialNumber,
StringDescs,
info->DeviceInfoNode != NULL? info->DeviceInfoNode->LatestDevicePowerState: PowerDeviceUnspecified);
}
AppendTextBuffer("bNumConfigurations: 0x%02X\r\n",
ConnectInfo->DeviceDescriptor.bNumConfigurations);
if(ConnectInfo->DeviceDescriptor.bNumConfigurations != 1)
{
//@@TestCase A1.12
//@@CAUTION
//@@Descriptor Field - bNumConfigurations
//@@Most host controllers do not handle more than one configuration
AppendTextBuffer("*!*CAUTION: Most host controllers will only work with "\
"one configuration per speed\r\n");
OOPS();
}
if (ConnectInfo->NumberOfOpenPipes)
{
AppendTextBuffer("\r\n ---===>Open Pipes<===---\r\n");
DisplayPipeInfo(ConnectInfo->NumberOfOpenPipes,
ConnectInfo->PipeList);
}
return;
}
/*****************************************************************************
DisplayPipeInfo()
NumPipes - Number of pipe for we info should be displayed.
PipeInfo - Info about the pipes.
*****************************************************************************/
VOID
DisplayPipeInfo (
ULONG NumPipes,
USB_PIPE_INFO *PipeInfo
)
{
ULONG i = 0;
for (i = 0; i < NumPipes; i++)
{
DisplayEndpointDescriptor(&PipeInfo[i].EndpointDescriptor, NULL, NULL, 0, FALSE);
}
}
/*****************************************************************************
GetControllerFlavorString()
Returns the text for given controller flavor
*****************************************************************************/
PCHAR GetControllerFlavorString(USB_CONTROLLER_FLAVOR flavor)
{
return(GetStringFromList(slControllerFlavor,
sizeof(slControllerFlavor) / sizeof(STRINGLIST),
flavor,
STR_UNKNOWN_CONTROLLER_FLAVOR));
}
/*****************************************************************************
GetPowerStateString()
Returns the descriptive string for given power state
*****************************************************************************/
PCHAR GetPowerStateString(WDMUSB_POWER_STATE powerState)
{
return(GetStringFromList(slPowerState,
sizeof(slPowerState) / sizeof(STRINGLIST),
powerState,
STR_INVALID_POWER_STATE));
}
/*****************************************************************************
DisplayPowerState()
PUSB_POWER_INFO pUPI - USBUSER.H USB_Power_Info data
*****************************************************************************/
VOID
DisplayPowerState(
PUSB_POWER_INFO pUPI
)
{
AppendTextBuffer("%s\t%s\t%s%s\t\t%s\r\n",
GetPowerStateString(pUPI->SystemState),
GetPowerStateString(pUPI->HcDevicePowerState),
GetPowerStateString(pUPI->RhDevicePowerState),
pUPI->CanWakeup ? "Yes" : "",
pUPI->IsPowered ? "Yes" : ""
);
return;
}
/*****************************************************************************
ValidateDescAddress()
Given a descriptor address and the Configuration Descriptor length
(saved in DisplayConfigDesc(), and initialized for each new device)
return TRUE if the descriptor is within the Configuration length
else FALSE
*****************************************************************************/
BOOL
ValidateDescAddress (
PUSB_COMMON_DESCRIPTOR commonDesc
)
{
if ((PUCHAR) commonDesc + commonDesc->bLength <= g_descEnd)
{
return TRUE;
}
return FALSE;
}
/*****************************************************************************
DisplayConfigDesc()
ConfigDesc - The Configuration Descriptor, and associated Interface and
Endpoint Descriptors
*****************************************************************************/
VOID
DisplayConfigDesc (
PUSBDEVICEINFO info,
PUSB_CONFIGURATION_DESCRIPTOR ConfigDesc,
PSTRING_DESCRIPTOR_NODE StringDescs
)
{
PUSB_COMMON_DESCRIPTOR commonDesc = NULL;
UCHAR bInterfaceClass = 0;
UCHAR bInterfaceSubClass = 0;
UCHAR bInterfaceProtocol = 0;
BOOL displayUnknown = FALSE;
BOOL isSS;
isSS = info->ConnectionInfoV2
&& info->ConnectionInfoV2->Flags.DeviceIsOperatingAtSuperSpeedOrHigher
? TRUE
: FALSE;
commonDesc = (PUSB_COMMON_DESCRIPTOR)ConfigDesc;
// initialize global Configuration start/end address and string desc address
g_pConfigDesc = ConfigDesc;
g_pStringDescs = StringDescs;
g_descEnd = (PUCHAR)ConfigDesc + ConfigDesc->wTotalLength;
AppendTextBuffer("\r\n ---===>Full Configuration Descriptor<===---\r\n");
do
{
displayUnknown = FALSE;
switch (commonDesc->bDescriptorType)
{
case USB_DEVICE_QUALIFIER_DESCRIPTOR_TYPE:
//@@DisplayConfigDesc - Device Qualifier Descriptor
if (commonDesc->bLength != sizeof(USB_DEVICE_QUALIFIER_DESCRIPTOR))
{
//@@TestCase A2.1
//@@ERROR
//@@Descriptor Field - bLength
//@@The declared length in the device descriptor is not equal to the
//@@ required length in the USB Device Specification
AppendTextBuffer("*!*ERROR: bLength of %d for Device Qualifier incorrect, "\
"should be %d\r\n",
commonDesc->bLength,
sizeof(USB_DEVICE_QUALIFIER_DESCRIPTOR));
OOPS();
displayUnknown = TRUE;
break;
}
DisplayDeviceQualifierDescriptor((PUSB_DEVICE_QUALIFIER_DESCRIPTOR)commonDesc);
break;
case USB_OTHER_SPEED_CONFIGURATION_DESCRIPTOR_TYPE:
//@@DisplayConfigDesc - Other Speed Configuration Descriptor
if (commonDesc->bLength != sizeof(USB_CONFIGURATION_DESCRIPTOR))
{
//@@TestCase A2.2
//@@ERROR
//@@Descriptor Field - bLength
//@@The declared length in the device descriptor is not equal to the
//@@ required length in the USB Device Specification
AppendTextBuffer("*!*ERROR: bLength of %d for Other Speed Configuration "\
"incorrect, should be %d\r\n",
commonDesc->bLength,
sizeof(USB_CONFIGURATION_DESCRIPTOR));
OOPS();
displayUnknown = TRUE;
}
DisplayConfigurationDescriptor(
(PUSBDEVICEINFO) info,
(PUSB_CONFIGURATION_DESCRIPTOR)commonDesc,
StringDescs);
break;
case USB_CONFIGURATION_DESCRIPTOR_TYPE:
//@@DisplayConfigDesc - Configuration Descriptor
if (commonDesc->bLength != sizeof(USB_CONFIGURATION_DESCRIPTOR))
{
//@@TestCase A2.3
//@@ERROR
//@@Descriptor Field - bLength
//@@The declared length in the device descriptor is not equal to the
//@@required length in the USB Device Specification
AppendTextBuffer("*!*ERROR: bLength of %d for Configuration incorrect, "\
"should be %d\r\n",
commonDesc->bLength,
sizeof(USB_CONFIGURATION_DESCRIPTOR));
OOPS();
displayUnknown = TRUE;
break;
}
DisplayConfigurationDescriptor((PUSBDEVICEINFO)info,
(PUSB_CONFIGURATION_DESCRIPTOR)commonDesc,
StringDescs);
break;
case USB_INTERFACE_DESCRIPTOR_TYPE:
//@@DisplayConfigDesc - Interface Descriptor
if ((commonDesc->bLength != sizeof(USB_INTERFACE_DESCRIPTOR)) &&
(commonDesc->bLength != sizeof(USB_INTERFACE_DESCRIPTOR2)))
{
//@@TestCase A2.4
//@@ERROR
//@@Descriptor Field - bLength
//@@The declared length in the device descriptor is not equal to the
//@@required length in the USB Device Specification
AppendTextBuffer("*!*ERROR: bLength of %d for Interface incorrect, "\
"should be %d or %d\r\n",
commonDesc->bLength,
sizeof(USB_INTERFACE_DESCRIPTOR),
sizeof(USB_INTERFACE_DESCRIPTOR2));
OOPS();
displayUnknown = TRUE;
break;
}
bInterfaceClass = ((PUSB_INTERFACE_DESCRIPTOR)commonDesc)->bInterfaceClass;
bInterfaceSubClass = ((PUSB_INTERFACE_DESCRIPTOR)commonDesc)->bInterfaceSubClass;
bInterfaceProtocol = ((PUSB_INTERFACE_DESCRIPTOR)commonDesc)->bInterfaceProtocol;
DisplayInterfaceDescriptor(
(PUSB_INTERFACE_DESCRIPTOR)commonDesc,
StringDescs,
info->DeviceInfoNode != NULL? info->DeviceInfoNode->LatestDevicePowerState: PowerDeviceUnspecified);
break;
case USB_ENDPOINT_DESCRIPTOR_TYPE:
{
PUSB_SUPERSPEED_ENDPOINT_COMPANION_DESCRIPTOR epCompDesc = NULL;
PUSB_SUPERSPEEDPLUS_ISOCH_ENDPOINT_COMPANION_DESCRIPTOR
sspIsochCompDesc = NULL;
//@@DisplayConfigDesc - Endpoint Descriptor
if ((commonDesc->bLength != sizeof(USB_ENDPOINT_DESCRIPTOR)) &&
(commonDesc->bLength != sizeof(USB_ENDPOINT_DESCRIPTOR2)))
{
//@@TestCase A2.5
//@@ERROR
//@@Descriptor Field - bLength
//@@The declared length in the device descriptor is not equal to
//@@ the required length in the USB Device Specification
AppendTextBuffer("*!*ERROR: bLength of %d for Endpoint incorrect, "\
"should be %d or %d\r\n",
commonDesc->bLength,
sizeof(USB_ENDPOINT_DESCRIPTOR),
sizeof(USB_ENDPOINT_DESCRIPTOR2));
OOPS();
displayUnknown = TRUE;
break;
}
if (isSS)
{
epCompDesc = (PUSB_SUPERSPEED_ENDPOINT_COMPANION_DESCRIPTOR)
GetNextDescriptor((PUSB_COMMON_DESCRIPTOR)ConfigDesc, ConfigDesc->wTotalLength, commonDesc, -1);
}
if (epCompDesc != NULL &&
epCompDesc->bmAttributes.Isochronous.SspCompanion == 1)
{
sspIsochCompDesc = (PUSB_SUPERSPEEDPLUS_ISOCH_ENDPOINT_COMPANION_DESCRIPTOR)
GetNextDescriptor((PUSB_COMMON_DESCRIPTOR)ConfigDesc,
ConfigDesc->wTotalLength,
(PUSB_COMMON_DESCRIPTOR)epCompDesc,
-1);
}
DisplayEndpointDescriptor((PUSB_ENDPOINT_DESCRIPTOR)commonDesc,
epCompDesc,
sspIsochCompDesc,
bInterfaceClass,
TRUE);
if (sspIsochCompDesc != NULL)
{
commonDesc = (PUSB_COMMON_DESCRIPTOR)sspIsochCompDesc;
}
else if (epCompDesc != NULL)
{
commonDesc = (PUSB_COMMON_DESCRIPTOR)epCompDesc;
}
}
break;
case USB_HID_DESCRIPTOR_TYPE:
if (commonDesc->bLength < sizeof(USB_HID_DESCRIPTOR))
{
OOPS();
displayUnknown = TRUE;
break;
}
DisplayHidDescriptor((PUSB_HID_DESCRIPTOR)commonDesc);
break;
case USB_OTG_DESCRIPTOR_TYPE:
if (commonDesc->bLength < sizeof(USB_OTG_DESCRIPTOR))
{
OOPS();
displayUnknown = TRUE;
break;
}
DisplayOTGDescriptor((PUSB_OTG_DESCRIPTOR)commonDesc);
break;
case USB_IAD_DESCRIPTOR_TYPE:
if (commonDesc->bLength < sizeof(USB_IAD_DESCRIPTOR))
{
OOPS();
displayUnknown = TRUE;
break;
}
DisplayIADDescriptor((PUSB_IAD_DESCRIPTOR)commonDesc, StringDescs,
ConfigDesc->bNumInterfaces,
info->DeviceInfoNode != NULL? info->DeviceInfoNode->LatestDevicePowerState: PowerDeviceUnspecified);
break;
default:
//@@DisplayConfigDesc - Interface Class Device
// TODO: BUG: bInterfaceClass is initialized before this code
switch (bInterfaceClass)
{
case USB_DEVICE_CLASS_AUDIO:
displayUnknown = ! DisplayAudioDescriptor(
(PUSB_AUDIO_COMMON_DESCRIPTOR)commonDesc,
bInterfaceSubClass);
break;
case USB_DEVICE_CLASS_VIDEO:
displayUnknown = ! DisplayVideoDescriptor(
(PVIDEO_SPECIFIC)commonDesc,
bInterfaceSubClass,
StringDescs,
info->DeviceInfoNode != NULL? info->DeviceInfoNode->LatestDevicePowerState: PowerDeviceUnspecified);
break;
case USB_DEVICE_CLASS_RESERVED:
//@@TestCase A2.6
//@@ERROR
//@@Descriptor Field - bInterfaceClass
//@@An unknown interface class has been defined
AppendTextBuffer("*!*ERROR: %d is a Reserved USB Device Interface Class\r\n",
USB_DEVICE_CLASS_RESERVED);
displayUnknown = TRUE;
break;
case USB_DEVICE_CLASS_COMMUNICATIONS:
AppendTextBuffer(" -> This is a Communications (CDC Control) USB Device Interface Class\r\n");
displayUnknown = TRUE;
break;
case USB_DEVICE_CLASS_HUMAN_INTERFACE:
AppendTextBuffer(" -> This is a HID USB Device Interface Class\r\n");
displayUnknown = TRUE;
break;
case USB_DEVICE_CLASS_MONITOR:
AppendTextBuffer(" -> This is a Monitor USB Device Interface Class (This may be obsolete)\r\n");
displayUnknown = TRUE;
break;
case USB_DEVICE_CLASS_PHYSICAL_INTERFACE:
AppendTextBuffer(" -> This is a Physical Interface USB Device Interface Class\r\n");
displayUnknown = TRUE;
break;
case USB_DEVICE_CLASS_POWER:
if(bInterfaceSubClass == 1 && bInterfaceProtocol == 1)
{
AppendTextBuffer(" -> This is an Image USB Device Interface Class\r\n");
}
else
{
AppendTextBuffer(" -> This is a Power USB Device Interface Class (This may be obsolete)\r\n");
}
displayUnknown = TRUE;
break;
case USB_DEVICE_CLASS_PRINTER:
AppendTextBuffer(" -> This is a Printer USB Device Interface Class\r\n");
displayUnknown = TRUE;
break;
case USB_DEVICE_CLASS_STORAGE:
AppendTextBuffer(" -> This is a Mass Storage USB Device Interface Class\r\n");
displayUnknown = TRUE;
break;
case USB_DEVICE_CLASS_HUB:
AppendTextBuffer(" -> This is a HUB USB Device Interface Class\r\n");
displayUnknown = TRUE;
break;
case USB_CDC_DATA_INTERFACE:
AppendTextBuffer(" -> This is a CDC Data USB Device Interface Class\r\n");
displayUnknown = TRUE;
break;
case USB_CHIP_SMART_CARD_INTERFACE:
AppendTextBuffer(" -> This is a Chip/Smart Card USB Device Interface Class\r\n");
displayUnknown = TRUE;
break;
case USB_CONTENT_SECURITY_INTERFACE:
AppendTextBuffer(" -> This is a Content Security USB Device Interface Class\r\n");
displayUnknown = TRUE;
break;
case USB_DIAGNOSTIC_DEVICE_INTERFACE:
if(bInterfaceSubClass == 1 && bInterfaceProtocol == 1)
{
AppendTextBuffer(" -> This is a Reprogrammable USB2 Compliance Diagnostic Device USB Device\r\n");
}
else
{
//@@TestCase A2.7
//@@CAUTION
//@@Descriptor Field - bInterfaceClass
//@@An unknown diagnostic interface class device has been defined
AppendTextBuffer("*!*CAUTION: This appears to be an invalid Interface Class\r\n");
OOPS();
}
displayUnknown = TRUE;
break;
case USB_WIRELESS_CONTROLLER_INTERFACE:
if(bInterfaceSubClass == 1 && bInterfaceProtocol == 1)
{
AppendTextBuffer(" -> This is a Wireless RF Controller USB Device Interface Class with Bluetooth Programming Interface\r\n");
}
else
{
//@@TestCase A2.8
//@@CAUTION
//@@Descriptor Field - bInterfaceClass
//@@An unknown wireless controller interface class device has been defined
AppendTextBuffer("*!*CAUTION: This appears to be an invalid Interface Class\r\n");
OOPS();
}
displayUnknown = TRUE;
break;
case USB_APPLICATION_SPECIFIC_INTERFACE:
AppendTextBuffer(" -> This is an Application Specific USB Device Interface Class\r\n");
switch(bInterfaceSubClass)
{
case 1:
AppendTextBuffer(" -> This is a Device Firmware Application Specific USB Device Interface Class\r\n");
break;
case 2:
AppendTextBuffer(" -> This is an IrDA Bridge Application Specific USB Device Interface Class\r\n");
break;
case 3:
AppendTextBuffer(" -> This is a Test & Measurement Class (USBTMC) Application Specific USB Device Interface Class\r\n");
break;
default:
//@@TestCase A2.9
//@@CAUTION
//@@Descriptor Field - bInterfaceClass
//@@A possibly invalid interface class has been defined
AppendTextBuffer("*!*CAUTION: This appears to be an invalid Interface Class\r\n");
OOPS();
}
displayUnknown = TRUE;
break;
default:
if (bInterfaceClass == USB_DEVICE_CLASS_VENDOR_SPECIFIC)
{
AppendTextBuffer(" -> This is a Vendor Specific USB Device Interface Class\r\n");
}
else
{
//@@TestCase A2.10
//@@CAUTION
//@@Descriptor Field - bInterfaceClass
//@@An unknown interface class has been defined
AppendTextBuffer("*!*CAUTION: This appears to be an invalid Interface Class\r\n");
OOPS();
}
displayUnknown = TRUE;
break;
}
break;
}
if (displayUnknown)
{
DisplayUnknownDescriptor(commonDesc);
}
} while ((commonDesc = GetNextDescriptor((PUSB_COMMON_DESCRIPTOR)ConfigDesc,
ConfigDesc->wTotalLength,
commonDesc,
-1)) != NULL);
#ifdef H264_SUPPORT
DoAdditionalErrorChecks();
#endif
}
/*****************************************************************************
DisplayDeviceQualifierDescriptor()
*****************************************************************************/
VOID
DisplayDeviceQualifierDescriptor (
PUSB_DEVICE_QUALIFIER_DESCRIPTOR DevQualDesc
)
{
//@@DisplayDeviceQualifierDescriptor - Device Qualifier Descriptor
AppendTextBuffer("\r\n ===>Device Qualifier Descriptor<===\r\n");
//length checked in DisplayConfigDesc()
AppendTextBuffer("bLength: 0x%02X\r\n",
DevQualDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
DevQualDesc->bDescriptorType);
AppendTextBuffer("bcdUSB: 0x%04X\r\n",
DevQualDesc->bcdUSB);
AppendTextBuffer("bDeviceClass: 0x%02X",
DevQualDesc->bDeviceClass);
switch (DevQualDesc->bDeviceClass)
{
case USB_INTERFACE_CLASS_DEVICE:
if(gDoAnnotation)
{
AppendTextBuffer(" -> This is an Interface Class Defined Device\r\n");
}
break;
case USB_COMMUNICATION_DEVICE:
if(gDoAnnotation)
{
AppendTextBuffer(" -> This is a Communication Device\r\n");
}
break;
case USB_HUB_DEVICE:
if(gDoAnnotation)
{
AppendTextBuffer(" -> This is a HUB Device\r\n");
}
break;
case USB_DIAGNOSTIC_DEVICE:
if(gDoAnnotation)
{
AppendTextBuffer(" -> This is a Diagnostic Device\r\n");
}
break;
case USB_WIRELESS_CONTROLLER_DEVICE:
if(gDoAnnotation)
{
AppendTextBuffer(" -> This is a Wireless Controller(Bluetooth) Device\r\n");
}
break;
case USB_VENDOR_SPECIFIC_DEVICE:
if(gDoAnnotation)
{
AppendTextBuffer(" -> This is a Vendor Specific Device\r\n");
}
break;
case USB_DEVICE_CLASS_BILLBOARD:
if (gDoAnnotation)
{
AppendTextBuffer(" -> This is a billboard class device\r\n");
}
break;
default:
//@@TestCase A3.1
//@@ERROR
//@@Descriptor Field - bDeviceClass
//@@An unknown device class has been defined
AppendTextBuffer("*!*ERROR: bDeviceClass of %d is invalid\r\n",
DevQualDesc->bDeviceClass);
OOPS();
break;
}
AppendTextBuffer("bDeviceSubClass: 0x%02X\r\n",
DevQualDesc->bDeviceSubClass);
if(DevQualDesc->bDeviceSubClass > 0x00 && DevQualDesc->bDeviceSubClass < 0xFF)
{
//@@TestCase A3.2
//@@ERROR
//@@Descriptor Field - bDeviceSubClass
//@@An unknown device sub class has been defined
AppendTextBuffer("*!*ERROR: bDeviceSubClass of %d is invalid\r\n",
DevQualDesc->bDeviceSubClass);
OOPS();
}
AppendTextBuffer("bDeviceProtocol: 0x%02X\r\n",
DevQualDesc->bDeviceProtocol);
if(DevQualDesc->bDeviceProtocol > 0x00 && DevQualDesc->bDeviceProtocol < 0xFF)
{
//@@TestCase A3.4
//@@ERROR
//@@Descriptor Field - bDeviceProtocol
//@@An invalid device protocol has been defined
AppendTextBuffer("*!*ERROR: bDeviceProtocol of %d is invalid",
DevQualDesc->bDeviceProtocol);
OOPS();
}
//@@TestCase A3.5
//@@Priority 1
//@@Descriptor Field - bcdDevice
//@@We should test to verify a valid bMaxPacketSize0 based on speed
AppendTextBuffer("bMaxPacketSize0: 0x%02X",
DevQualDesc->bMaxPacketSize0);
if(gDoAnnotation)
{
AppendTextBuffer(" = (%d) Bytes\r\n",
DevQualDesc->bMaxPacketSize0);
}
else {AppendTextBuffer("\r\n");}
AppendTextBuffer("bNumConfigurations: 0x%02X\r\n",
DevQualDesc->bNumConfigurations);
if(DevQualDesc->bNumConfigurations != 1)
{
//@@TestCase A3.6
//@@CAUTION
//@@Descriptor Field - bNumConfigurations
//@@Most host controllers do not handle more than one configuration
AppendTextBuffer("*!*CAUTION: Most host controllers will only work with one configuration per speed\r\n");
OOPS();
}
AppendTextBuffer("bReserved: 0x%02X\r\n",
DevQualDesc->bReserved);
if(DevQualDesc->bReserved != 0)
{
AppendTextBuffer("*!*WARNING: bReserved needs to be set to 0 to be valid\r\n");
OOPS();
}
}
VOID
DisplayUsb20CapabilityExtensionDescriptor (
PUSB_DEVICE_CAPABILITY_USB20_EXTENSION_DESCRIPTOR extCapDesc
)
{
AppendTextBuffer("\r\n ===>USB 2.0 Extension Descriptor<===\r\n");
AppendTextBuffer("bLength: 0x%02X\r\n",
extCapDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
extCapDesc->bDescriptorType);
AppendTextBuffer("bDevCapabilityType: 0x%02X\r\n",
extCapDesc->bDevCapabilityType);
AppendTextBuffer("bmAttributes: 0x%08X",
extCapDesc->bmAttributes);
if (extCapDesc->bmAttributes.AsUlong & USB_DEVICE_CAPABILITY_USB20_EXTENSION_BMATTRIBUTES_RESERVED_MASK)
{
if(gDoAnnotation)
{
AppendTextBuffer("\r\n*!*ERROR: bits 31..2 and bit 0 are reserved and must be 0\r\n");
}
}
if (extCapDesc->bmAttributes.LPMCapable == 1)
{
if(gDoAnnotation)
{
AppendTextBuffer(" -> Supports Link Power Management protocol\r\n");
}
}
if (extCapDesc->bmAttributes.AsUlong == 0)
{
AppendTextBuffer("\r\n");
}
}
VOID
DisplaySuperSpeedCapabilityExtensionDescriptor (
PUSB_DEVICE_CAPABILITY_SUPERSPEED_USB_DESCRIPTOR ssCapDesc
)
{
AppendTextBuffer("\r\n ===>SuperSpeed USB Device Capability Descriptor<===\r\n");
AppendTextBuffer("bLength: 0x%02X\r\n",
ssCapDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
ssCapDesc->bDescriptorType);
AppendTextBuffer("bDevCapabilityType: 0x%02X\r\n",
ssCapDesc->bDevCapabilityType);
AppendTextBuffer("bmAttributes: 0x%02X\r\n",
ssCapDesc->bmAttributes);
if (ssCapDesc->bmAttributes & USB_DEVICE_CAPABILITY_SUPERSPEED_BMATTRIBUTES_RESERVED_MASK)
{
if(gDoAnnotation)
{
AppendTextBuffer("\r\n*!*ERROR: bits 7:2 and bit 0 are reserved\r\n");
}
}
if (ssCapDesc->bmAttributes & USB_DEVICE_CAPABILITY_SUPERSPEED_BMATTRIBUTES_LTM_CAPABLE)
{
if(gDoAnnotation)
{
AppendTextBuffer(" -> capable of generating Latency Tolerance Messages\r\n");
}
}
AppendTextBuffer("wSpeedsSupported: 0x%02X\r\n",
ssCapDesc->wSpeedsSupported);
if (ssCapDesc->wSpeedsSupported & USB_DEVICE_CAPABILITY_SUPERSPEED_SPEEDS_SUPPORTED_LOW)
{
if(gDoAnnotation)
{
AppendTextBuffer(" -> Supports low-speed operation\r\n");
}
}
if (ssCapDesc->wSpeedsSupported & USB_DEVICE_CAPABILITY_SUPERSPEED_SPEEDS_SUPPORTED_FULL)
{
if(gDoAnnotation)
{
AppendTextBuffer(" -> Supports full-speed operation\r\n");
}
}
if (ssCapDesc->wSpeedsSupported & USB_DEVICE_CAPABILITY_SUPERSPEED_SPEEDS_SUPPORTED_HIGH)
{
if(gDoAnnotation)
{
AppendTextBuffer(" -> Supports high-speed operation\r\n");
}
}
if (ssCapDesc->wSpeedsSupported & USB_DEVICE_CAPABILITY_SUPERSPEED_SPEEDS_SUPPORTED_SUPER)
{
if(gDoAnnotation)
{
AppendTextBuffer(" -> Supports SuperSpeed operation\r\n");
}
}
if (ssCapDesc->wSpeedsSupported & USB_DEVICE_CAPABILITY_SUPERSPEED_SPEEDS_SUPPORTED_RESERVED_MASK)
{
if(gDoAnnotation)
{
AppendTextBuffer("\r\n*!*ERROR: bits 15:4 are reserved\r\n");
}
}
if (!gDoAnnotation)
{
AppendTextBuffer("\r\n");
}
AppendTextBuffer("bFunctionalitySupport: 0x%02X",
ssCapDesc->bFunctionalitySupport);
if(gDoAnnotation)
{
switch (ssCapDesc->bFunctionalitySupport)
{
case UsbLowSpeed:
AppendTextBuffer(" -> lowest speed = low-speed\r\n");
break;
case UsbFullSpeed:
AppendTextBuffer(" -> lowest speed = full-speed\r\n");
break;
case UsbHighSpeed:
AppendTextBuffer(" -> lowest speed = high-speed\r\n");
break;
case UsbSuperSpeed:
AppendTextBuffer(" -> lowest speed = SuperSpeed\r\n");
break;
default:
AppendTextBuffer("\r\n*!*ERROR: Invalid value\r\n");
break;
}
}
else
{
AppendTextBuffer("\r\n");
}
AppendTextBuffer("bU1DevExitLat: 0x%02X",
ssCapDesc->bU1DevExitLat);
if(gDoAnnotation)
{
if (ssCapDesc->bU1DevExitLat <= USB_DEVICE_CAPABILITY_SUPERSPEED_U1_DEVICE_EXIT_MAX_VALUE)
{
AppendTextBuffer(" -> less than %d micro-seconds\r\n",
ssCapDesc->bU1DevExitLat);
}
else
{
AppendTextBuffer("\r\n*!*ERROR: Invalid value\r\n");
}
}
else
{
AppendTextBuffer("\r\n");
}
AppendTextBuffer("wU2DevExitLat: 0x%04X",
ssCapDesc->wU2DevExitLat);
if(gDoAnnotation)
{
if (ssCapDesc->wU2DevExitLat <= USB_DEVICE_CAPABILITY_SUPERSPEED_U2_DEVICE_EXIT_MAX_VALUE)
{
AppendTextBuffer(" -> less than %d micro-seconds\r\n",
ssCapDesc->wU2DevExitLat);
}
else
{
AppendTextBuffer("\r\n*!*ERROR: Invalid value\r\n");
}
}
else
{
AppendTextBuffer("\r\n");
}
}
VOID
DisplayContainerIdCapabilityExtensionDescriptor (
PUSB_DEVICE_CAPABILITY_CONTAINER_ID_DESCRIPTOR containerIdCapDesc
)
{
LPGUID pGuid;
AppendTextBuffer("\r\n ===>Container ID Capability Descriptor<===\r\n");
AppendTextBuffer("bLength: 0x%02X\r\n",
containerIdCapDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
containerIdCapDesc->bDescriptorType);
AppendTextBuffer("bDevCapabilityType: 0x%02X\r\n",
containerIdCapDesc->bDevCapabilityType);
AppendTextBuffer("bReserved: 0x%02X\r\n",
containerIdCapDesc->bReserved);
if (containerIdCapDesc->bReserved != 0)
{
if(gDoAnnotation)
{
AppendTextBuffer("*!*ERROR: field is reserved\r\n");
}
}
pGuid = (LPGUID)containerIdCapDesc->ContainerID;
AppendTextBuffer("Container ID: ");
AppendTextBuffer("%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X\r\n",
pGuid->Data1,
pGuid->Data2,
pGuid->Data3,
pGuid->Data4[0],
pGuid->Data4[1],
pGuid->Data4[2],
pGuid->Data4[3],
pGuid->Data4[4],
pGuid->Data4[5],
pGuid->Data4[6],
pGuid->Data4[7]);
}
VOID
DisplayBillboardCapabilityDescriptor (
PUSBDEVICEINFO info,
PUSB_DEVICE_CAPABILITY_BILLBOARD_DESCRIPTOR billboardCapDesc,
PSTRING_DESCRIPTOR_NODE StringDescs
)
{
UCHAR i = 0;
UCHAR bNumAlternateModes = 0;
UCHAR alternateModeConfiguration = 0;
UCHAR adjustedBLength = 0;
AppendTextBuffer("\r\n ===>Billboard Capability Descriptor<===\r\n");
AppendTextBuffer("bLength: 0x%02X",
billboardCapDesc->bLength);
adjustedBLength = sizeof(USB_DEVICE_CAPABILITY_BILLBOARD_DESCRIPTOR) +
sizeof(billboardCapDesc->AlternateMode[0]) * (billboardCapDesc->bNumberOfAlternateModes - 1);
AppendTextBuffer(" -> Actual Length: 0x%02X\r\n", adjustedBLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
billboardCapDesc->bDescriptorType);
AppendTextBuffer("bDevCapabilityType: 0x%02X -> Billboard capability\r\n",
billboardCapDesc->bDevCapabilityType);
AppendTextBuffer("iAdditionalInfoURL: 0x%02X ->",
billboardCapDesc->iAddtionalInfoURL);
if (billboardCapDesc->iAddtionalInfoURL && gDoAnnotation) {
DisplayStringDescriptor(billboardCapDesc->iAddtionalInfoURL,
StringDescs,
info->DeviceInfoNode != NULL ? info->DeviceInfoNode->LatestDevicePowerState : PowerDeviceUnspecified);
}
AppendTextBuffer("bNumberOfAlternateModes: 0x%02X\r\n",
billboardCapDesc->bNumberOfAlternateModes);
if (billboardCapDesc->bNumberOfAlternateModes > BILLBOARD_MAX_NUM_ALT_MODE)
{
AppendTextBuffer("*!*ERROR: Invalid bNumberofAlternateModes\r\n");
}
AppendTextBuffer("bPreferredAlternateMode: 0x%02X\r\n",
billboardCapDesc->bPreferredAlternateMode);
AppendTextBuffer("VCONN Power: 0x%04X",
billboardCapDesc->VconnPower);
if (billboardCapDesc->VconnPower.NoVconnPowerRequired)
{
AppendTextBuffer(" -> The adapter does not require Vconn Power. Bits 2..0 ignored\r\n");
}
else
{
switch (billboardCapDesc->VconnPower.VConnPowerNeededForFullFunctionality)
{
case 0:
AppendTextBuffer(" -> 1W needed by adapter for full functionality\r\n");
break;
case 1:
AppendTextBuffer(" -> 1.5W needed by adapter for full functionality\r\n");
break;
case 7:
AppendTextBuffer(" -> *!*ERROR: VConnPowerNeededForFullFunctionality - Reserved value being used\r\n");
break;
default:
AppendTextBuffer(" -> %2XW needed by adapter for full functionality\r\n", billboardCapDesc->VconnPower.VConnPowerNeededForFullFunctionality);
}
}
if (billboardCapDesc->VconnPower.Reserved)
{
AppendTextBuffer("*!*ERROR: Reserved bits in VCONN Power being used\r\n");
}
if (billboardCapDesc->bReserved)
{
AppendTextBuffer("*!*ERROR: bReserved being used\r\n");
}
bNumAlternateModes = billboardCapDesc->bNumberOfAlternateModes;
if (bNumAlternateModes > BILLBOARD_MAX_NUM_ALT_MODE)
{
bNumAlternateModes = BILLBOARD_MAX_NUM_ALT_MODE;
}
if (bNumAlternateModes > 0)
{
AppendTextBuffer("\r\nAlternate Modes Identified:\r\n");
}
for (i = 0; i < bNumAlternateModes; i++)
{
alternateModeConfiguration = ((billboardCapDesc->bmConfigured[i / 4]) >> ((i % 4) * 2)) & 0x3;
AppendTextBuffer("wSVID - 0x%04X bAlternateMode - 0x%02X ->",
billboardCapDesc->AlternateMode[i].wSVID,
billboardCapDesc->AlternateMode[i].bAlternateMode,
billboardCapDesc->AlternateMode[i].iAlternateModeSetting);
switch (alternateModeConfiguration)
{
case 0:
AppendTextBuffer("Unspecified Error\r\n");
break;
case 1:
AppendTextBuffer("Alternate Mode configuration not attempted\r\n");
break;
case 2:
AppendTextBuffer("Alternate Mode configuration attempted but unsuccessful\r\n");
break;
case 3:
AppendTextBuffer("Alternate Mode configuration successful\r\n");
break;
}
AppendTextBuffer("iAlternateModeString - 0x%02X ", billboardCapDesc->AlternateMode[i].iAlternateModeSetting);
if (billboardCapDesc->AlternateMode[i].iAlternateModeSetting && gDoAnnotation)
{
DisplayStringDescriptor(billboardCapDesc->AlternateMode[i].iAlternateModeSetting,
StringDescs,
info->DeviceInfoNode != NULL ? info->DeviceInfoNode->LatestDevicePowerState : PowerDeviceUnspecified);
}
else
{
AppendTextBuffer("\r\n");
}
AppendTextBuffer("\r\n");
}
}
/*****************************************************************************
DisplayBosDescriptor()
BosDesc - The Binary Object Store (BOS) Descriptor, and associated Descriptors
*****************************************************************************/
VOID
DisplayBosDescriptor (
PUSBDEVICEINFO info,
PUSB_BOS_DESCRIPTOR BosDesc,
PSTRING_DESCRIPTOR_NODE StringDescs
)
{
PUSB_COMMON_DESCRIPTOR commonDesc = NULL;
PUSB_DEVICE_CAPABILITY_DESCRIPTOR capDesc = NULL;
AppendTextBuffer("\r\n ===>BOS Descriptor<===\r\n");
AppendTextBuffer("bLength: 0x%02X\r\n",
BosDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
BosDesc->bDescriptorType);
AppendTextBuffer("wTotalLength: 0x%04X\r\n",
BosDesc->wTotalLength);
AppendTextBuffer("bNumDeviceCaps: 0x%02X\r\n",
BosDesc->bNumDeviceCaps);
commonDesc = (PUSB_COMMON_DESCRIPTOR)BosDesc;
while ((commonDesc = GetNextDescriptor((PUSB_COMMON_DESCRIPTOR)BosDesc,
BosDesc->wTotalLength,
commonDesc,
-1)) != NULL)
{
switch (commonDesc->bDescriptorType)
{
case USB_DEVICE_CAPABILITY_DESCRIPTOR_TYPE:
capDesc = (PUSB_DEVICE_CAPABILITY_DESCRIPTOR)commonDesc;
switch (capDesc->bDevCapabilityType)
{
case USB_DEVICE_CAPABILITY_USB20_EXTENSION:
DisplayUsb20CapabilityExtensionDescriptor((PUSB_DEVICE_CAPABILITY_USB20_EXTENSION_DESCRIPTOR)capDesc);
break;
case USB_DEVICE_CAPABILITY_SUPERSPEED_USB:
DisplaySuperSpeedCapabilityExtensionDescriptor((PUSB_DEVICE_CAPABILITY_SUPERSPEED_USB_DESCRIPTOR)capDesc);
break;
case USB_DEVICE_CAPABILITY_CONTAINER_ID:
DisplayContainerIdCapabilityExtensionDescriptor((PUSB_DEVICE_CAPABILITY_CONTAINER_ID_DESCRIPTOR)capDesc);
break;
case USB_DEVICE_CAPABILITY_BILLBOARD:
DisplayBillboardCapabilityDescriptor((PUSBDEVICEINFO) info, (PUSB_DEVICE_CAPABILITY_BILLBOARD_DESCRIPTOR) capDesc, StringDescs);
break;
default:
AppendTextBuffer("\r\n ===>Unknown Capability Descriptor<===\r\n");
AppendTextBuffer("bLength: 0x%02X\r\n",
capDesc->bLength);
AppendTextBuffer("bType: 0x%02X\r\n",
capDesc->bLength);
AppendTextBuffer("bDevCapabilityType: 0x%02X\r\n",
capDesc->bDevCapabilityType);
DisplayRemainingUnknownDescriptor((PUCHAR)commonDesc,
(ULONG)sizeof(USB_DEVICE_CAPABILITY_DESCRIPTOR),
commonDesc->bLength);
break;
}
break;
default:
DisplayUnknownDescriptor(commonDesc);
break;
}
}
}
/*****************************************************************************
DisplayConfigurationDescriptor()
*****************************************************************************/
VOID
DisplayConfigurationDescriptor (
PUSBDEVICEINFO info,
PUSB_CONFIGURATION_DESCRIPTOR ConfigDesc,
PSTRING_DESCRIPTOR_NODE StringDescs
)
{
UINT uCount = 0;
BOOL isSS;
isSS = info->ConnectionInfoV2
&& (info->ConnectionInfoV2->Flags.DeviceIsOperatingAtSuperSpeedOrHigher ||
info->ConnectionInfoV2->Flags.DeviceIsOperatingAtSuperSpeedPlusOrHigher)
? TRUE
: FALSE;
AppendTextBuffer("\r\n ===>Configuration Descriptor<===\r\n");
//@@DisplayConfigurationDescriptor - Configuration Descriptor
//length checked in DisplayConfigDesc()
AppendTextBuffer("bLength: 0x%02X\r\n",
ConfigDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
ConfigDesc->bDescriptorType);
//@@TestCase A4.1
//@@Priority 1
//@@Descriptor Field - wTotalLength
//@@Verify Configuration length is valid
AppendTextBuffer("wTotalLength: 0x%04X",
ConfigDesc->wTotalLength);
uCount = GetConfigurationSize(info);
if (uCount != ConfigDesc->wTotalLength) {
AppendTextBuffer("\r\n*!*ERROR: Invalid total configuration size 0x%02X, should be 0x%02X\r\n",
ConfigDesc->wTotalLength, uCount);
} else {
AppendTextBuffer(" -> Validated\r\n");
}
//@@TestCase A4.2
//@@Priority 1
//@@Descriptor Field - bNumInterfaces
//@@Verify the number of interfaces is valid
AppendTextBuffer("bNumInterfaces: 0x%02X\r\n",
ConfigDesc->bNumInterfaces);
/* Need to check spec vs composite devices
uCount = GetInterfaceCount(info);
if (uCount != ConfigDesc->bNumInterfaces) {
AppendTextBuffer("\r\n*!*ERROR: Invalid total Interfaces %d, should be %d\r\n",
ConfigDesc->bNumInterfaces, uCount);
} else {
AppendTextBuffer(" -> Validated\r\n");
}
*/
AppendTextBuffer("bConfigurationValue: 0x%02X\r\n",
ConfigDesc->bConfigurationValue);
if(ConfigDesc->bConfigurationValue != 1)
{
//@@TestCase A4.3
//@@CAUTION
//@@Descriptor Field - bConfigurationValue
//@@Most host controllers do not handle more than one configuration
AppendTextBuffer("*!*CAUTION: Most host controllers will only work with one configuration per speed\r\n");
OOPS();
}
AppendTextBuffer("iConfiguration: 0x%02X\r\n",
ConfigDesc->iConfiguration);
if (ConfigDesc->iConfiguration && gDoAnnotation)
{
DisplayStringDescriptor(ConfigDesc->iConfiguration,
StringDescs,
info->DeviceInfoNode != NULL? info->DeviceInfoNode->LatestDevicePowerState: PowerDeviceUnspecified);
}
AppendTextBuffer("bmAttributes: 0x%02X",
ConfigDesc->bmAttributes);
if (info->ConnectionInfo->DeviceDescriptor.bcdUSB == 0x0100)
{
if (ConfigDesc->bmAttributes & USB_CONFIG_SELF_POWERED)
{
if(gDoAnnotation)
{
AppendTextBuffer(" -> Self Powered\r\n");
}
}
if (ConfigDesc->bmAttributes & USB_CONFIG_BUS_POWERED)
{
if(gDoAnnotation)
{
AppendTextBuffer(" -> Bus Powered\r\n");
}
}
}
else
{
if (ConfigDesc->bmAttributes & USB_CONFIG_SELF_POWERED)
{
if(gDoAnnotation)
{
AppendTextBuffer(" -> Self Powered\r\n");
}
}
else
{
if(gDoAnnotation)
{
AppendTextBuffer(" -> Bus Powered\r\n");
}
}
if ((ConfigDesc->bmAttributes & USB_CONFIG_BUS_POWERED) == 0)
{
AppendTextBuffer("\r\n*!*ERROR: Bit 7 is reserved and must be set\r\n");
OOPS();
}
}
if (ConfigDesc->bmAttributes & USB_CONFIG_REMOTE_WAKEUP)
{
if(gDoAnnotation)
{
AppendTextBuffer(" -> Remote Wakeup\r\n");
}
}
if (ConfigDesc->bmAttributes & USB_CONFIG_RESERVED)
{
//@@TestCase A4.4
//@@WARNING
//@@Descriptor Field - bmAttributes
//@@A bit has been set in reserved space
AppendTextBuffer("\r\n*!*ERROR: Bits 4...0 are reserved\r\n");
OOPS();
}
AppendTextBuffer("MaxPower: 0x%02X",
ConfigDesc->MaxPower);
if(gDoAnnotation)
{
AppendTextBuffer(" = %3d mA\r\n",
isSS ? ConfigDesc->MaxPower * 8 : ConfigDesc->MaxPower * 2);
}
else {AppendTextBuffer("\r\n");}
}
/*****************************************************************************
DisplayInterfaceDescriptor()
*****************************************************************************/
VOID
DisplayInterfaceDescriptor (
PUSB_INTERFACE_DESCRIPTOR InterfaceDesc,
PSTRING_DESCRIPTOR_NODE StringDescs,
DEVICE_POWER_STATE LatestDevicePowerState
)
{
//@@DisplayInterfaceDescriptor - Interface Descriptor
AppendTextBuffer("\r\n ===>Interface Descriptor<===\r\n");
//length checked in DisplayConfigDesc()
AppendTextBuffer("bLength: 0x%02X\r\n",
InterfaceDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
InterfaceDesc->bDescriptorType);
//@@TestCase A5.1
//@@Priority 1
//@@Descriptor Field - bInterfaceNumber
//@@Question - Should we test to verify bInterfaceNumber is valid?
AppendTextBuffer("bInterfaceNumber: 0x%02X\r\n",
InterfaceDesc->bInterfaceNumber);
//@@TestCase A5.2
//@@Priority 1
//@@Descriptor Field - bAlternateSetting
//@@Question - Should we test to verify bAlternateSetting is valid?
AppendTextBuffer("bAlternateSetting: 0x%02X\r\n",
InterfaceDesc->bAlternateSetting);
//@@TestCase A5.3
//@@Priority 1
//@@Descriptor Field - bNumEndpoints
//@@Question - Should we test to verify bNumEndpoints is valid?
AppendTextBuffer("bNumEndpoints: 0x%02X\r\n",
InterfaceDesc->bNumEndpoints);
AppendTextBuffer("bInterfaceClass: 0x%02X",
InterfaceDesc->bInterfaceClass);
switch (InterfaceDesc->bInterfaceClass)
{
case USB_DEVICE_CLASS_AUDIO:
if(gDoAnnotation)
{
AppendTextBuffer(" -> Audio Interface Class\r\n");
}
AppendTextBuffer("bInterfaceSubClass: 0x%02X",
InterfaceDesc->bInterfaceSubClass);
if(gDoAnnotation)
{
switch (InterfaceDesc->bInterfaceSubClass)
{
case USB_AUDIO_SUBCLASS_AUDIOCONTROL:
AppendTextBuffer(" -> Audio Control Interface SubClass\r\n");
break;
case USB_AUDIO_SUBCLASS_AUDIOSTREAMING:
AppendTextBuffer(" -> Audio Streaming Interface SubClass\r\n");
break;
case USB_AUDIO_SUBCLASS_MIDISTREAMING:
AppendTextBuffer(" -> MIDI Streaming Interface SubClass\r\n");
break;
default:
//@@TestCase A5.4
//@@CAUTION
//@@Descriptor Field - bInterfaceSubClass
//@@Invalid bInterfaceSubClass
AppendTextBuffer("\r\n*!*CAUTION: This appears to be an invalid bInterfaceSubClass\r\n");
OOPS();
break;
}
}
break;
case USB_DEVICE_CLASS_VIDEO:
if(gDoAnnotation)
AppendTextBuffer(" -> Video Interface Class\r\n");
AppendTextBuffer("bInterfaceSubClass: 0x%02X",
InterfaceDesc->bInterfaceSubClass);
switch(InterfaceDesc->bInterfaceSubClass)
{
case VIDEO_SUBCLASS_CONTROL:
if(gDoAnnotation)
{
AppendTextBuffer(" -> Video Control Interface SubClass\r\n");
}
break;
case VIDEO_SUBCLASS_STREAMING:
if(gDoAnnotation)
{
AppendTextBuffer(" -> Video Streaming Interface SubClass\r\n");
}
break;
default:
//@@TestCase A5.5
//@@CAUTION
//@@Descriptor Field - bInterfaceSubClass
//@@Invalid bInterfaceSubClass
AppendTextBuffer("\r\n*!*CAUTION: This appears to be an invalid bInterfaceSubClass\r\n");
OOPS();
break;
}
break;
case USB_DEVICE_CLASS_HUMAN_INTERFACE:
if(gDoAnnotation)
{
AppendTextBuffer(" -> HID Interface Class\r\n");
}
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_DEVICE_CLASS_HUB:
if(gDoAnnotation)
{
AppendTextBuffer(" -> HUB Interface Class\r\n");
}
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_DEVICE_CLASS_RESERVED:
//@@TestCase A5.6
//@@CAUTION
//@@Descriptor Field - bInterfaceClass
//@@A reserved USB Device Interface Class has been defined
AppendTextBuffer("\r\n*!*CAUTION: %d is a Reserved USB Device Interface Class\r\n",
USB_DEVICE_CLASS_RESERVED);
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_DEVICE_CLASS_COMMUNICATIONS:
AppendTextBuffer(" -> This is Communications (CDC Control) USB Device Interface Class\r\n");
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_DEVICE_CLASS_MONITOR:
AppendTextBuffer(" -> This is a Monitor USB Device Interface Class*** (This may be obsolete)\r\n");
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_DEVICE_CLASS_PHYSICAL_INTERFACE:
AppendTextBuffer(" -> This is a Physical Interface USB Device Interface Class\r\n");
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_DEVICE_CLASS_POWER:
if(InterfaceDesc->bInterfaceSubClass == 1 && InterfaceDesc->bInterfaceProtocol == 1)
{
AppendTextBuffer(" -> This is an Image USB Device Interface Class\r\n");
}
else
{
AppendTextBuffer(" -> This is a Power USB Device Interface Class (This may be obsolete)\r\n");
}
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_DEVICE_CLASS_PRINTER:
AppendTextBuffer(" -> This is a Printer USB Device Interface Class\r\n");
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_DEVICE_CLASS_STORAGE:
AppendTextBuffer(" -> This is a Mass Storage USB Device Interface Class\r\n");
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_CDC_DATA_INTERFACE:
AppendTextBuffer(" -> This is a CDC Data USB Device Interface Class\r\n");
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_CHIP_SMART_CARD_INTERFACE:
AppendTextBuffer(" -> This is a Chip/Smart Card USB Device Interface Class\r\n");
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_CONTENT_SECURITY_INTERFACE:
AppendTextBuffer(" -> This is a Content Security USB Device Interface Class\r\n");
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_DIAGNOSTIC_DEVICE_INTERFACE:
if(InterfaceDesc->bInterfaceSubClass == 1 && InterfaceDesc->bInterfaceProtocol == 1)
{
AppendTextBuffer(" -> This is a Reprogrammable USB2 Compliance Diagnostic Device USB Device\r\n");
}
else
{
//@@TestCase A5.7
//@@CAUTION
//@@Descriptor Field - bInterfaceClass
//@@Invalid Interface Class
AppendTextBuffer("\r\n*!*CAUTION: This appears to be an invalid Interface Class\r\n");
OOPS();
}
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_WIRELESS_CONTROLLER_INTERFACE:
if(InterfaceDesc->bInterfaceSubClass == 1 && InterfaceDesc->bInterfaceProtocol == 1)
{
AppendTextBuffer(" -> This is a Wireless RF Controller USB Device Interface Class with Bluetooth Programming Interface\r\n");
}
else
{
//@@TestCase A5.8
//@@CAUTION
//@@Descriptor Field - bInterfaceClass
//@@Invalid Interface Class
AppendTextBuffer("\r\n*!*CAUTION: This appears to be an invalid Interface Class\r\n");
OOPS();
}
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_APPLICATION_SPECIFIC_INTERFACE:
AppendTextBuffer(" -> This is an Application Specific USB Device Interface Class\r\n");
switch(InterfaceDesc->bInterfaceSubClass)
{
case 1:
AppendTextBuffer(" -> This is a Device Firmware Application Specific USB Device Interface Class\r\n");
break;
case 2:
AppendTextBuffer(" -> This is an IrDA Bridge Application Specific USB Device Interface Class\r\n");
break;
case 3:
AppendTextBuffer(" -> This is a Test & Measurement Class (USBTMC) Application Specific USB Device Interface Class\r\n");
break;
default:
//@@TestCase A5.9
//@@CAUTION
//@@Descriptor Field - bInterfaceClass
//@@Invalid Interface Class
AppendTextBuffer("\r\n*!*CAUTION: This appears to be an invalid Interface Class\r\n");
OOPS();
}
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
case USB_DEVICE_CLASS_BILLBOARD:
AppendTextBuffer(" -> Billboard Class\r\n");
AppendTextBuffer("bInterfaceSubClass: 0x%02X", InterfaceDesc->bInterfaceSubClass);
switch (InterfaceDesc->bInterfaceSubClass)
{
case 0:
AppendTextBuffer(" -> Billboard Subclass\r\n");
break;
default:
AppendTextBuffer("\r\n*!*CAUTION: This appears to be an invalid bInterfaceSubClass\r\n");
break;
}
break;
default:
if(gDoAnnotation)
{
AppendTextBuffer(" -> Interface Class Unknown to USBView\r\n");
}
AppendTextBuffer("bInterfaceSubClass: 0x%02X\r\n",
InterfaceDesc->bInterfaceSubClass);
break;
}
AppendTextBuffer("bInterfaceProtocol: 0x%02X\r\n",
InterfaceDesc->bInterfaceProtocol);
//This is basically the check for PC_PROTOCOL_UNDEFINED
if ((InterfaceDesc->bInterfaceClass == USB_DEVICE_CLASS_VIDEO) ||
(InterfaceDesc->bInterfaceClass == USB_DEVICE_CLASS_AUDIO))
{
if(InterfaceDesc->bInterfaceProtocol != PC_PROTOCOL_UNDEFINED)
{
//@@TestCase A5.10
//@@WARNING
//@@Descriptor Field - iInterface
//@@bInterfaceProtocol must be set to PC_PROTOCOL_UNDEFINED
AppendTextBuffer("*!*WARNING: must be set to PC_PROTOCOL_UNDEFINED %d for this class\r\n",
PC_PROTOCOL_UNDEFINED);
OOPS();
}
}
AppendTextBuffer("iInterface: 0x%02X\r\n",
InterfaceDesc->iInterface);
if(gDoAnnotation)
{
if (InterfaceDesc->iInterface)
{
DisplayStringDescriptor(InterfaceDesc->iInterface,
StringDescs,
LatestDevicePowerState);
}
}
if (InterfaceDesc->bLength == sizeof(USB_INTERFACE_DESCRIPTOR2))
{
PUSB_INTERFACE_DESCRIPTOR2 interfaceDesc2;
interfaceDesc2 = (PUSB_INTERFACE_DESCRIPTOR2)InterfaceDesc;
AppendTextBuffer("wNumClasses: 0x%04X\r\n",
interfaceDesc2->wNumClasses);
}
}
/*****************************************************************************
DisplayEndpointDescriptor()
*****************************************************************************/
VOID
DisplayEndpointDescriptor (
_In_ PUSB_ENDPOINT_DESCRIPTOR
EndpointDesc,
_In_opt_ PUSB_SUPERSPEED_ENDPOINT_COMPANION_DESCRIPTOR
EpCompDesc,
_In_opt_ PUSB_SUPERSPEEDPLUS_ISOCH_ENDPOINT_COMPANION_DESCRIPTOR
SspIsochEpCompDesc,
_In_ UCHAR InterfaceClass,
_In_ BOOLEAN EpCompDescAvail
)
{
UCHAR epType = EndpointDesc->bmAttributes & USB_ENDPOINT_TYPE_MASK;
PUSB_HIGH_SPEED_MAXPACKET hsMaxPacket;
AppendTextBuffer("\r\n ===>Endpoint Descriptor<===\r\n");
//@@DisplayEndpointDescriptor - Endpoint Descriptor
//length checked in DisplayConfigDesc()
AppendTextBuffer("bLength: 0x%02X\r\n",
EndpointDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
EndpointDesc->bDescriptorType);
AppendTextBuffer("bEndpointAddress: 0x%02X",
EndpointDesc->bEndpointAddress);
if(gDoAnnotation)
{
if(USB_ENDPOINT_DIRECTION_OUT(EndpointDesc->bEndpointAddress))
{
AppendTextBuffer(" -> Direction: OUT - EndpointID: %d\r\n",
(EndpointDesc->bEndpointAddress & USB_ENDPOINT_ADDRESS_MASK));
}
else if(USB_ENDPOINT_DIRECTION_IN(EndpointDesc->bEndpointAddress))
{
AppendTextBuffer(" -> Direction: IN - EndpointID: %d\r\n",
(EndpointDesc->bEndpointAddress & USB_ENDPOINT_ADDRESS_MASK));
}
else
{
//@@TestCase A6.1
//@@ERROR
//@@Descriptor Field - bEndpointAddress
//@@An invalid endpoint addressl has been defined
AppendTextBuffer("\r\n*!*ERROR: This appears to be an invalid bEndpointAddress\r\n");
OOPS();
}
}
else {AppendTextBuffer("\r\n");}
AppendTextBuffer("bmAttributes: 0x%02X",
EndpointDesc->bmAttributes);
if(gDoAnnotation)
{
AppendTextBuffer(" -> ");
switch (epType)
{
case USB_ENDPOINT_TYPE_CONTROL:
AppendTextBuffer("Control Transfer Type\r\n");
if (EndpointDesc->bmAttributes & USB_ENDPOINT_TYPE_CONTROL_RESERVED_MASK)
{
AppendTextBuffer("\r\n*!*ERROR: Bits 7..2 are reserved and must be set to 0\r\n");
OOPS();
}
break;
case USB_ENDPOINT_TYPE_ISOCHRONOUS:
AppendTextBuffer("Isochronous Transfer Type, Synchronization Type = ");
switch (USB_ENDPOINT_TYPE_ISOCHRONOUS_SYNCHRONIZATION(EndpointDesc->bmAttributes))
{
case USB_ENDPOINT_TYPE_ISOCHRONOUS_SYNCHRONIZATION_NO_SYNCHRONIZATION:
AppendTextBuffer("No Synchronization");
break;
case USB_ENDPOINT_TYPE_ISOCHRONOUS_SYNCHRONIZATION_ASYNCHRONOUS:
AppendTextBuffer("Asynchronous");
break;
case USB_ENDPOINT_TYPE_ISOCHRONOUS_SYNCHRONIZATION_ADAPTIVE:
AppendTextBuffer("Adaptive");
break;
case USB_ENDPOINT_TYPE_ISOCHRONOUS_SYNCHRONIZATION_SYNCHRONOUS:
AppendTextBuffer("Synchronous");
break;
}
AppendTextBuffer(", Usage Type = ");
switch (USB_ENDPOINT_TYPE_ISOCHRONOUS_USAGE(EndpointDesc->bmAttributes))
{
case USB_ENDPOINT_TYPE_ISOCHRONOUS_USAGE_DATA_ENDOINT:
AppendTextBuffer("Data Endpoint\r\n");
break;
case USB_ENDPOINT_TYPE_ISOCHRONOUS_USAGE_FEEDBACK_ENDPOINT:
AppendTextBuffer("Feedback Endpoint\r\n");
break;
case USB_ENDPOINT_TYPE_ISOCHRONOUS_USAGE_IMPLICIT_FEEDBACK_DATA_ENDPOINT:
AppendTextBuffer("Implicit Feedback Data Endpoint\r\n");
break;
case USB_ENDPOINT_TYPE_ISOCHRONOUS_USAGE_RESERVED:
//@@TestCase A6.2
//@@ERROR
//@@Descriptor Field - bmAttributes
//@@A reserved bit has a value
AppendTextBuffer("\r\n*!*ERROR: This value is Reserved\r\n");
OOPS();
break;
}
if (EndpointDesc->bmAttributes & USB_ENDPOINT_TYPE_ISOCHRONOUS_RESERVED_MASK)
{
AppendTextBuffer("\r\n*!*ERROR: Bits 7..6 are reserved and must be set to 0\r\n");
OOPS();
}
break;
case USB_ENDPOINT_TYPE_BULK:
AppendTextBuffer("Bulk Transfer Type\r\n");
if (EndpointDesc->bmAttributes & USB_ENDPOINT_TYPE_BULK_RESERVED_MASK)
{
AppendTextBuffer("\r\n*!*ERROR: Bits 7..2 are reserved and must be set to 0\r\n");
OOPS();
}
break;
case USB_ENDPOINT_TYPE_INTERRUPT:
if (gDeviceSpeed != UsbSuperSpeed)
{
AppendTextBuffer("Interrupt Transfer Type\r\n");
if (EndpointDesc->bmAttributes & USB_20_ENDPOINT_TYPE_INTERRUPT_RESERVED_MASK)
{
AppendTextBuffer("\r\n*!*ERROR: Bits 7..2 are reserved and must be set to 0\r\n");
OOPS();
}
}
else
{
AppendTextBuffer("Interrupt Transfer Type, Usage Type = ");
switch (USB_30_ENDPOINT_TYPE_INTERRUPT_USAGE(EndpointDesc->bmAttributes))
{
case USB_30_ENDPOINT_TYPE_INTERRUPT_USAGE_PERIODIC:
AppendTextBuffer("Periodic\r\n");
break;
case USB_30_ENDPOINT_TYPE_INTERRUPT_USAGE_NOTIFICATION:
AppendTextBuffer("Notification\r\n");
break;
case USB_30_ENDPOINT_TYPE_INTERRUPT_USAGE_RESERVED10:
case USB_30_ENDPOINT_TYPE_INTERRUPT_USAGE_RESERVED11:
AppendTextBuffer("\r\n*!*ERROR: This value is Reserved\r\n");
OOPS();
break;
}
if (EndpointDesc->bmAttributes & USB_30_ENDPOINT_TYPE_INTERRUPT_RESERVED_MASK)
{
AppendTextBuffer("\r\n*!*ERROR: Bits 7..6 and 3..2 are reserved and must be set to 0\r\n");
OOPS();
}
if (EpCompDescAvail)
{
if (EpCompDesc == NULL)
{
AppendTextBuffer("\r\n*!*ERROR: Endpoint Companion Descriptor missing\r\n");
OOPS();
}
else if (EpCompDesc->bmAttributes.Isochronous.SspCompanion == 1 &&
SspIsochEpCompDesc == NULL)
{
AppendTextBuffer("\r\n*!*ERROR: SuperSpeedPlus Isoch Endpoint Companion Descriptor missing\r\n");
OOPS();
}
}
}
break;
}
}
else
{
AppendTextBuffer("\r\n");
}
//@@TestCase A6.3
//@@Priority 1
//@@Descriptor Field - bInterfaceNumber
//@@Question - Should we test to verify bInterfaceNumber is valid?
AppendTextBuffer("wMaxPacketSize: 0x%04X",
EndpointDesc->wMaxPacketSize);
if(gDoAnnotation)
{
switch (gDeviceSpeed)
{
case UsbSuperSpeed:
switch (epType)
{
case USB_ENDPOINT_TYPE_BULK:
if (EndpointDesc->wMaxPacketSize != USB_ENDPOINT_SUPERSPEED_BULK_MAX_PACKET_SIZE)
{
AppendTextBuffer("\r\n*!*ERROR: SuperSpeed Bulk endpoints must be %d bytes\r\n",
USB_ENDPOINT_SUPERSPEED_BULK_MAX_PACKET_SIZE);
}
else
{
AppendTextBuffer("\r\n");
}
break;
case USB_ENDPOINT_TYPE_CONTROL:
if (EndpointDesc->wMaxPacketSize != USB_ENDPOINT_SUPERSPEED_CONTROL_MAX_PACKET_SIZE)
{
AppendTextBuffer("\r\n*!*ERROR: SuperSpeed Control endpoints must be %d bytes\r\n",
USB_ENDPOINT_SUPERSPEED_CONTROL_MAX_PACKET_SIZE);
}
else
{
AppendTextBuffer("\r\n");
}
break;
case USB_ENDPOINT_TYPE_ISOCHRONOUS:
if (EpCompDesc != NULL)
{
if (EpCompDesc->bMaxBurst > 0)
{
if (EndpointDesc->wMaxPacketSize != USB_ENDPOINT_SUPERSPEED_ISO_MAX_PACKET_SIZE)
{
AppendTextBuffer("\r\n*!*ERROR: SuperSpeed isochronous endpoints must have wMaxPacketSize value of %d bytes\r\n",
USB_ENDPOINT_SUPERSPEED_ISO_MAX_PACKET_SIZE);
AppendTextBuffer(" when the SuperSpeed endpoint companion descriptor bMaxBurst value is greater than 0\r\n");
}
else
{
AppendTextBuffer("\r\n");
}
}
else if (EndpointDesc->wMaxPacketSize > USB_ENDPOINT_SUPERSPEED_ISO_MAX_PACKET_SIZE)
{
AppendTextBuffer("\r\n*!*ERROR: Invalid SuperSpeed isochronous maximum packet size\r\n");
}
else
{
AppendTextBuffer("\r\n");
}
}
else
{
AppendTextBuffer("\r\n");
}
break;
case USB_ENDPOINT_TYPE_INTERRUPT:
if (EpCompDesc != NULL)
{
if (EpCompDesc->bMaxBurst > 0)
{
if (EndpointDesc->wMaxPacketSize != USB_ENDPOINT_SUPERSPEED_INTERRUPT_MAX_PACKET_SIZE)
{
AppendTextBuffer("\r\n*!*ERROR: SuperSpeed interrupt endpoints must have wMaxPacketSize value of %d bytes\r\n",
USB_ENDPOINT_SUPERSPEED_INTERRUPT_MAX_PACKET_SIZE);
AppendTextBuffer(" when the SuperSpeed endpoint companion descriptor bMaxBurst value is greater than 0\r\n");
}
else
{
AppendTextBuffer("\r\n");
}
}
else if (EndpointDesc->wMaxPacketSize > USB_ENDPOINT_SUPERSPEED_INTERRUPT_MAX_PACKET_SIZE)
{
AppendTextBuffer("\r\n*!*ERROR: Invalid SuperSpeed interrupt maximum packet size\r\n");
}
else
{
AppendTextBuffer("\r\n");
}
}
else
{
AppendTextBuffer("\r\n");
}
break;
}
break;
case UsbHighSpeed:
hsMaxPacket = (PUSB_HIGH_SPEED_MAXPACKET)&EndpointDesc->wMaxPacketSize;
switch (epType)
{
case USB_ENDPOINT_TYPE_ISOCHRONOUS:
case USB_ENDPOINT_TYPE_INTERRUPT:
switch (hsMaxPacket->HSmux) {
case 0:
if ((hsMaxPacket->MaxPacket < 1) || (hsMaxPacket->MaxPacket >1024))
{
AppendTextBuffer("*!*ERROR: Invalid maximum packet size, should be between 1 and 1024\r\n");
}
break;
case 1:
if ((hsMaxPacket->MaxPacket < 513) || (hsMaxPacket->MaxPacket >1024))
{
AppendTextBuffer("*!*ERROR: Invalid maximum packet size, should be between 513 and 1024\r\n");
}
break;
case 2:
if ((hsMaxPacket->MaxPacket < 683) || (hsMaxPacket->MaxPacket >1024))
{
AppendTextBuffer("*!*ERROR: Invalid maximum packet size, should be between 683 and 1024\r\n");
}
break;
case 3:
AppendTextBuffer("*!*ERROR: Bits 12-11 set to Reserved value in wMaxPacketSize\r\n");
break;
}
AppendTextBuffer(" = %d transactions per microframe, 0x%02X max bytes\r\n", hsMaxPacket->HSmux + 1, hsMaxPacket->MaxPacket);
break;
case USB_ENDPOINT_TYPE_BULK:
case USB_ENDPOINT_TYPE_CONTROL:
AppendTextBuffer(" = 0x%02X max bytes\r\n", hsMaxPacket->MaxPacket);
break;
}
break;
case UsbFullSpeed:
// full speed
AppendTextBuffer(" = 0x%02X bytes\r\n",
EndpointDesc->wMaxPacketSize & 0x7FF);
break;
default:
// low or invalid speed
if (InterfaceClass == USB_DEVICE_CLASS_VIDEO)
{
AppendTextBuffer(" = Invalid bus speed for USB Video Class\r\n");
}
else
{
AppendTextBuffer("\r\n");
}
break;
}
}
else
{
AppendTextBuffer("\r\n");
}
if (EndpointDesc->wMaxPacketSize & 0xE000)
{
//@@TestCase A6.4
//@@Priority 1
//@@OTG Descriptor Field - wMaxPacketSize
//@@Attribute bits D7-2 reserved (reset to 0)
AppendTextBuffer("*!*ERROR: wMaxPacketSize bits 15-13 should be 0\r\n");
}
if (EndpointDesc->bLength == sizeof(USB_ENDPOINT_DESCRIPTOR))
{
//@@TestCase A6.5
//@@Priority 1
//@@Descriptor Field - bInterfaceNumber
//@@Question - Should we test to verify bInterfaceNumber is valid?
AppendTextBuffer("bInterval: 0x%02X\r\n",
EndpointDesc->bInterval);
}
else
{
PUSB_ENDPOINT_DESCRIPTOR2 endpointDesc2;
endpointDesc2 = (PUSB_ENDPOINT_DESCRIPTOR2)EndpointDesc;
AppendTextBuffer("wInterval: 0x%04X\r\n",
endpointDesc2->wInterval);
AppendTextBuffer("bSyncAddress: 0x%02X\r\n",
endpointDesc2->bSyncAddress);
}
if (EpCompDesc != NULL)
{
DisplayEndointCompanionDescriptor(EpCompDesc, SspIsochEpCompDesc, epType);
}
if (SspIsochEpCompDesc != NULL)
{
DisplaySuperSpeedPlusIsochEndpointCompanionDescriptor(SspIsochEpCompDesc);
}
}
/*****************************************************************************
DisplaySuperSpeedPlusIsochEndpointCompanionDescriptor()
*****************************************************************************/
VOID
DisplaySuperSpeedPlusIsochEndpointCompanionDescriptor(
_In_ PUSB_SUPERSPEEDPLUS_ISOCH_ENDPOINT_COMPANION_DESCRIPTOR SspIsochEpCompDesc
)
{
AppendTextBuffer("\r\n ===>SuperSpeedPlus Isochronous Endpoint Companion Descriptor<===\r\n");
AppendTextBuffer("bLength: 0x%02X\r\n",
SspIsochEpCompDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
SspIsochEpCompDesc->bDescriptorType);
AppendTextBuffer("wReserved: 0x%02X\r\n",
SspIsochEpCompDesc->wReserved);
if (gDoAnnotation)
{
if (SspIsochEpCompDesc->wReserved != 0)
{
AppendTextBuffer("*!*ERROR: field is reserved\r\n");
}
}
AppendTextBuffer("dwBytesPerInterval: 0x%04X\r\n",
SspIsochEpCompDesc->dwBytesPerInterval);
}
/*****************************************************************************
DisplayEndointCompanionDescriptor()
*****************************************************************************/
VOID
DisplayEndointCompanionDescriptor (
_In_ PUSB_SUPERSPEED_ENDPOINT_COMPANION_DESCRIPTOR EpCompDesc,
_In_opt_ PUSB_SUPERSPEEDPLUS_ISOCH_ENDPOINT_COMPANION_DESCRIPTOR SspIsochEpCompDesc,
_In_ UCHAR DescType
)
{
AppendTextBuffer("\r\n ===>SuperSpeed Endpoint Companion Descriptor<===\r\n");
AppendTextBuffer("bLength: 0x%02X\r\n",
EpCompDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
EpCompDesc->bDescriptorType);
AppendTextBuffer("bMaxBurst: 0x%02X\r\n",
EpCompDesc->bMaxBurst);
AppendTextBuffer("bmAttributes: 0x%02X",
EpCompDesc->bmAttributes.AsUchar);
if(gDoAnnotation)
{
switch (DescType)
{
case USB_ENDPOINT_TYPE_CONTROL:
case USB_ENDPOINT_TYPE_INTERRUPT:
if (EpCompDesc->bmAttributes.AsUchar != 0)
{
AppendTextBuffer("*!*ERROR: Control/Interrupt SuperSpeed endpoints do not support streams\r\n");
}
else
{
AppendTextBuffer("\r\n");
}
break;
case USB_ENDPOINT_TYPE_BULK:
if(EpCompDesc->bmAttributes.Bulk.MaxStreams == 0)
{
AppendTextBuffer("The bulk endpoint does not define streams (MaxStreams == 0)\r\n");
}
else
{
AppendTextBuffer(" = %d streams supported\r\n", 1 << EpCompDesc->bmAttributes.Bulk.MaxStreams);
}
if (EpCompDesc->bmAttributes.Bulk.Reserved1 != 0)
{
AppendTextBuffer("*!*ERROR: bmAttributes bits 7-5 should be 0\r\n");
}
break;
case USB_ENDPOINT_TYPE_ISOCHRONOUS:
if (EpCompDesc->bmAttributes.Isochronous.SspCompanion == 0)
{
if (EpCompDesc->bMaxBurst == 0 &&
EpCompDesc->bmAttributes.Isochronous.Mult != 0)
{
AppendTextBuffer("*!*ERROR: SuperSpeed isochronous endpoint multiplier value should be zero if bMaxBurst is zero\r\n");
}
else
{
AppendTextBuffer(" = %d maximum number of packets within a service interval\r\n",
(EpCompDesc->bmAttributes.Isochronous.Mult + 1)*(EpCompDesc->bMaxBurst + 1));
if (EpCompDesc->bmAttributes.Isochronous.Mult > USB_SUPERSPEED_ISOCHRONOUS_MAX_MULTIPLIER)
{
AppendTextBuffer("*!*ERROR: Maximum SuperSpeed isochronous endpoint multiplier value exceeded\r\n");
}
}
}
else
{
if (EpCompDesc->bMaxBurst != 0)
{
AppendTextBuffer(" = %d maximum number of packets within a service interval\r\n",
(SspIsochEpCompDesc->dwBytesPerInterval*USB_ENDPOINT_SUPERSPEED_ISO_MAX_PACKET_SIZE) /
EpCompDesc->bMaxBurst);
}
}
if (EpCompDesc->bmAttributes.Isochronous.Reserved2 != 0)
{
AppendTextBuffer("*!*ERROR: bmAttributes bits 7-2 should be 0\r\n");
}
else
{
AppendTextBuffer("\r\n");
}
break;
}
}
AppendTextBuffer("wBytesPerInterval: 0x%04X\r\n",
EpCompDesc->wBytesPerInterval);
if (EpCompDesc->bmAttributes.Isochronous.SspCompanion == 1 &&
EpCompDesc->wBytesPerInterval != 0x1)
{
AppendTextBuffer("*!*ERROR: SuperSpeed endpoint wBytesPerInterval value should be 1 if \
SuperSpeedPlus Isoch companion descriptor is present\r\n");
}
}
/*****************************************************************************
DisplayHidDescriptor()
*****************************************************************************/
VOID
DisplayHidDescriptor (
PUSB_HID_DESCRIPTOR HidDesc
)
{
UCHAR i = 0;
AppendTextBuffer("\r\n ===>HID Descriptor<===\r\n");
//length checked in DisplayConfigDesc()
AppendTextBuffer("bLength: 0x%02X\r\n",
HidDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
HidDesc->bDescriptorType);
AppendTextBuffer("bcdHID: 0x%04X\r\n",
HidDesc->bcdHID);
AppendTextBuffer("bCountryCode: 0x%02X\r\n",
HidDesc->bCountryCode);
AppendTextBuffer("bNumDescriptors: 0x%02X\r\n",
HidDesc->bNumDescriptors);
for (i=0; i<HidDesc->bNumDescriptors; i++)
{
if (HidDesc->OptionalDescriptors[i].bDescriptorType == 0x22) {
AppendTextBuffer("bDescriptorType: 0x%02X (Report Descriptor)\r\n",
HidDesc->OptionalDescriptors[i].bDescriptorType);
}
else {
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
HidDesc->OptionalDescriptors[i].bDescriptorType);
}
AppendTextBuffer("wDescriptorLength: 0x%04X\r\n",
HidDesc->OptionalDescriptors[i].wDescriptorLength);
}
}
/*****************************************************************************
DisplayOTGDescriptor()
*****************************************************************************/
VOID
DisplayOTGDescriptor (
PUSB_OTG_DESCRIPTOR OTGDesc
)
{
AppendTextBuffer("\r\n ===>OTG Descriptor<===\r\n");
//length checked in DisplayConfigDesc()
AppendTextBuffer("bLength: 0x%02X\r\n",
OTGDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
OTGDesc->bDescriptorType);
AppendTextBuffer("bmAttributes: 0x%02X",
OTGDesc->bmAttributes);
switch (OTGDesc->bmAttributes)
{
case 0:
break;
case 1:
if(gDoAnnotation)
{
AppendTextBuffer(" -> SRP support\r\n");
}
break;
case 2:
if(gDoAnnotation)
{
AppendTextBuffer(" -> HNP support\r\n");
}
break;
case 3:
if(gDoAnnotation)
{
AppendTextBuffer(" -> SRP and HNP support\r\n");
}
break;
default:
//@@TestCase A6.5
//@@Priority 1
//@@OTG Descriptor Field - bmAttributes
//@@Attribute bits D7-2 reserved (reset to 0)
AppendTextBuffer("*!*ERROR: bmAttributes bits 2-7 are reserved "\
"(should be 0)\r\n");
OOPS();
break;
}
}
/*****************************************************************************
InitializeGlobalFlags ()
Initialize the global device flags in UVCView.h
*****************************************************************************/
void
InitializePerDeviceSettings (
PUSBDEVICEINFO info
)
{
// Save base address for this current device's info (including Configuration descriptor)
CurrentUSBDeviceInfo = info;
// Initialize Configuration descriptor length
dwConfigLength = 0;
// Save # of bytes from start of Configuration descriptor
// (Update this in the descriptor parsing routines)
dwConfigIndex = 0;
// Flags used in dispvid.c to display default Frame descriptor for MJPEG,
// Uncompressed, Vendor and FrameBased Formats
g_chMJPEGFrameDefault = 0;
g_chUNCFrameDefault = 0;
g_chVendorFrameDefault = 0;
g_chFrameBasedFrameDefault = 0;
// Spec version of UVC device
g_chUVCversion = 0;
// Start and end address of the configuration descriptor and start of the string descriptors
g_pConfigDesc = NULL;
g_pStringDescs = NULL;
g_descEnd = NULL;
//
// The GetConfigDescriptor() function in enum.c does not always work
// If that fails, the Configuration descriptor will be NULL
// and we can only display the device descriptor
//
CurrentConfigDesc = NULL;
if (NULL != info)
{
if (NULL != info->ConfigDesc)
{
CurrentConfigDesc = (PUSB_CONFIGURATION_DESCRIPTOR)(info->ConfigDesc + 1);
// Save the LENGTH of the Config descriptor
// Note that IsIADDevice() saves the ADDRESS of the END of the Config desc
// Be aware of the difference
dwConfigLength = CurrentConfigDesc->wTotalLength;
}
}
return;
}
/*****************************************************************************
IsUVCDevice()
Return Spec version of UVC device
0x0 = Not a UVC device
0x10 = UVC 1.0
0x11 = UVC 1.1
*****************************************************************************/
UINT
IsUVCDevice (
PUSBDEVICEINFO info
)
{
PUSB_CONFIGURATION_DESCRIPTOR ConfigDesc = NULL;
PUSB_COMMON_DESCRIPTOR commonDesc = NULL;
PUCHAR descEnd = NULL;
UINT uUVCversion = 0;
//
// The GetConfigDescriptor() function in enum.c does not always work
// If that fails, the Configuration descriptor will be NULL
// and we can only display the device descriptor
//
if (NULL == info)
{
return 0;
}
if (NULL == info->ConfigDesc)
{
return 0;
}
ConfigDesc = (PUSB_CONFIGURATION_DESCRIPTOR)(info->ConfigDesc + 1);
if (NULL == ConfigDesc)
{
return 0;
}
// We've got a good Configuration Descriptor
commonDesc = (PUSB_COMMON_DESCRIPTOR)ConfigDesc;
descEnd = (PUCHAR)ConfigDesc + ConfigDesc->wTotalLength;
// walk through all the descriptors looking for the VIDEO_CONTROL_HEADER_UNIT
while ((PUCHAR)commonDesc + sizeof(USB_COMMON_DESCRIPTOR) < descEnd &&
(PUCHAR)commonDesc + commonDesc->bLength <= descEnd)
{
if ((commonDesc->bDescriptorType == CS_INTERFACE) &&
(commonDesc->bLength > sizeof(VIDEO_CONTROL_HEADER_UNIT)))
{
// Right type, size. Now check subtype
PVIDEO_CONTROL_HEADER_UNIT pCSVC = NULL;
pCSVC = (PVIDEO_CONTROL_HEADER_UNIT) commonDesc;
if (VC_HEADER == pCSVC->bDescriptorSubtype)
{
// found the Class-specific VC Interface Header descriptor
uUVCversion = pCSVC->bcdVideoSpec;
// Save the version to global
g_chUVCversion = uUVCversion;
// We're done
break;
}
}
commonDesc = (PUSB_COMMON_DESCRIPTOR) ((PUCHAR) commonDesc + commonDesc->bLength);
}
return (uUVCversion);
}
/*****************************************************************************
IsIADDevice()
*****************************************************************************/
UINT
IsIADDevice (
PUSBDEVICEINFO info
)
{
PUSB_CONFIGURATION_DESCRIPTOR ConfigDesc = NULL;
PUSB_COMMON_DESCRIPTOR commonDesc = NULL;
PUCHAR descEnd = NULL;
UINT uIADcount = 0;
//
// The GetConfigDescriptor() function in enum.c does not always work
// If that fails, the Configuration descriptor will be NULL
// and we can only display the device descriptor
//
if (NULL == info)
{
return 0;
}
if (NULL == info->ConfigDesc)
{
return 0;
}
ConfigDesc = (PUSB_CONFIGURATION_DESCRIPTOR)(info->ConfigDesc + 1);
if (NULL != ConfigDesc)
{
commonDesc = (PUSB_COMMON_DESCRIPTOR)ConfigDesc;
descEnd = (PUCHAR)ConfigDesc + ConfigDesc->wTotalLength;
}
// return total number of IAD descriptors in this device configuration
while ((PUCHAR)commonDesc + sizeof(USB_COMMON_DESCRIPTOR) < descEnd &&
(PUCHAR)commonDesc + commonDesc->bLength <= descEnd)
{
if (commonDesc->bDescriptorType == USB_IAD_DESCRIPTOR_TYPE)
{
uIADcount++;
}
commonDesc = (PUSB_COMMON_DESCRIPTOR) ((PUCHAR) commonDesc + commonDesc->bLength);
}
return (uIADcount);
}
/*****************************************************************************
DisplayIADDescriptor()
*****************************************************************************/
VOID
DisplayIADDescriptor (
PUSB_IAD_DESCRIPTOR IADDesc,
PSTRING_DESCRIPTOR_NODE StringDescs,
int nInterfaces,
DEVICE_POWER_STATE LatestDevicePowerState
)
{
AppendTextBuffer("\r\n ===>IAD Descriptor<===\r\n");
//length checked in DisplayConfigDesc()
AppendTextBuffer("bLength: 0x%02X\r\n",
IADDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
IADDesc->bDescriptorType);
AppendTextBuffer("bFirstInterface: 0x%02X\r\n",
IADDesc->bFirstInterface);
AppendTextBuffer("bInterfaceCount: 0x%02X\r\n",
IADDesc->bInterfaceCount);
if (IADDesc->bInterfaceCount == 1)
{
//@@TestCase A7.1
//@@Priority 1
//@@Standard IAD Descriptor Field - bInterfaceCount
//@@The number of interfaces must be greater than 1
AppendTextBuffer("*!*ERROR: bInterfaceCount must be greater than 1 \r\n");
OOPS();
}
if (nInterfaces < IADDesc->bFirstInterface + IADDesc->bInterfaceCount)
{
//@@TestCase A7.2
//@@Priority 1
//@@Standard IAD Descriptor Field - bInterfaceCount
//@@The total number of interfaces must be greater than or equal to
//@@ the highest linked interface number (base interface number plus count)
AppendTextBuffer("*!*ERROR: The total number of interfaces (%d) must be greater "\
"than or equal to\r\n",
nInterfaces);
AppendTextBuffer(" the highest linked interface number (base %d + "\
"count %d = %d)\r\n",
IADDesc->bFirstInterface, IADDesc->bInterfaceCount,
(IADDesc->bFirstInterface + IADDesc->bInterfaceCount));
OOPS();
}
AppendTextBuffer("bFunctionClass: 0x%02X",
IADDesc->bFunctionClass);
if (IADDesc->bFunctionClass == 0)
{
//@@TestCase A7.3
//@@Priority 1
//@@Standard IAD Descriptor Field - bFunctionClass
//@@"A value of zero is not allowed in this descriptor"
AppendTextBuffer("\r\n*!*ERROR: bFunctionClass contains an illegal value 0 \r\n");
OOPS();
}
switch (IADDesc->bFunctionClass)
{
case USB_DEVICE_CLASS_AUDIO:
if(gDoAnnotation)
{
AppendTextBuffer(" -> Audio Interface Class\r\n");
}
AppendTextBuffer("bFunctionSubClass: 0x%02X",
IADDesc->bFunctionSubClass);
if(gDoAnnotation)
{
switch (IADDesc->bFunctionSubClass)
{
case USB_AUDIO_SUBCLASS_AUDIOCONTROL:
AppendTextBuffer(" -> Audio Control Interface SubClass\r\n");
break;
case USB_AUDIO_SUBCLASS_AUDIOSTREAMING:
AppendTextBuffer(" -> Audio Streaming Interface SubClass\r\n");
break;
case USB_AUDIO_SUBCLASS_MIDISTREAMING:
AppendTextBuffer(" -> MIDI Streaming Interface SubClass\r\n");
break;
default:
//@@TestCase A7.4
//@@CAUTION
//@@Descriptor Field - bFunctionSubClass
//@@Invalid bFunctionSubClass
AppendTextBuffer("\r\n*!*CAUTION: This appears to be an invalid bFunctionSubClass\r\n");
OOPS();
break;
}
}
break;
case USB_DEVICE_CLASS_VIDEO:
if(gDoAnnotation)
{
AppendTextBuffer(" -> Video Interface Class\r\n");
}
AppendTextBuffer("bFunctionSubClass: 0x%02X",
IADDesc->bFunctionSubClass);
switch(IADDesc->bFunctionSubClass)
{
case SC_VIDEO_INTERFACE_COLLECTION:
if(gDoAnnotation)
{
AppendTextBuffer(" -> Video Interface Collection\r\n");
}
break;
default:
//@@TestCase A7.5
//@@CAUTION
//@@Descriptor Field - bFunctionSubClass
//@@Invalid bFunctionSubClass
AppendTextBuffer("\r\n*!*ERROR: This should be USB_VIDEO_SC_VIDEO_INTERFACE_COLLECTION %d\r\n",
SC_VIDEO_INTERFACE_COLLECTION);
OOPS();
break;
}
break;
case USB_DEVICE_CLASS_HUMAN_INTERFACE:
if(gDoAnnotation)
{
AppendTextBuffer(" -> HID Interface Class\r\n");
}
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_DEVICE_CLASS_HUB:
if(gDoAnnotation)
{
AppendTextBuffer(" -> HUB Interface Class\r\n");
}
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_DEVICE_CLASS_RESERVED:
//@@TestCase A7.6
//@@CAUTION
//@@Descriptor Field - bFunctionClass
//@@A reserved USB Device Interface Class has been defined
AppendTextBuffer("\r\n*!*CAUTION: %d is a Reserved USB Device Interface Class\r\n",
USB_DEVICE_CLASS_RESERVED);
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_DEVICE_CLASS_COMMUNICATIONS:
AppendTextBuffer(" -> This is Communications (CDC Control) USB Device Interface Class\r\n");
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_DEVICE_CLASS_MONITOR:
AppendTextBuffer(" -> This is a Monitor USB Device Interface Class*** (This may be obsolete)\r\n");
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_DEVICE_CLASS_PHYSICAL_INTERFACE:
AppendTextBuffer(" -> This is a Physical Interface USB Device Interface Class\r\n");
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_DEVICE_CLASS_POWER:
if(IADDesc->bFunctionSubClass == 1 && IADDesc->bFunctionProtocol == 1)
{
AppendTextBuffer(" -> This is an Image USB Device Interface Class\r\n");
}
else
{
AppendTextBuffer(" -> This is a Power USB Device Interface Class (This may be obsolete)\r\n");
}
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_DEVICE_CLASS_PRINTER:
AppendTextBuffer(" -> This is a Printer USB Device Interface Class\r\n");
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_DEVICE_CLASS_STORAGE:
AppendTextBuffer(" -> This is a Mass Storage USB Device Interface Class\r\n");
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_CDC_DATA_INTERFACE:
AppendTextBuffer(" -> This is a CDC Data USB Device Interface Class\r\n");
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_CHIP_SMART_CARD_INTERFACE:
AppendTextBuffer(" -> This is a Chip/Smart Card USB Device Interface Class\r\n");
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_CONTENT_SECURITY_INTERFACE:
AppendTextBuffer(" -> This is a Content Security USB Device Interface Class\r\n");
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_DIAGNOSTIC_DEVICE_INTERFACE:
if(IADDesc->bFunctionSubClass == 1 && IADDesc->bFunctionProtocol == 1)
{
AppendTextBuffer(" -> This is a Reprogrammable USB2 Compliance Diagnostic Device USB Device\r\n");
}
else
{
//@@TestCase A7.7
//@@CAUTION
//@@Descriptor Field - bFunctionClass
//@@Invalid Interface Class
AppendTextBuffer("\r\n*!*CAUTION: This appears to be an invalid Interface Class\r\n");
OOPS();
}
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_WIRELESS_CONTROLLER_INTERFACE:
if(IADDesc->bFunctionSubClass == 1 && IADDesc->bFunctionProtocol == 1)
{
AppendTextBuffer(" -> This is a Wireless RF Controller USB Device Interface Class with Bluetooth Programming Interface\r\n");
}
else
{
//@@TestCase A7.8
//@@CAUTION
//@@Descriptor Field - bFunctionClass
//@@Invalid Interface Class
AppendTextBuffer("\r\n*!*CAUTION: This appears to be an invalid Interface Class\r\n");
OOPS();
}
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
case USB_APPLICATION_SPECIFIC_INTERFACE:
AppendTextBuffer(" -> This is an Application Specific USB Device Interface Class\r\n");
switch(IADDesc->bFunctionSubClass)
{
case 1:
AppendTextBuffer(" -> This is a Device Firmware Application Specific USB Device Interface Class\r\n");
break;
case 2:
AppendTextBuffer(" -> This is an IrDA Bridge Application Specific USB Device Interface Class\r\n");
break;
case 3:
AppendTextBuffer(" -> This is a Test & Measurement Class (USBTMC) Application Specific USB Device Interface Class\r\n");
break;
default:
//@@TestCase A7.9
//@@CAUTION
//@@Descriptor Field - bFunctionClass
//@@Invalid Interface Class
AppendTextBuffer("\r\n*!*CAUTION: This appears to be an invalid Interface Class\r\n");
OOPS();
}
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
default:
if(gDoAnnotation)
{
AppendTextBuffer(" -> Interface Class Unknown to USBView\r\n");
}
AppendTextBuffer("bFunctionSubClass: 0x%02X\r\n",
IADDesc->bFunctionSubClass);
break;
}
AppendTextBuffer("bFunctionProtocol: 0x%02X",
IADDesc->bFunctionProtocol);
// check protocol for our class
if ((IADDesc->bFunctionClass == USB_DEVICE_CLASS_VIDEO))
{
// USB Video Class
if(IADDesc->bFunctionProtocol == PC_PROTOCOL_UNDEFINED)
{
// correct protocol for UVC
if(gDoAnnotation)
{
AppendTextBuffer(" -> PC_PROTOCOL_UNDEFINED protocol\r\n");
} else {
AppendTextBuffer("\r\n");
}
} else {
// incorrect protocol for UVC
//@@TestCase A7.10
//@@WARNING
//@@Descriptor Field - iInterface
//@@bFunctionProtocol must be set to PC_PROTOCOL_UNDEFINED
AppendTextBuffer("*!*WARNING: must be set to PC_PROTOCOL_UNDEFINED %d for this class\r\n",
PC_PROTOCOL_UNDEFINED);
OOPS();
}
} else {
AppendTextBuffer("\r\n");
}
AppendTextBuffer("iFunction: 0x%02X\r\n",
IADDesc->iFunction);
if(gDoAnnotation)
{
if (IADDesc->iFunction)
{
DisplayStringDescriptor(IADDesc->iFunction,
StringDescs,
LatestDevicePowerState);
}
}
}
/*****************************************************************************
GetConfigurationSize()
*****************************************************************************/
UINT
GetConfigurationSize (
PUSBDEVICEINFO info
)
{
PUSB_CONFIGURATION_DESCRIPTOR
ConfigDesc = (PUSB_CONFIGURATION_DESCRIPTOR)(info->ConfigDesc + 1);
PUSB_COMMON_DESCRIPTOR
commonDesc = (PUSB_COMMON_DESCRIPTOR)ConfigDesc;
PUCHAR
descEnd = (PUCHAR)ConfigDesc + ConfigDesc->wTotalLength;
UINT uCount = 0;
// return this device configuration's total sum of descriptor lengths
while ((PUCHAR)commonDesc + sizeof(USB_COMMON_DESCRIPTOR) < descEnd &&
(PUCHAR)commonDesc + commonDesc->bLength <= descEnd)
{
uCount += commonDesc->bLength;
commonDesc = (PUSB_COMMON_DESCRIPTOR) ((PUCHAR) commonDesc + commonDesc->bLength);
}
return (uCount);
}
/*****************************************************************************
GetInterfaceCount()
*****************************************************************************/
UINT
GetInterfaceCount (
PUSBDEVICEINFO info
)
{
// how do we handle composite devices?
PUSB_CONFIGURATION_DESCRIPTOR
ConfigDesc = (PUSB_CONFIGURATION_DESCRIPTOR)(info->ConfigDesc + 1);
PUSB_COMMON_DESCRIPTOR
commonDesc = (PUSB_COMMON_DESCRIPTOR)ConfigDesc;
PUCHAR
descEnd = (PUCHAR)ConfigDesc + ConfigDesc->wTotalLength;
UINT uCount = 0;
// return this device configuration's total number of interface descriptors
while ((PUCHAR)commonDesc + sizeof(USB_COMMON_DESCRIPTOR) < descEnd &&
(PUCHAR)commonDesc + commonDesc->bLength <= descEnd)
{
if (commonDesc->bDescriptorType == USB_INTERFACE_DESCRIPTOR_TYPE)
{
uCount++;
}
commonDesc = (PUSB_COMMON_DESCRIPTOR) ((PUCHAR) commonDesc + commonDesc->bLength);
}
return (uCount);
}
/*****************************************************************************
DisplayUSEnglishStringDescriptor()
*****************************************************************************/
VOID
DisplayUSEnglishStringDescriptor (
UCHAR Index,
PSTRING_DESCRIPTOR_NODE USStringDescs,
DEVICE_POWER_STATE LatestDevicePowerState
)
{
ULONG nBytes = 0;
BOOLEAN FoundMatchingString = FALSE;
CHAR pString[512];
//@@DisplayUSEnglishStringDescriptor - String Descriptor
while (USStringDescs)
{
if (USStringDescs->DescriptorIndex == Index)
{
if (USStringDescs->LanguageID != 0x0409)
continue;
FoundMatchingString = TRUE;
AppendTextBuffer("English product name: \"");
memset(pString, 0, 512);
nBytes = WideCharToMultiByte(
CP_ACP, // CodePage
WC_NO_BEST_FIT_CHARS,
USStringDescs->StringDescriptor->bString,
(USStringDescs->StringDescriptor->bLength - 2) / 2,
pString,
512,
NULL, // lpDefaultChar
NULL); // pUsedDefaultChar
if (nBytes)
AppendTextBuffer("%s\"\r\n", pString);
else
AppendTextBuffer("\"\r\n", pString);
return;
}
USStringDescs = USStringDescs->Next;
}
//@@TestCase A8.1
//@@WARNING
//@@Descriptor Field - string index
//@@No support for english
if (!FoundMatchingString)
{
if (LatestDevicePowerState == PowerDeviceD0)
{
AppendTextBuffer("*!*ERROR: No String Descriptor for index %d!\r\n", Index);
OOPS();
}
else
{
AppendTextBuffer("String Descriptor for index %d not available while device is in low power state.\r\n", Index);
}
}
else
{
AppendTextBuffer("*!*ERROR: The index selected does not support English(US)\r\n");
OOPS();
}
return;
}
/*****************************************************************************
DisplayStringDescriptor()
*****************************************************************************/
VOID
DisplayStringDescriptor (
UCHAR Index,
PSTRING_DESCRIPTOR_NODE StringDescs,
DEVICE_POWER_STATE LatestDevicePowerState
)
{
ULONG nBytes = 0;
BOOLEAN FoundMatchingString = FALSE;
PCHAR pStr = NULL;
CHAR pString[512];
//@@DisplayStringDescriptor - String Descriptor
while (StringDescs)
{
if (StringDescs->DescriptorIndex == Index)
{
FoundMatchingString = TRUE;
if(gDoAnnotation)
{
pStr= GetLangIDString(StringDescs->LanguageID);
if(pStr)
{
AppendTextBuffer(" %s \"",
pStr);
}
else
{
//@@TestCase A9.1
//@@WARNING
//@@Descriptor Field - string index
//@@The Language ID does not match any known languages supported by USB ORG
AppendTextBuffer("*!*WARNING: %d is an invalid Language ID\r\n",
Index);
OOPS();
}
}
else
{
AppendTextBuffer(" 0x%04X: \"", StringDescs->LanguageID);
}
memset(pString, 0, 512);
if (StringDescs->StringDescriptor->bLength > sizeof(USHORT))
{
nBytes = WideCharToMultiByte(
CP_ACP, // CodePage
WC_NO_BEST_FIT_CHARS,
StringDescs->StringDescriptor->bString,
(StringDescs->StringDescriptor->bLength - 2) / 2,
pString,
512,
NULL, // lpDefaultChar
NULL); // pUsedDefaultChar
if (nBytes)
{
AppendTextBuffer("%s\"\r\n", pString);
}
else
{
AppendTextBuffer("\"\r\n");
}
}
else
{
//
// This is NULL string which is invalid
//
AppendTextBuffer("\"\r\n");
}
}
StringDescs = StringDescs->Next;
}
if (!FoundMatchingString)
{
if (LatestDevicePowerState == PowerDeviceD0)
{
AppendTextBuffer("*!*ERROR: No String Descriptor for index %d!\r\n", Index);
OOPS();
}
else
{
AppendTextBuffer("String Descriptor for index %d not available while device is in low power state.\r\n", Index);
}
}
}
/*****************************************************************************
DisplayUnknownDescriptor()
*****************************************************************************/
VOID
DisplayUnknownDescriptor (
PUSB_COMMON_DESCRIPTOR CommonDesc
)
{
AppendTextBuffer("\r\n ===>Descriptor Hex Dump<===\r\n");
AppendTextBuffer("bLength: 0x%02X\r\n",
CommonDesc->bLength);
AppendTextBuffer("bDescriptorType: 0x%02X\r\n",
CommonDesc->bDescriptorType);
DisplayRemainingUnknownDescriptor((PUCHAR)CommonDesc, 0, CommonDesc->bLength);
}
VOID
DisplayRemainingUnknownDescriptor(
PUCHAR DescriptorData,
ULONG Start,
ULONG Stop
)
{
ULONG i;
for (i = Start; i < Stop; i++)
{
AppendTextBuffer("%02X ",
DescriptorData[i]);
if (i % 16 == 15)
{
AppendTextBuffer("\r\n");
}
}
if (i % 16 != 0)
{
AppendTextBuffer("\r\n");
}
}
/*****************************************************************************
GetVendorString()
idVendor - USB Vendor ID
Return Value - Vendor name string associated with idVendor, or NULL if
no vendor name string is found which is associated with idVendor.
*****************************************************************************/
PCHAR
GetVendorString (
USHORT idVendor
)
{
PUSBVENDORID vendorID = NULL;
if (idVendor == 0x0000)
{
return NULL;
}
vendorID = USBVendorIDs;
while (vendorID->usVendorID != 0x0000)
{
if (vendorID->usVendorID == idVendor)
{
break;
}
vendorID++;
}
return (vendorID->szVendor);
}
/*****************************************************************************
GetLangIDString()
idVendor - USB Vendor ID
Return Value - Vendor name string associated with idVendor, or NULL if
no vendor name string is found which is associated with idVendor.
*****************************************************************************/
PCHAR
GetLangIDString (
USHORT idLang
)
{
PUSBLANGID langID = NULL;
if (idLang != 0x0000)
{
langID = USBLangIDs;
while (langID->usLangID != 0x0000)
{
if (langID->usLangID == idLang)
{
return (langID->szLanguage);
}
langID++;
}
}
return NULL;
}
/*****************************************************************************
GetStringFromList()
PSTRINGLIST slList, - pointer to STRINGLIST used
ULONG ulNumElements, -
number of elements in that STRINGLIST calc before call with sizeof(slList) / sizeof(STRINGLIST),
ULONG or ULONGLONG (if H264_SUPPORT is defined)ulFlag - - flag to look for
PCHAR szDefault - string to return if no match
Return a string associated with a value from a stringtable.
example:
GetStringFromList(slPowerState,
sizeof(slPowerState) / sizeof(STRINGLIST),
pUPI->SystemState,
"Invalid Power State")
*****************************************************************************/
PCHAR
GetStringFromList(
PSTRINGLIST slList,
ULONG ulNumElements,
#ifdef H264_SUPPORT
ULONGLONG ulFlag,
#else
ULONG ulFlag,
#endif
_In_ PCHAR szDefault
)
{
// ulIndex is zero based, but ulNumElements is 1 based
// subtract 1 from ulNumElements so that are same base
#ifdef H264_SUPPORT
ULONGLONG ulIndex = 0;
#else
ULONG ulIndex = 0;
#endif
ulNumElements--;
for ( ; ulIndex <= ulNumElements; ulIndex++)
{
if (ulFlag == slList[ulIndex].ulFlag)
{
return (slList[ulIndex].pszString);
}
}
return szDefault;
}
|
Geronius/DeploymentFramework
|
src/Documentation/HelpNDoc/Templates/code/C-Defines/header.pas.h
|
<filename>src/Documentation/HelpNDoc/Templates/code/C-Defines/header.pas.h
var
aTopicList: THndTopicsInfoArray;
nCurTopic: integer;
sModuleName: string;
begin
HndGeneratorInfo.CurrentFile := ExtractFileName(HndGeneratorInfo.OutputFile);
sModuleName := ChangeFileExt(ExtractFileName(HndGeneratorInfo.OutputFile), '');
aTopicList := HndTopics.GetTopicListVisible(False);
printfln('/* Project: %s */', [HndProjects.GetProjectTitle()]);
println ('/* Generated by HelpNDoc - http://www.helpndoc.com */');
println ('');
printfln('#ifndef __%s_HEADER__', [sModuleName]);
printfln('#define __%s_HEADER__', [sModuleName]);
println ('');
for nCurTopic := 0 to length(aTopicList) - 1 do
begin
printfln('#define HELP_%s %d', [aTopicList[nCurTopic].HelpId, aTopicList[nCurTopic].HelpContext]);
end;
println ('');
println ('#endif');
end.
|
IwoZachary/MSiD
|
Sort3i4/Sort3i4/InsertSort.h
|
#pragma once
class InsertSort {
public:
InsertSort(int ammount, int volume);
~InsertSort();
void vSort();
void vShow();
private:
int* tab;
int length;
};
|
IwoZachary/MSiD
|
Sort3i4/Sort3i4/BubbleSort.h
|
#pragma once
class BubbleSort {
public:
BubbleSort(int ammount,int volume);
~BubbleSort();
void vShow();
void vSort();
private:
void vSwap(int i,int j);
int* tab;
int length;
};
|
IwoZachary/MSiD
|
Sort3i4/Sort3i4/Generator.h
|
<reponame>IwoZachary/MSiD
#pragma once
class Generator {
public:
Generator(int max);
void vGenerate(int* tab,int length);
private:
int max;
};
|
da-phil/libdw1000
|
inc/libdw1000Types.h
|
<reponame>da-phil/libdw1000
/*
* Driver for decaWave DW1000 802.15.4 UWB radio chip.
*
* Copyright (c) 2016 Bitcraze AB
* Converted to C from the Decawave DW1000 library for arduino.
* which is Copyright (c) 2015 by <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __LIBDW1000_TYPES_H__
#define __LIBDW1000_TYPES_H__
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include "dw1000.h"
struct dwOps_s;
struct dwDevice_s;
typedef union dwTime_u {
uint8_t raw[5];
uint64_t full;
struct {
uint32_t low32;
uint8_t high8;
} __attribute__((packed));
struct {
uint8_t low8;
uint32_t high32;
} __attribute__((packed));
} dwTime_t;
typedef void (*dwHandler_t)(struct dwDevice_s *dev);
/**
* DW device type. Contains the context of a dw1000 device and should be passed
* as first argument of most of the driver functions.
*/
typedef struct dwDevice_s {
struct dwOps_s *ops;
void *userdata;
/* State */
uint8_t sysctrl[LEN_SYS_CTRL];
uint8_t deviceMode;
uint8_t networkAndAddress[LEN_PANADR];
uint8_t syscfg[LEN_SYS_CFG];
uint8_t sysmask[LEN_SYS_MASK];
uint8_t chanctrl[LEN_CHAN_CTRL];
uint8_t sysstatus[LEN_SYS_STATUS];
uint8_t txfctrl[LEN_TX_FCTRL];
uint8_t extendedFrameLength;
uint8_t pacSize;
uint8_t pulseFrequency;
uint8_t dataRate;
uint8_t preambleLength;
uint8_t preambleCode;
uint8_t channel;
bool smartPower;
bool frameCheck;
bool permanentReceive;
bool wait4resp;
dwTime_t antennaDelay;
// Callback handles
dwHandler_t handleSent;
dwHandler_t handleReceived;
dwHandler_t handleReceiveTimeout;
dwHandler_t handleReceiveFailed;
// settings
uint32_t txPower;
bool forceTxPower;
} dwDevice_t;
typedef enum {dwSpiSpeedLow, dwSpiSpeedHigh} dwSpiSpeed_t;
typedef enum {dwClockAuto = 0x00, dwClockXti = 0x01, dwClockPll = 0x02} dwClock_t;
/**
* DW operation type. Constains function pointer to all hardware-dependent
* operation required to access the DW1000 device.
*/
typedef struct dwOps_s {
/**
* Function that activates the chip-select, sends header, read data and
* disable the chip-select.
*/
void (*spiRead)(dwDevice_t* dev, const void *header, size_t headerLength,
void* data, size_t dataLength);
/**
* Function that activates the chip-select, sends header, sends data and
* disable the chip-select.
*/
void (*spiWrite)(dwDevice_t* dev, const void *header, size_t headerLength,
const void* data, size_t dataLength);
/**
* Sets the SPI bus speed. Take as argument:
* - dwSpiSpeedLow: <= 4MHz
* - dwSpiSpeedHigh: <= 20MHz
*/
void (*spiSetSpeed)(dwDevice_t* dev, dwSpiSpeed_t speed);
/**
* Waits at least 'delay' miliseconds.
*/
void (*delayms)(dwDevice_t* dev, unsigned int delay);
/**
* Resets the DW1000 by pulling the reset pin low and then releasing it.
* This function is optional, if not set softreset via SPI will be used.
*/
void (*reset)(dwDevice_t *dev);
} dwOps_t;
#endif //__LIBDW1000_TYPES_H__
|
ErvinXie/VIPSS
|
vipss/src/surfacer/utils/Rn_vector.h
|
// -*-c++-*-
#ifndef IG_VECTOR_H
#define IG_VECTOR_H
// $Id: Rn_vector.h,v 1.2 2004/05/07 20:24:51 cmg Exp $
// CwMtx matrix and vector math library
// Copyright (C) 1999-2001 <NAME>
// Copyright (C) 2000 <NAME> (template conversion)
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
// 5/25/2002 - Made changes to default includes --Cindy Grimm
#include <WINSystemDefines.h>
#ifndef IG_MATRIX_H
#include <utils/Rn_Matrix.H>
#endif
namespace CwMtx
{
template < class T = double >
class CWTVector : public CWTMatrix<T>
{
public:
CWTVector(): CWTMatrix<T>() {};
CWTVector(unsigned crowInit): CWTMatrix<T>(crowInit, 1) {};
CWTVector(const CWTMatrix<T>& mat): CWTMatrix<T>(mat) {};
CWTVector(const CWTVector& vec): CWTMatrix<T>(vec) {};
// mapping into a matrix
CWTVector(const CWTMatrix<T>& , unsigned, unsigned, unsigned);
// mapping into a vector
CWTVector(const CWTVector& , unsigned, unsigned);
~CWTVector() {};
void MapInto(const CWTMatrix<T> &, unsigned, unsigned, unsigned);
void MapInto(const CWTVector &, unsigned, unsigned);
void Dimension(unsigned crowInit)
{
CWTMatrix<T>::Dimension(crowInit, 1);
}
T & operator [](unsigned irow)
{
return this->CWTMatrix<T>::operator[](irow)[0];
}
const T & operator [](unsigned irow) const
{
return this->CWTMatrix<T>::operator[](irow)[0];
}
CWTVector operator +(const CWTVector &) const;
CWTVector operator -(const CWTVector &) const;
CWTVector operator -() const;
CWTVector operator *(const T &) const;
// CWTVector*CWTVector, inner product
T operator *(const CWTVector &) const;
CWTVector operator /(const T &value) const
{
return (*this)*static_cast<const T &>(CWTUnity<T>()/value);
}
// not inherited
CWTVector & operator =(const CWTVector &vec);
CWTVector & operator +=(const CWTVector &vec);
CWTVector & operator -=(const CWTVector &vec);
CWTVector & operator *=(const T &value);
CWTVector & operator /=(const T &value);
// CWTVector norm
T operator !() const { return (*this).Norm(); };
void StoreAtRow(unsigned, const CWTVector &);
// returns vector norm (length)
T Norm() const;
// returns a unit vector with same direction as this
CWTVector Unit() const { return (*this)/Norm(); }
// make this a unit vector
void MakeUnit() { (*this) /= Norm(); }
};
template <class T, unsigned crow>
class CWTVec: public T
{
public:
CWTVec(): T(crow) {}
T & operator =(const T &mtx) { return T::operator=(mtx); }
};
// NOTE: There exists no unity vector for a general vector!
// Zero matrix.
//template <class T, unsigned crow>
//class CWTZero< CWTVec<CWTVector<T>, crow> >:
// public CWTVec<CWTVector<T>, crow>
//{
//public:
// CWTZero() { Fill(CWTZero<T>()); }
//};
//
// Constructors
//
// mapping into a vector
template < class T >
inline CWTVector<T>::CWTVector(const CWTVector<T> &vec,
unsigned irowStart,
unsigned irowEnd)
: CWTMatrix<T>(vec, irowStart, 0, irowEnd, 0)
{
}
// mapping into a matrix
template < class T >
inline CWTVector<T>::CWTVector(const CWTMatrix<T> &mat,
unsigned irowStart,
unsigned icolStart,
unsigned irowEnd)
:
CWTMatrix<T>(mat, irowStart, icolStart, irowEnd, icolStart)
{
}
//
// User Methods
//
template < class T >
inline void CWTVector<T>::MapInto(const CWTMatrix<T> &mat,
unsigned irowStart,
unsigned icol,
unsigned irowEnd)
{
CWTMatrix<T>::MapInto(mat, irowStart, icol, irowEnd, icol);
}
template < class T >
inline void CWTVector<T>::MapInto(const CWTVector &vec,
unsigned irowStart,
unsigned irowEnd)
{
CWTMatrix<T>::MapInto(vec, irowStart, 0, irowEnd, 0);
}
// not inherited
template < class T >
inline CWTVector<T> & CWTVector<T>::operator =(const CWTVector<T> &vec)
{
return static_cast<CWTVector &>(CWTMatrix<T>::operator=(vec));
}
template < class T >
inline CWTVector<T> & CWTVector<T>::operator +=(const CWTVector<T> &vec)
{
return static_cast<CWTVector &>(CWTMatrix<T>::operator+=(vec));
}
template < class T >
inline CWTVector<T> & CWTVector<T>::operator -=(const CWTVector<T> &vec)
{
return static_cast<CWTVector &>(CWTMatrix<T>::operator-=(vec));
}
template < class T >
inline CWTVector<T> & CWTVector<T>::operator *=(const T &value)
{
return static_cast<CWTVector &>(CWTMatrix<T>::operator*=(value));
}
template < class T >
inline CWTVector<T> & CWTVector<T>::operator /=(const T &value)
{
return (*this) *= static_cast<const T &>(CWTUnity<T>()/value);
}
template < class T >
inline void CWTVector<T>::StoreAtRow(unsigned irowStart,
const CWTVector<T> &vec)
{
CWTMatrix<T>::StoreAtPosition(irowStart, 0, vec);
}
template < class T >
CWTVector<T> CWTVector<T>::operator +(const CWTVector<T> &vec) const
{
return CWTVector<T>(*this) += vec;
}
template < class T >
CWTVector<T> CWTVector<T>::operator -(const CWTVector<T> &vec) const
{
return CWTVector<T>(*this) -= vec;
}
template < class T >
CWTVector<T> CWTVector<T>::operator -() const
{
return (*this)*static_cast<const T &>(CWTZero<T>() - CWTUnity<T>());
}
template < class T >
CWTVector<T> CWTVector<T>::operator *(const T &value) const
{
return CWTVector<T>(*this) *= value;
}
template < class T >
T CWTVector<T>::operator *(const CWTVector<T> &vec) const
{
T elemResult = 0;
for (unsigned irow = 0; irow < (*this).GetRows(); ++irow)
{
elemResult += (*this)[irow]*vec[irow];
}
return elemResult;
}
// length of vector
template < class T >
T CWTVector<T>::Norm() const
{
T elemResult = 0;
elemResult = (*this)*(*this);
return sqrt( elemResult );
}
//
// template functions designed work with the vector class.
//
template < class T >
inline CWTVector<T> operator *(const T &value, const CWTVector<T> &vec)
{
return vec*value;
}
// matrix*vector must yield a vector
template < class T >
CWTVector<T> operator *(const CWTMatrix<T> &mat, const CWTVector<T> &vec)
{
CWTVector<T> vecResult(vec.GetRows());
vecResult.StoreProduct(mat, vec);
return vecResult;
}
// norm computation as a function
template < class T >
inline T Length(const CWTVector<T> &vec)
{
return vec.Norm();
}
typedef CWTVector<double> RNVector;
}
#endif // IG_VECTOR_H
|
ErvinXie/VIPSS
|
vipss/src/surfacer/utils/LiveWire.h
|
#pragma once
#include <math.h>
#include <stack>
#include <queue>
#include <../src/utils/LiveWire/MyStack.h>
#include <../src/utils/LiveWire/MyQueue.h>
#include <../src/utils/LiveWire/MyList.h>
#include <../src/utils/LiveWire/MyCPoint.h>
#include <utils/Rn_Defs.H>
#include <utils/Mesh_Array.H>
#include <iostream>
#include <fstream>
class DistMap;
class MyImage;
class MyCPoint;
using namespace std;
// Object "LiveWire" is created by the GUI for each image opened by the user.
// A pointer to the corresponding image is passed along by the constructor (see below).
// "Segmentation" object allows efficient object segmentation via extraction of contours
// and regions based on two very basic algorithms for image analysis.
//
// Contour extraction is activated when a user enters a sequence of seeds on the
// desired object boundary (left mouse clicks). The GUI calls 'addSeed'
// function after each mouse click. The seeds are automatically connected via "live-wire"
// which is a short continuous "path" of pixels with high intensity contrast (note that
// high contrast normally occurs on object boundaries).
// A stack of points on a high-contrast path to the last entered seed is returned by
// 'findPath(MyCPoint p)' function called by the GUI each time a mouse moves
// to a new pixel 'p'. As a user clicks/adds a new seed (addSeed), the current live-wire is
// permanently added to the list of contour points (m_contour). As the mouse moves on, live-wire
// returns high-contrast paths to the newly added seed.
// A right mouse click completes the contour: GUI calls 'addLastSeed(p)' function
// that adds current live-wire to the contour and also closes a contour by
// computing a live-wire path between the contour's first seed and the last one (point p).
//
// Region extraction is activated by "growRegion(MyCPoint seed)" function called by the GUI when
// a user clicks on a point in the desired region while holding button 'r' down on the keyboard.
// This function returns a mask (2D binary array of values 0 and 1) for the region
// that was grown from the specified seed by adding neighboring points with small intensity
// difference. This mask (2D array) has the same size as the image.
class LiveWire
{
public:
LiveWire(void);
LiveWire(int rows, int cols, float** imgData); //Initializes a contour, links with an image
~LiveWire(void);
bool addSeed(R2Pt pt); //Called by the GUI when a user makes a left or right mouse click
R2Pt removeLastSeed();
bool addLastSeed(R2Pt pt); // Called by the GUI when a user makes a right mouse click
// This function 'loops' the contour
void clear(); // Clears all contour points and seeds (called when a user presses "DEL")
// Allocates, initializes, and returns a path (stack) of points from p to
// the last entereted seed, if any. GUI calls this function as a mouse moves
// to a new point p.
MyStack<MyCPoint>* findPath(MyCPoint p); // for internal calls
Array<R2Pt> findPath(R2Pt p); // for external calls
// This function is activated by a left (reset=false) or right (reset=true) mouse clicks
// when "r" key is down. It "grows" a region startind from the specified seed and returns
// it via a binary "mask" of the same size as the image. The region grows by adding
// to each pixel p already in the region all neighbors q such that |Ip-Iq|<T where
// T is some fixed threshold. If 'reset' flag is false than the algorithm should
// add a new region to existing set of masked pixels. Otherwise, the mask should
// be cleared-up (all values reset to zero) first.
void growRegion(char ** mask, R2Pt region_seed, bool reset = false);
// Returns all points in the contour. GUI draws these pixels in green color
// on the top of the image each time a display is refreshed
inline const MyList<MyCPoint> * getContour() {return &m_contour;}
// These allow for external access of contour since MyList and MyCPoint are made just for LiveWire class
inline const R2Pt getContourPt(int i) {return R2Pt(m_contour.retrieve(i).x, m_contour.retrieve(i).y);}
inline const int getContourSize() {return m_contour.getLength();}
inline const int getLastSeedPos() {return m_iLastSeedPos;}
//inline const R2Pt getLastSeed() { return R2Pt(m_seeds.retrieveLast().x,m_seeds.retrieveLast().y); }
// Returns the status of the contour (Is it closed already or not?)
inline bool isClosed() {return m_loop;}
// Just to check if there are any points in the contour already
//inline bool empty() {return m_contour.isEmpty();}
inline bool empty() {return m_seeds.isEmpty();}
private:
// Internal method that allows to "precompute" live-wire paths to the last seed
// from any image pixel. Is called inside "addSeed" for each new mouse click.
void computePaths(MyCPoint seed);
MyList<MyCPoint> m_contour; // stores permanent contour points
MyList<MyCPoint> m_seeds; // stored all enetered seed points
MyImage * m_im; // stores a pointer to image data
bool m_loop; // a closed contour flag
int m_iLastSeedPos; //posistion of the last seed in the contour
double ** m_penalty; // A 2D table of individual pixel penalties
// Low penalty m_penalty[x][y] means high image contrast
// at image pixel (x,y).
DistMap * m_dist_map; // Distance Map object for computing and
// storing "live-wire" paths to the last seed
// In particular, for each pixel/node p it should store
// a "parent" neighboring node connecting p to the last seed
// along a "good" (high contrast) path. m_dist_path should
// also store a distance from 'p' to the sees along that path
// (distance = accumulated sum of penalties of nodes along the path).
};
|
ErvinXie/VIPSS
|
vipss/src/readers.h
|
#ifndef READERS_H
#define READERS_H
#include<vector>
#include<string>
#include <fstream>
using namespace std;
//extern ofstream debug_output;
bool readOffFile(string filename, vector<double> &vertices, vector<unsigned int> &faces2vertices);
bool writeOffFile(string filename, const vector<double> &vertices, const vector<unsigned int> &faces2vertices);
bool writePLYFile(string filename, const vector<double> &vertices, const vector<unsigned int> &faces2vertices,
const vector<double> &vertices_normal, const vector<unsigned char> &vertices_color);
bool writePLYFile_VF(string filename, const vector<double> &vertices, const vector<unsigned int> &faces2vertices);
bool writePLYFile_VN(string filename, const vector<double> &vertices, const vector<double> &vertices_normal);
bool readPLYFile(string filename, vector<double> &vertices, vector<double> &vertices_normal);
bool readObjFile(string filename, vector<double> &vertices, vector<unsigned int> &faces2vertices,
vector<double> &vertices_normal);
bool readObjFile_Line(string filename, vector<double> &vertices, vector<unsigned int> &edges2vertices);
bool writeObjFile(string filename, const vector<double> &vertices, const vector<unsigned int> &faces2vertices);
bool writeObjFile_line(string filename, const vector<double> &vertices, const vector<unsigned int> &edge2vertices);
bool writeObjFile_vn(string filename, const vector<double> &vertices, const vector<double> &vn);
bool readSurfFile(string filename, vector<double> &vertices, vector<unsigned int> &faces2vertices,
vector<double> &vertices_field);
bool writeSurfFile(string filename, const vector<double> &vertices, const vector<unsigned int> &faces2vertices,
const vector<double> &vertices_field);
bool readCurfFile(string filename, vector<double> &vertices, vector<unsigned int> &edges2vertices,
vector<double> &vertices_field, vector<double> &vertices_tangent);
bool writeCurfFile(string filename, const vector<double> &vertices, const vector<unsigned int> &edges2vertices,
vector<double> &vertices_field, vector<double> &vertices_tangent);
bool readVolfFile(string filename, vector<double> &vertices, vector<unsigned int> &tets2vertices,
vector<double> &vertices_normal, vector<double> &vertices_field);
bool writeVolfFile(string filename, const vector<double> &vertices, const vector<unsigned int> &tets2vertices,
vector<double> &vertices_normal, vector<double> &vertices_field);
bool readContourEdgeTxtFile(string filename, vector<int> &edges2vertices);
bool writeContourEdgeTxtFile(string filename, const vector<unsigned int> &edges2vertices);
bool writeVecFile(string filename, const vector<int> &vec);
bool readVecFile(string filename, vector<int> &vec);
bool readVVecFile(string filename, vector<vector<int>> &vvec);
bool writeVVecFile(string filename, const vector<vector<int>> &vvec);
bool writeVecFile(string filename, const vector<float> &vec);
bool readVecFile(string filename, vector<float> &vec);
bool readVecFile(string filename, vector<double> &vec);
bool readVVecFile(string filename, vector<vector<double>> &vvec);
bool writeVVecFile(string filename, const vector<vector<double>> &vvec);
bool writeSufFile(string filename, const vector<double> &vertices, const vector<unsigned int> &faces2vertices,
const vector<int> &facesMat, const vector<int> &CtrEdges);
bool writeCtrGraphFile(string filename, const vector<float> &vertices, const vector<vector<int>> &edge2vertices,
const vector<vector<int>> &edgeMat, const vector<vector<float>> &planepara);
bool writeCurNetFile(string filename, const vector<double> &vertices, const vector<vector<int>> &edge2vertices,
const vector<vector<int>> &edgeMat, const vector<vector<double>> &planepara,
const vector<double> &verticesNor);
bool readXYZ(string filename, vector<double> &v);
bool readXYZnormal(string filename, vector<double> &v, vector<double> &vn);
bool writeXYZ(string filename, vector<double> &v);
bool writeXYZnormal(string filename, vector<double> &v, vector<double> &vn);
#endif // READERS_H
|
ErvinXie/VIPSS
|
vipss/src/surfacer/utils/BaryPoly.h
|
#ifndef BARY_POLY_H
#define BARY_POLY_H
#include <utils/Pm_MeshLite.H>
WINbool CalculateWeights( const PMeshLite &in_mesh, const R3Pt &in_pt, Array<double> &out_adWeights );
/// Sorts points by angle in tangent plane first
double LaplacianWeights( const R3Pt &in_pt, const R3Vec &in_vecNorm, const Array<R3Pt> &in_apt, Array<double> &out_adWeights );
/// Assumes points ordered
double LaplacianWeights( const R3Pt &in_pt, const Array<R3Pt> &in_apt, Array<double> &out_adWeights );
// Project onto plane by distributing angle error and keeping length
void ProjectPlane( const R3Pt &in_pt, const Array<R3Pt> &in_apt, Array<R2Pt> &out_apt2D );
/// Uses projection to sort
double FloaterWeights( const R3Pt &in_pt, const R3Vec &in_vecNorm, const Array<R3Pt> &in_apt, Array<double> &out_adWeights );
/// Assumes points are already sorted
double FloaterWeights( const R3Pt &in_pt, const Array<R3Pt> &in_apt, Array<double> &out_adWeights );
namespace Strain {
/// Find the symmetric matrix that aligns the two points
R3Matrix MatrixAlign( const Array<R3Pt> &in_apt1, const Array<R3Pt> &in_apt2 );
void DiscreteStrain( const Array<R3Pt> &in_apt1, const Array<R3Pt> &in_apt2, const R3Vec &in_vecNormPts2,
R3Matrix &out_matF, R3Matrix &out_matR1To2 );
/// Calculate the max,min strain of the deformation between two sets of points
pair<double, double> DiscreteStrain( const Array<R3Pt> &in_apt1, const Array<R3Pt> &in_apt2, const R3Vec &in_vecNormPts2,
R3Matrix &out_matF );
/// Same as above, but calculates the normal for you.
pair<double, double> DiscreteStrain( const Array<R3Pt> &in_apt1, const Array<R3Pt> &in_apt2, R3Matrix &out_matF );
/// Same as above, but uses vecDs and vecDt to determine normal
/// Returns the 2D tensor in out_matFij
pair<double, double> DiscreteStrain( const Array<R3Pt> &in_apt1, const Array<R3Pt> &in_apt2, const R3Vec &in_vecDs, const R3Vec &in_vecDt, R3Matrix &out_matFij );
/// Calculates strains based on fitting a surface to the points and using derivatives
/// Assumes points are sampled at same s,t values
/// Returns the 2D tensor in out_matFij
pair<double, double> AnalyticStrain( const Array<R3Pt> &in_apt1, const Array<R3Pt> &in_apt2 );
/// Works from the raw derivatives - assumes using the same parameter space, i.e., f(s,t) = f'(s,t) everywhere
/// Returns the 2D tensor in out_matFij
pair<double, double> AnalyticStrain( R2Matrix &out_matFij, const R3Vec &in_vecDs1, const R3Vec &in_vecDt1, const R3Vec &in_vecDs2, const R3Vec &in_vecDt2 );
void AnalyticStrain3D(const R3Vec &vSA, const R3Vec &vTA, const R3Vec &vSB, const R3Vec &vTB,
double &out_E1, double &out_E2, double &out_e1, double &out_e2);
}
#endif
|
ErvinXie/VIPSS
|
vipss/src/surfacer/ImplicitedSurfacing.h
|
#ifndef IMPLICITEDSURFACING_H
#define IMPLICITEDSURFACING_H
#include "Polygonizer.h"
#include "../readers.h"
class Surfacer {
public:
R3Pt s_ptMin, s_ptMax;
Array<R3Pt> s_aptSurface;
Array<R3Vec> s_avecSurface;
Array<R3Pt_i> s_afaceSurface;
vector<double> all_v;
vector<uint> all_fv;
R3Pt st;
double dSize;
int iBound;
Surfacer() {}
void CalSurfacingPara(vector<double> &Vs, int nvoxels);
double Surfacing_Implicit(vector<double> &Vs, int n_voxels, bool ischeckall,
double (*function)(const R3Pt &in_pt));
void WriteSurface(string fname);
void WriteSurface(vector<double> &v, vector<uint> &fv);
void WriteSurface(vector<double> **v, vector<uint> **fv);
void ClearBuffer();
void ClearSingleComponentBuffer();
private:
void GetCurSurface(vector<double> &v, vector<uint> &fv);
void InsertToCurSurface(vector<double> &v, vector<uint> &fv);
};
#endif // IMPLICITEDSURFACING_H
|
ErvinXie/VIPSS
|
vipss/src/surfacer/OctotreeSurfacer.h
|
//
// Created by 谢威宇 on 2020/5/12.
//
#ifndef VIPSS_OCTOTREESURFACER_H
#define VIPSS_OCTOTREESURFACER_H
#include <vector>
#include <functional>
#include <map>
#include <fstream>
#include <string>
using namespace std;
class OctotreeSurfacer;
class OctNode;
typedef OctNode *np;
class OctNode {
public:
OctNode(OctotreeSurfacer *surfacer, np father, const vector<int> &range);
OctotreeSurfacer *surfacer;
vector<int> range;
vector<vector<int> > point_seg, corner;
vector<vector<int> > mc_point;
bool containInput;
bool end;
bool split;
bool visited = false;
vector<int> corner_signs;
vector<int> face_signs;
vector<int> get_signs(bool prevent);
void update_surround_signs();
bool intersect();
void update_sign(np sonp);
np father;
vector<np> sons;
int get_son_idx(double ix, double iy, double iz);
np &get_son(double ix, double iy, double iz);
void addInputPoint(double ix, double iy, double iz);
int get_mc_idx();
void Surfacing(np caller);
tuple<int, int, int, int, int> get_face(int dir);
void debug(int d = 0);
};
class OctotreeSurfacer {
public:
const vector<double> &inputPoints;
vector<double> upper, lower, step;
ofstream out;
int n_voxels_1d;
function<double(tuple<double, double, double>)> implicitFunction;
vector<double> vertices;
vector<uint> triangleFaces;
vector<np> cubes;
np octroot;
map<tuple<int, int, int, int, int>, np> face_node[6];
np get_np_by_face(np c, int dir);
vector<np> get_neighbors(np c);
OctotreeSurfacer(const vector<double> &inputPoints,
const function<double(tuple<double, double, double>)> &implicitFunction, int n_voxels_1d,
string out_path = "PointCloud.xyz");
tuple<double, double, double> idx_to_coord(double x, double y, double z);
tuple<double, double, double> idx_to_coord(tuple<double, double, double> idx);
map<tuple<int, int, int>, double> mem;
double get_function_value(tuple<int, int, int>);
void Surfacing();
void polygonize();
map<vector<int>, int> interpolant_point;
int get_interpolant_point(vector<int> a, vector<int> b);
};
#endif //VIPSS_OCTOTREESURFACER_H
|
ckuehnel/LoRa
|
radino32_sx1272.h
|
<reponame>ckuehnel/LoRa
/*
* THE FOLLOWING FIRMWARE IS PROVIDED: (1) "AS IS" WITH NO WARRANTY; AND
* (2)TO ENABLE ACCESS TO CODING INFORMATION TO GUIDE AND FACILITATE CUSTOMER.
* CONSEQUENTLY, SEMTECH SHALL NOT BE HELD LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE CONTENT
* OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING INFORMATION
* CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* Copyright (C) SEMTECH S.A.
*
* MODIFIED BY IN-CIRCUIT GMBH
* SX1272 radio-Chip on In-Circuit radino32 SX1272 modules
* for more information: www.in-circuit.de or www.radino.cc
*/
#ifndef __RADINO32_SX1272_H__
#define __RADINO32_SX1272_H__
#ifndef __GNUC__
#define inline
#endif
#include <Arduino.h>
#include "SPI.h"
#define GET_TICK_COUNT( ) ( millis() )
/*!
* SPI DEFINES
*/
//#define PIN_SPI_CLK
#define SPI_INTERFACE SPI2
#define SPI_CLK RCC_APB1Periph_SPI2
#define SCK_PIN 34
#define SPI_PIN_SCK_PORT GPIOB
#define SPI_PIN_SCK_PORT_CLK RCC_AHBPeriph_GPIOB
#define SPI_PIN_SCK GPIO_Pin_13
#define SPI_SCK_AF_PIN GPIO_PinSource13
#define MISO_PIN 35
#define SPI_PIN_MISO_PORT GPIOB
#define SPI_PIN_MISO_PORT_CLK RCC_AHBPeriph_GPIOB
#define SPI_PIN_MISO GPIO_Pin_14
#define SPI_MISO_AF_PIN GPIO_PinSource14
#define MOSI_PIN 36
#define SPI_PIN_MOSI_PORT GPIOB
#define SPI_PIN_MOSI_PORT_CLK RCC_AHBPeriph_GPIOB
#define SPI_PIN_MOSI GPIO_Pin_15
#define SPI_MOSI_AF_PIN GPIO_PinSource15
/*!
* SX1272 RESET I/O definitions
*/
#define PIN_RESET 28
#define RESET_PIN PIN_RESET
/*!
* SX1272 SPI NSS I/O definitions
*/
#define PIN_SPI_NSS 29
#define SS_PIN PIN_SPI_NSS
/*!
* SX1272 DIO pins I/O definitions
*/
#define PIN_DIO0 31
#define PIN_DIO1 33
#define PIN_DIO2 30
#define PIN_DIO3 32
// NOTE: all functions that control DIO4/DIO5/RXTX have no effect, if DIO4_DUMMY/DIO5_DUMMY/RXTX_DUMMY set to 1
// these functions will than always return 0.
// Set to 0 to activate usage of PIN_DIO4 / PIN_DIO5 PIN_RXTX.
#define USE_DIO4_DUMMY 1 // defined for dummy (set 0 for using PIN_DIO4)
#define USE_DIO5_DUMMY 1 // defined for dummy (set 0 for using PIN_DIO5)
#define USE_RXTX_DUMMY 1 // defined for dummy (set 0 for using PIN_RXTX)
// NOTE: not connect on radino32 SX1272, using 0xFF as dummy for initalisation.
#define PIN_DIO4 0xFF
#define PIN_DIO5 0xFF
#define PIN_RXTX 0xFF
/*!
* SX1272 LoRa General parameters definition
*/
typedef struct sLoRaSettings
{
uint32_t RFFrequency;
int8_t Power;
uint8_t SignalBw; // LORA [0: 125 kHz, 1: 250 kHz, 2: 500 kHz, 3: Reserved]
uint8_t SpreadingFactor; // LORA [6: 64, 7: 128, 8: 256, 9: 512, 10: 1024, 11: 2048, 12: 4096 chips]
uint8_t ErrorCoding; // LORA [1: 4/5, 2: 4/6, 3: 4/7, 4: 4/8]
bool CrcOn; // [0: OFF, 1: ON]
bool ImplicitHeaderOn; // [0: OFF, 1: ON]
bool RxSingleOn; // [0: Continuous, 1 Single]
bool FreqHopOn; // [0: OFF, 1: ON]
uint8_t HopPeriod; // Hops every frequency hopping period symbols
uint32_t TxPacketTimeout;
uint32_t RxPacketTimeout;
uint8_t PayloadLength;
}tLoRaSettings;
/*!
* RF packet definition
*/
#define RF_BUFFER_SIZE_MAX 256
#define RF_BUFFER_SIZE 256
/*!
* RF state machine
*/
//LoRa
typedef enum
{
RFLR_STATE_IDLE,
RFLR_STATE_RX_INIT,
RFLR_STATE_RX_RUNNING,
RFLR_STATE_RX_DONE,
RFLR_STATE_RX_TIMEOUT,
RFLR_STATE_TX_INIT,
RFLR_STATE_TX_RUNNING,
RFLR_STATE_TX_DONE,
RFLR_STATE_TX_TIMEOUT,
RFLR_STATE_CAD_INIT,
RFLR_STATE_CAD_RUNNING,
}tRFLRStates;
/*!
* Functions return codes definition
*/
typedef enum
{
SX_OK,
SX_ERROR,
SX_BUSY,
SX_EMPTY,
SX_DONE,
SX_TIMEOUT,
SX_UNSUPPORTED,
SX_WAIT,
SX_CLOSE,
SX_YES,
SX_NO,
}tReturnCodes;
//extern volatile uint32_t TickCounter;
/*!
* SX1272 definitions
*/
#define XTAL_FREQ 32000000
#define FREQ_STEP 61.03515625
/*!
* SX1272 Internal registers Address
*/
#define REG_FIFO 0x00
// Common settings
#define REG_OPMODE 0x01
#define REG_BITRATEMSB 0x02
#define REG_BITRATELSB 0x03
#define REG_FDEVMSB 0x04
#define REG_FDEVLSB 0x05
#define REG_FRFMSB 0x06
#define REG_FRFMID 0x07
#define REG_FRFLSB 0x08
// Tx settings
#define REG_PACONFIG 0x09
#define REG_PARAMP 0x0A
#define REG_OCP 0x0B
// Rx settings
#define REG_LNA 0x0C
#define REG_RXCONFIG 0x0D
#define REG_RSSICONFIG 0x0E
#define REG_RSSICOLLISION 0x0F
#define REG_RSSITHRESH 0x10
#define REG_RSSIVALUE 0x11
#define REG_RXBW 0x12
#define REG_AFCBW 0x13
#define REG_OOKPEAK 0x14
#define REG_OOKFIX 0x15
#define REG_OOKAVG 0x16
#define REG_RES17 0x17
#define REG_RES18 0x18
#define REG_RES19 0x19
#define REG_AFCFEI 0x1A
#define REG_AFCMSB 0x1B
#define REG_AFCLSB 0x1C
#define REG_FEIMSB 0x1D
#define REG_FEILSB 0x1E
#define REG_PREAMBLEDETECT 0x1F
#define REG_RXTIMEOUT1 0x20
#define REG_RXTIMEOUT2 0x21
#define REG_RXTIMEOUT3 0x22
#define REG_RXDELAY 0x23
// Oscillator settings
#define REG_OSC 0x24
// Packet handler settings
#define REG_PREAMBLEMSB 0x25
#define REG_PREAMBLELSB 0x26
#define REG_SYNCCONFIG 0x27
#define REG_SYNCVALUE1 0x28
#define REG_SYNCVALUE2 0x29
#define REG_SYNCVALUE3 0x2A
#define REG_SYNCVALUE4 0x2B
#define REG_SYNCVALUE5 0x2C
#define REG_SYNCVALUE6 0x2D
#define REG_SYNCVALUE7 0x2E
#define REG_SYNCVALUE8 0x2F
#define REG_PACKETCONFIG1 0x30
#define REG_PACKETCONFIG2 0x31
#define REG_PAYLOADLENGTH 0x32
#define REG_NODEADRS 0x33
#define REG_BROADCASTADRS 0x34
#define REG_FIFOTHRESH 0x35
// SM settings
#define REG_SEQCONFIG1 0x36
#define REG_SEQCONFIG2 0x37
#define REG_TIMERRESOL 0x38
#define REG_TIMER1COEF 0x39
#define REG_TIMER2COEF 0x3A
// Service settings
#define REG_IMAGECAL 0x3B
#define REG_TEMP 0x3C
#define REG_LOWBAT 0x3D
// Status
#define REG_IRQFLAGS1 0x3E
#define REG_IRQFLAGS2 0x3F
// I/O settings
#define REG_DIOMAPPING1 0x40
#define REG_DIOMAPPING2 0x41
// Version
#define REG_VERSION 0x42
// Additional settings
#define REG_AGCREF 0x43
#define REG_AGCTHRESH1 0x44
#define REG_AGCTHRESH2 0x45
#define REG_AGCTHRESH3 0x46
#define REG_PLLHOP 0x4B
#define REG_TCXO 0x58
#define REG_PADAC 0x5A
#define REG_PLL 0x5C
#define REG_PLLLOWPN 0x5E
#define REG_FORMERTEMP 0x6C
#define REG_BITRATEFRAC 0x70
/*!
* SX1272 Internal registers Address
*/
#define REG_LR_FIFO 0x00
// Common settings
#define REG_LR_OPMODE 0x01
#define REG_LR_FRFMSB 0x06
#define REG_LR_FRFMID 0x07
#define REG_LR_FRFLSB 0x08
// Tx settings
#define REG_LR_PACONFIG 0x09
#define REG_LR_PARAMP 0x0A
#define REG_LR_OCP 0x0B
// Rx settings
#define REG_LR_LNA 0x0C
// LoRa registers
#define REG_LR_FIFOADDRPTR 0x0D
#define REG_LR_FIFOTXBASEADDR 0x0E
#define REG_LR_FIFORXBASEADDR 0x0F
#define REG_LR_FIFORXCURRENTADDR 0x10
#define REG_LR_IRQFLAGSMASK 0x11
#define REG_LR_IRQFLAGS 0x12
#define REG_LR_NBRXBYTES 0x13
#define REG_LR_RXHEADERCNTVALUEMSB 0x14
#define REG_LR_RXHEADERCNTVALUELSB 0x15
#define REG_LR_RXPACKETCNTVALUEMSB 0x16
#define REG_LR_RXPACKETCNTVALUELSB 0x17
#define REG_LR_MODEMSTAT 0x18
#define REG_LR_PKTSNRVALUE 0x19
#define REG_LR_PKTRSSIVALUE 0x1A
#define REG_LR_RSSIVALUE 0x1B
#define REG_LR_HOPCHANNEL 0x1C
#define REG_LR_MODEMCONFIG1 0x1D
#define REG_LR_MODEMCONFIG2 0x1E
#define REG_LR_SYMBTIMEOUTLSB 0x1F
#define REG_LR_PREAMBLEMSB 0x20
#define REG_LR_PREAMBLELSB 0x21
#define REG_LR_PAYLOADLENGTH 0x22
#define REG_LR_PAYLOADMAXLENGTH 0x23
#define REG_LR_HOPPERIOD 0x24
#define REG_LR_FIFORXBYTEADDR 0x25
#define REG_LR_FEIMSB 0x28
#define REG_LR_FEIMIB 0x29
#define REG_LR_FEILSB 0x2A
#define REG_LR_LORADETECTOPTIMIZE 0x31
#define REG_LR_INVERTIQ 0x33
#define REG_LR_DETECTIONTHRESHOLD 0x37
// end of documented register in datasheet
// I/O settings
#define REG_LR_DIOMAPPING1 0x40
#define REG_LR_DIOMAPPING2 0x41
// Version
#define REG_LR_VERSION 0x42
// Additional settings
#define REG_LR_AGCREF 0x43
#define REG_LR_AGCTHRESH1 0x44
#define REG_LR_AGCTHRESH2 0x45
#define REG_LR_AGCTHRESH3 0x46
#define REG_LR_PLLHOP 0x4B
#define REG_LR_TCXO 0x58
#define REG_LR_PADAC 0x5A
#define REG_LR_PLL 0x5C
#define REG_LR_PLLLOWPN 0x5E
#define REG_LR_FORMERTEMP 0x6C
/*!
* SX1272 LoRa bit control definition
*/
/*!
* RegFifo
*/
/*!
* RegOpMode
*/
#define RFLR_OPMODE_LONGRANGEMODE_MASK 0x7F
#define RFLR_OPMODE_LONGRANGEMODE_OFF 0x00 // Default
#define RFLR_OPMODE_LONGRANGEMODE_ON 0x80
#define RFLR_OPMODE_ACCESSSHAREDREG_MASK 0xBF
#define RFLR_OPMODE_ACCESSSHAREDREG_ENABLE 0x40
#define RFLR_OPMODE_ACCESSSHAREDREG_DISABLE 0x00 // Default
#define RFLR_OPMODE_MASK 0xF8
#define RFLR_OPMODE_SLEEP 0x00
#define RFLR_OPMODE_STANDBY 0x01 // Default
#define RFLR_OPMODE_SYNTHESIZER_TX 0x02
#define RFLR_OPMODE_TRANSMITTER 0x03
#define RFLR_OPMODE_SYNTHESIZER_RX 0x04
#define RFLR_OPMODE_RECEIVER 0x05
// LoRa specific modes
#define RFLR_OPMODE_RECEIVER_SINGLE 0x06
#define RFLR_OPMODE_CAD 0x07
/*!
* RegFrf (MHz)
*/
#define RFLR_FRFMSB_863_MHZ 0xD7
#define RFLR_FRFMID_863_MHZ 0xC0
#define RFLR_FRFLSB_863_MHZ 0x00
#define RFLR_FRFMSB_864_MHZ 0xD8
#define RFLR_FRFMID_864_MHZ 0x00
#define RFLR_FRFLSB_864_MHZ 0x00
#define RFLR_FRFMSB_865_MHZ 0xD8
#define RFLR_FRFMID_865_MHZ 0x40
#define RFLR_FRFLSB_865_MHZ 0x00
#define RFLR_FRFMSB_866_MHZ 0xD8
#define RFLR_FRFMID_866_MHZ 0x80
#define RFLR_FRFLSB_866_MHZ 0x00
#define RFLR_FRFMSB_867_MHZ 0xD8
#define RFLR_FRFMID_867_MHZ 0xC0
#define RFLR_FRFLSB_867_MHZ 0x00
#define RFLR_FRFMSB_868_MHZ 0xD9
#define RFLR_FRFMID_868_MHZ 0x00
#define RFLR_FRFLSB_868_MHZ 0x00
#define RFLR_FRFMSB_869_MHZ 0xD9
#define RFLR_FRFMID_869_MHZ 0x40
#define RFLR_FRFLSB_869_MHZ 0x00
#define RFLR_FRFMSB_870_MHZ 0xD9
#define RFLR_FRFMID_870_MHZ 0x80
#define RFLR_FRFLSB_870_MHZ 0x00
#define RFLR_FRFMSB_902_MHZ 0xE1
#define RFLR_FRFMID_902_MHZ 0x80
#define RFLR_FRFLSB_902_MHZ 0x00
#define RFLR_FRFMSB_903_MHZ 0xE1
#define RFLR_FRFMID_903_MHZ 0xC0
#define RFLR_FRFLSB_903_MHZ 0x00
#define RFLR_FRFMSB_904_MHZ 0xE2
#define RFLR_FRFMID_904_MHZ 0x00
#define RFLR_FRFLSB_904_MHZ 0x00
#define RFLR_FRFMSB_905_MHZ 0xE2
#define RFLR_FRFMID_905_MHZ 0x40
#define RFLR_FRFLSB_905_MHZ 0x00
#define RFLR_FRFMSB_906_MHZ 0xE2
#define RFLR_FRFMID_906_MHZ 0x80
#define RFLR_FRFLSB_906_MHZ 0x00
#define RFLR_FRFMSB_907_MHZ 0xE2
#define RFLR_FRFMID_907_MHZ 0xC0
#define RFLR_FRFLSB_907_MHZ 0x00
#define RFLR_FRFMSB_908_MHZ 0xE3
#define RFLR_FRFMID_908_MHZ 0x00
#define RFLR_FRFLSB_908_MHZ 0x00
#define RFLR_FRFMSB_909_MHZ 0xE3
#define RFLR_FRFMID_909_MHZ 0x40
#define RFLR_FRFLSB_909_MHZ 0x00
#define RFLR_FRFMSB_910_MHZ 0xE3
#define RFLR_FRFMID_910_MHZ 0x80
#define RFLR_FRFLSB_910_MHZ 0x00
#define RFLR_FRFMSB_911_MHZ 0xE3
#define RFLR_FRFMID_911_MHZ 0xC0
#define RFLR_FRFLSB_911_MHZ 0x00
#define RFLR_FRFMSB_912_MHZ 0xE4
#define RFLR_FRFMID_912_MHZ 0x00
#define RFLR_FRFLSB_912_MHZ 0x00
#define RFLR_FRFMSB_913_MHZ 0xE4
#define RFLR_FRFMID_913_MHZ 0x40
#define RFLR_FRFLSB_913_MHZ 0x00
#define RFLR_FRFMSB_914_MHZ 0xE4
#define RFLR_FRFMID_914_MHZ 0x80
#define RFLR_FRFLSB_914_MHZ 0x00
#define RFLR_FRFMSB_915_MHZ 0xE4 // Default
#define RFLR_FRFMID_915_MHZ 0xC0 // Default
#define RFLR_FRFLSB_915_MHZ 0x00 // Default
#define RFLR_FRFMSB_916_MHZ 0xE5
#define RFLR_FRFMID_916_MHZ 0x00
#define RFLR_FRFLSB_916_MHZ 0x00
#define RFLR_FRFMSB_917_MHZ 0xE5
#define RFLR_FRFMID_917_MHZ 0x40
#define RFLR_FRFLSB_917_MHZ 0x00
#define RFLR_FRFMSB_918_MHZ 0xE5
#define RFLR_FRFMID_918_MHZ 0x80
#define RFLR_FRFLSB_918_MHZ 0x00
#define RFLR_FRFMSB_919_MHZ 0xE5
#define RFLR_FRFMID_919_MHZ 0xC0
#define RFLR_FRFLSB_919_MHZ 0x00
#define RFLR_FRFMSB_920_MHZ 0xE6
#define RFLR_FRFMID_920_MHZ 0x00
#define RFLR_FRFLSB_920_MHZ 0x00
#define RFLR_FRFMSB_921_MHZ 0xE6
#define RFLR_FRFMID_921_MHZ 0x40
#define RFLR_FRFLSB_921_MHZ 0x00
#define RFLR_FRFMSB_922_MHZ 0xE6
#define RFLR_FRFMID_922_MHZ 0x80
#define RFLR_FRFLSB_922_MHZ 0x00
#define RFLR_FRFMSB_923_MHZ 0xE6
#define RFLR_FRFMID_923_MHZ 0xC0
#define RFLR_FRFLSB_923_MHZ 0x00
#define RFLR_FRFMSB_924_MHZ 0xE7
#define RFLR_FRFMID_924_MHZ 0x00
#define RFLR_FRFLSB_924_MHZ 0x00
#define RFLR_FRFMSB_925_MHZ 0xE7
#define RFLR_FRFMID_925_MHZ 0x40
#define RFLR_FRFLSB_925_MHZ 0x00
#define RFLR_FRFMSB_926_MHZ 0xE7
#define RFLR_FRFMID_926_MHZ 0x80
#define RFLR_FRFLSB_926_MHZ 0x00
#define RFLR_FRFMSB_927_MHZ 0xE7
#define RFLR_FRFMID_927_MHZ 0xC0
#define RFLR_FRFLSB_927_MHZ 0x00
#define RFLR_FRFMSB_928_MHZ 0xE8
#define RFLR_FRFMID_928_MHZ 0x00
#define RFLR_FRFLSB_928_MHZ 0x00
/*!
* RegPaConfig
*/
#define RFLR_PACONFIG_PASELECT_MASK 0x7F
#define RFLR_PACONFIG_PASELECT_PABOOST 0x80
#define RFLR_PACONFIG_PASELECT_RFO 0x00 // Default
#define RFLR_PACONFIG_OUTPUTPOWER_MASK 0xF0
/*!
* RegPaRamp
*/
#define RFLR_PARAMP_LOWPNTXPLL_MASK 0xE0
#define RFLR_PARAMP_LOWPNTXPLL_OFF 0x10 // Default
#define RFLR_PARAMP_LOWPNTXPLL_ON 0x00
#define RFLR_PARAMP_MASK 0xF0
#define RFLR_PARAMP_3400_US 0x00
#define RFLR_PARAMP_2000_US 0x01
#define RFLR_PARAMP_1000_US 0x02
#define RFLR_PARAMP_0500_US 0x03
#define RFLR_PARAMP_0250_US 0x04
#define RFLR_PARAMP_0125_US 0x05
#define RFLR_PARAMP_0100_US 0x06
#define RFLR_PARAMP_0062_US 0x07
#define RFLR_PARAMP_0050_US 0x08
#define RFLR_PARAMP_0040_US 0x09 // Default
#define RFLR_PARAMP_0031_US 0x0A
#define RFLR_PARAMP_0025_US 0x0B
#define RFLR_PARAMP_0020_US 0x0C
#define RFLR_PARAMP_0015_US 0x0D
#define RFLR_PARAMP_0012_US 0x0E
#define RFLR_PARAMP_0010_US 0x0F
/*!
* RegOcp
*/
#define RFLR_OCP_MASK 0xDF
#define RFLR_OCP_ON 0x20 // Default
#define RFLR_OCP_OFF 0x00
#define RFLR_OCP_TRIM_MASK 0xE0
#define RFLR_OCP_TRIM_045_MA 0x00
#define RFLR_OCP_TRIM_050_MA 0x01
#define RFLR_OCP_TRIM_055_MA 0x02
#define RFLR_OCP_TRIM_060_MA 0x03
#define RFLR_OCP_TRIM_065_MA 0x04
#define RFLR_OCP_TRIM_070_MA 0x05
#define RFLR_OCP_TRIM_075_MA 0x06
#define RFLR_OCP_TRIM_080_MA 0x07
#define RFLR_OCP_TRIM_085_MA 0x08
#define RFLR_OCP_TRIM_090_MA 0x09
#define RFLR_OCP_TRIM_095_MA 0x0A
#define RFLR_OCP_TRIM_100_MA 0x0B // Default
#define RFLR_OCP_TRIM_105_MA 0x0C
#define RFLR_OCP_TRIM_110_MA 0x0D
#define RFLR_OCP_TRIM_115_MA 0x0E
#define RFLR_OCP_TRIM_120_MA 0x0F
#define RFLR_OCP_TRIM_130_MA 0x10
#define RFLR_OCP_TRIM_140_MA 0x11
#define RFLR_OCP_TRIM_150_MA 0x12
#define RFLR_OCP_TRIM_160_MA 0x13
#define RFLR_OCP_TRIM_170_MA 0x14
#define RFLR_OCP_TRIM_180_MA 0x15
#define RFLR_OCP_TRIM_190_MA 0x16
#define RFLR_OCP_TRIM_200_MA 0x17
#define RFLR_OCP_TRIM_210_MA 0x18
#define RFLR_OCP_TRIM_220_MA 0x19
#define RFLR_OCP_TRIM_230_MA 0x1A
#define RFLR_OCP_TRIM_240_MA 0x1B
/*!
* RegLna
*/
#define RFLR_LNA_GAIN_MASK 0x1F
#define RFLR_LNA_GAIN_G1 0x20 // Default
#define RFLR_LNA_GAIN_G2 0x40
#define RFLR_LNA_GAIN_G3 0x60
#define RFLR_LNA_GAIN_G4 0x80
#define RFLR_LNA_GAIN_G5 0xA0
#define RFLR_LNA_GAIN_G6 0xC0
#define RFLR_LNA_BOOST_MASK 0xFC
#define RFLR_LNA_BOOST_OFF 0x00 // Default
#define RFLR_LNA_BOOST_ON 0x03
/*!
* RegFifoAddrPtr
*/
#define RFLR_FIFOADDRPTR 0x00 // Default
/*!
* RegFifoTxBaseAddr
*/
#define RFLR_FIFOTXBASEADDR 0x80 // Default
/*!
* RegFifoTxBaseAddr
*/
#define RFLR_FIFORXBASEADDR 0x00 // Default
/*!
* RegFifoRxCurrentAddr (Read Only)
*/
/*!
* RegIrqFlagsMask
*/
#define RFLR_IRQFLAGS_RXTIMEOUT_MASK 0x80
#define RFLR_IRQFLAGS_RXDONE_MASK 0x40
#define RFLR_IRQFLAGS_PAYLOADCRCERROR_MASK 0x20
#define RFLR_IRQFLAGS_VALIDHEADER_MASK 0x10
#define RFLR_IRQFLAGS_TXDONE_MASK 0x08
#define RFLR_IRQFLAGS_CADDONE_MASK 0x04
#define RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL_MASK 0x02
#define RFLR_IRQFLAGS_CADDETECTED_MASK 0x01
/*!
* RegIrqFlags
*/
#define RFLR_IRQFLAGS_RXTIMEOUT 0x80
#define RFLR_IRQFLAGS_RXDONE 0x40
#define RFLR_IRQFLAGS_PAYLOADCRCERROR 0x20
#define RFLR_IRQFLAGS_VALIDHEADER 0x10
#define RFLR_IRQFLAGS_TXDONE 0x08
#define RFLR_IRQFLAGS_CADDONE 0x04
#define RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL 0x02
#define RFLR_IRQFLAGS_CADDETECTED 0x01
/*!
* RegFifoRxNbBytes (Read Only) //
*/
/*!
* RegRxHeaderCntValueMsb (Read Only) //
*/
/*!
* RegRxHeaderCntValueLsb (Read Only) //
*/
/*!
* RegRxPacketCntValueMsb (Read Only) //
*/
/*!
* RegRxPacketCntValueLsb (Read Only) //
*/
/*!
* RegModemStat (Read Only) //
*/
#define RFLR_MODEMSTAT_RX_CR_MASK 0x1F
#define RFLR_MODEMSTAT_MODEM_STATUS_MASK 0xE0
/*!
* RegPktSnrValue (Read Only) //
*/
/*!
* RegPktRssiValue (Read Only) //
*/
/*!
* RegRssiValue (Read Only) //
*/
/*!
* RegHopChannel (Read Only) //
*/
#define RFLR_HOP_CHANNEL_PAYLOAD_CRC_ON_MASK 0xBF
#define RFLR_HOP_CHANNEL_PAYLOAD_CRC_ON 0x40
#define RFLR_HOP_CHANNEL_PAYLOAD_CRC_OFF 0x00
/*!
* RegModemConfig1
*/
#define RFLR_MODEMCONFIG1_BW_MASK 0x3F
#define RFLR_MODEMCONFIG1_BW_125_KHZ 0x00 // Default
#define RFLR_MODEMCONFIG1_BW_250_KHZ 0x40
#define RFLR_MODEMCONFIG1_BW_500_KHZ 0x80
#define RFLR_MODEMCONFIG1_CODINGRATE_MASK 0xC7
#define RFLR_MODEMCONFIG1_CODINGRATE_4_5 0x08
#define RFLR_MODEMCONFIG1_CODINGRATE_4_6 0x10 // Default
#define RFLR_MODEMCONFIG1_CODINGRATE_4_7 0x18
#define RFLR_MODEMCONFIG1_CODINGRATE_4_8 0x20
#define RFLR_MODEMCONFIG1_IMPLICITHEADER_MASK 0xFB
#define RFLR_MODEMCONFIG1_IMPLICITHEADER_ON 0x04
#define RFLR_MODEMCONFIG1_IMPLICITHEADER_OFF 0x00 // Default
#define RFLR_MODEMCONFIG1_RXPAYLOADCRC_MASK 0xFD
#define RFLR_MODEMCONFIG1_RXPAYLOADCRC_ON 0x02
#define RFLR_MODEMCONFIG1_RXPAYLOADCRC_OFF 0x00 // Default
#define RFLR_MODEMCONFIG1_LOWDATARATEOPTIMIZE_MASK 0xFE
#define RFLR_MODEMCONFIG1_LOWDATARATEOPTIMIZE_ON 0x01
#define RFLR_MODEMCONFIG1_LOWDATARATEOPTIMIZE_OFF 0x00 // Default
/*!
* RegModemConfig2
*/
#define RFLR_MODEMCONFIG2_SF_MASK 0x0F
#define RFLR_MODEMCONFIG2_SF_6 0x60
#define RFLR_MODEMCONFIG2_SF_7 0x70 // Default
#define RFLR_MODEMCONFIG2_SF_8 0x80
#define RFLR_MODEMCONFIG2_SF_9 0x90
#define RFLR_MODEMCONFIG2_SF_10 0xA0
#define RFLR_MODEMCONFIG2_SF_11 0xB0
#define RFLR_MODEMCONFIG2_SF_12 0xC0
#define RFLR_MODEMCONFIG2_TXCONTINUOUSMODE_MASK 0xF7
#define RFLR_MODEMCONFIG2_TXCONTINUOUSMODE_ON 0x08
#define RFLR_MODEMCONFIG2_TXCONTINUOUSMODE_OFF 0x00
#define RFLR_MODEMCONFIG2_AGCAUTO_MASK 0xFB
#define RFLR_MODEMCONFIG2_AGCAUTO_ON 0x04 // Default
#define RFLR_MODEMCONFIG2_AGCAUTO_OFF 0x00
#define RFLR_MODEMCONFIG2_SYMBTIMEOUTMSB_MASK 0xFC
#define RFLR_MODEMCONFIG2_SYMBTIMEOUTMSB 0x00 // Default
/*!
* RegHopChannel (Read Only)
*/
#define RFLR_HOPCHANNEL_PLL_LOCK_TIMEOUT_MASK 0x7F
#define RFLR_HOPCHANNEL_PLL_LOCK_FAIL 0x80
#define RFLR_HOPCHANNEL_PLL_LOCK_SUCCEED 0x00 // Default
#define RFLR_HOPCHANNEL_PAYLOAD_CRC16_MASK 0xBF
#define RFLR_HOPCHANNEL_PAYLOAD_CRC16_ON 0x40
#define RFLR_HOPCHANNEL_PAYLOAD_CRC16_OFF 0x00 // Default
#define RFLR_HOPCHANNEL_CHANNEL_MASK 0x3F
/*!
* RegSymbTimeoutLsb
*/
#define RFLR_SYMBTIMEOUTLSB_SYMBTIMEOUT 0x64 // Default
/*!
* RegPreambleLengthMsb
*/
#define RFLR_PREAMBLELENGTHMSB 0x00 // Default
/*!
* RegPreambleLengthLsb
*/
#define RFLR_PREAMBLELENGTHLSB 0x08 // Default
/*!
* RegPayloadLength
*/
#define RFLR_PAYLOADLENGTH 0x0E // Default
/*!
* RegPayloadMaxLength
*/
#define RFLR_PAYLOADMAXLENGTH 0xFF // Default
/*!
* RegHopPeriod
*/
#define RFLR_HOPPERIOD_FREQFOPPINGPERIOD 0x00 // Default
/*!
* RegDioMapping1
*/
#define RFLR_DIOMAPPING1_DIO0_MASK 0x3F
#define RFLR_DIOMAPPING1_DIO0_00 0x00 // Default
#define RFLR_DIOMAPPING1_DIO0_01 0x40
#define RFLR_DIOMAPPING1_DIO0_10 0x80
#define RFLR_DIOMAPPING1_DIO0_11 0xC0
#define RFLR_DIOMAPPING1_DIO1_MASK 0xCF
#define RFLR_DIOMAPPING1_DIO1_00 0x00 // Default
#define RFLR_DIOMAPPING1_DIO1_01 0x10
#define RFLR_DIOMAPPING1_DIO1_10 0x20
#define RFLR_DIOMAPPING1_DIO1_11 0x30
#define RFLR_DIOMAPPING1_DIO2_MASK 0xF3
#define RFLR_DIOMAPPING1_DIO2_00 0x00 // Default
#define RFLR_DIOMAPPING1_DIO2_01 0x04
#define RFLR_DIOMAPPING1_DIO2_10 0x08
#define RFLR_DIOMAPPING1_DIO2_11 0x0C
#define RFLR_DIOMAPPING1_DIO3_MASK 0xFC
#define RFLR_DIOMAPPING1_DIO3_00 0x00 // Default
#define RFLR_DIOMAPPING1_DIO3_01 0x01
#define RFLR_DIOMAPPING1_DIO3_10 0x02
#define RFLR_DIOMAPPING1_DIO3_11 0x03
/*!
* RegDioMapping2
*/
#define RFLR_DIOMAPPING2_DIO4_MASK 0x3F
#define RFLR_DIOMAPPING2_DIO4_00 0x00 // Default
#define RFLR_DIOMAPPING2_DIO4_01 0x40
#define RFLR_DIOMAPPING2_DIO4_10 0x80
#define RFLR_DIOMAPPING2_DIO4_11 0xC0
#define RFLR_DIOMAPPING2_DIO5_MASK 0xCF
#define RFLR_DIOMAPPING2_DIO5_00 0x00 // Default
#define RFLR_DIOMAPPING2_DIO5_01 0x10
#define RFLR_DIOMAPPING2_DIO5_10 0x20
#define RFLR_DIOMAPPING2_DIO5_11 0x30
#define RFLR_DIOMAPPING2_MAP_MASK 0xFE
#define RFLR_DIOMAPPING2_MAP_PREAMBLEDETECT 0x01
#define RFLR_DIOMAPPING2_MAP_RSSI 0x00 // Default
/*!
* RegVersion (Read Only)
*/
/*!
* RegAgcRef
*/
/*!
* RegAgcThresh1
*/
/*!
* RegAgcThresh2
*/
/*!
* RegAgcThresh3
*/
/*!
* RegFifoRxByteAddr (Read Only)
*/
/*!
* RegPllHop
*/
#define RFLR_PLLHOP_FASTHOP_MASK 0x7F
#define RFLR_PLLHOP_FASTHOP_ON 0x80
#define RFLR_PLLHOP_FASTHOP_OFF 0x00 // Default
/*!
* RegTcxo
*/
#define RFLR_TCXO_TCXOINPUT_MASK 0xEF
#define RFLR_TCXO_TCXOINPUT_ON 0x10
#define RFLR_TCXO_TCXOINPUT_OFF 0x00 // Default
/*!
* RegPaDac
*/
#define RFLR_PADAC_20DBM_MASK 0xF8
#define RFLR_PADAC_20DBM_ON 0x07
#define RFLR_PADAC_20DBM_OFF 0x04 // Default
/*!
* RegPll
*/
#define RFLR_PLL_BANDWIDTH_MASK 0x3F
#define RFLR_PLL_BANDWIDTH_75 0x00
#define RFLR_PLL_BANDWIDTH_150 0x40
#define RFLR_PLL_BANDWIDTH_225 0x80
#define RFLR_PLL_BANDWIDTH_300 0xC0 // Default
/*!
* RegPllLowPn
*/
#define RFLR_PLLLOWPN_BANDWIDTH_MASK 0x3F
#define RFLR_PLLLOWPN_BANDWIDTH_75 0x00
#define RFLR_PLLLOWPN_BANDWIDTH_150 0x40
#define RFLR_PLLLOWPN_BANDWIDTH_225 0x80
#define RFLR_PLLLOWPN_BANDWIDTH_300 0xC0 // Default
/*!
* Define XRange hardware version
*/
#define XR_VER_0_1 0
#define XR_VER_1_0 1
#define XRANGE_HW_VER XR_VER_1_0
/*!
* RF process function return codes
*/
typedef enum
{
RF_IDLE,
RF_BUSY,
RF_RX_DONE,
RF_RX_TIMEOUT,
RF_TX_DONE,
RF_TX_TIMEOUT,
RF_LEN_ERROR,
RF_CHANNEL_EMPTY,
RF_CHANNEL_ACTIVITY_DETECTED,
}tRFProcessReturnCodes;
/*!
* Radio driver structure defining the different function pointers
*/
typedef struct sRadioDriver
{
void ( *Init )( void );
void ( *Reset )( void );
void ( *StartRx )( void );
void ( *GetRxPacket )( void *buffer, uint16_t *size );
void ( *SetTxPacket )( const void *buffer, uint16_t size );
uint32_t ( *Process )( void );
}tRadioDriver;
/*!
* RegFormerTemp
*/
typedef struct sSX1272LR
{
uint8_t RegFifo; // 0x00
// Common settings
uint8_t RegOpMode; // 0x01
uint8_t RegRes02; // 0x02
uint8_t RegRes03; // 0x03
uint8_t RegRes04; // 0x04
uint8_t RegRes05; // 0x05
uint8_t RegFrfMsb; // 0x06
uint8_t RegFrfMid; // 0x07
uint8_t RegFrfLsb; // 0x08
// Tx settings
uint8_t RegPaConfig; // 0x09
uint8_t RegPaRamp; // 0x0A
uint8_t RegOcp; // 0x0B
// Rx settings
uint8_t RegLna; // 0x0C
// LoRa registers
uint8_t RegFifoAddrPtr; // 0x0D
uint8_t RegFifoTxBaseAddr; // 0x0E
uint8_t RegFifoRxBaseAddr; // 0x0F
uint8_t RegFifoRxCurrentAddr; // 0x10
uint8_t RegIrqFlagsMask; // 0x11
uint8_t RegIrqFlags; // 0x12
uint8_t RegNbRxBytes; // 0x13
uint8_t RegRxHeaderCntValueMsb; // 0x14
uint8_t RegRxHeaderCntValueLsb; // 0x15
uint8_t RegRxPacketCntValueMsb; // 0x16
uint8_t RegRxPacketCntValueLsb; // 0x17
uint8_t RegModemStat; // 0x18
uint8_t RegPktSnrValue; // 0x19
uint8_t RegPktRssiValue; // 0x1A
uint8_t RegRssiValue; // 0x1B
uint8_t RegHopChannel; // 0x1C
uint8_t RegModemConfig1; // 0x1D
uint8_t RegModemConfig2; // 0x1E
uint8_t RegSymbTimeoutLsb; // 0x1F
uint8_t RegPreambleMsb; // 0x20
uint8_t RegPreambleLsb; // 0x21
uint8_t RegPayloadLength; // 0x22
uint8_t RegMaxPayloadLength; // 0x23
uint8_t RegHopPeriod; // 0x24
uint8_t RegFifoRxByteAddr; // 0x25
uint8_t RegTestReserved26[0x27 - 0x26]; // 0x26-0x27
uint8_t RegFeiMsb; // 0x28
uint8_t RegFeiMib; // 0x29
uint8_t RegFeiLsb; // 0x2A
uint8_t RegTestReserved2B[0x30 - 0x2B]; // 0x2B-0x30
uint8_t RegDetectOptimize; // 0x31
uint8_t RegTestReserved32; // 0x32
uint8_t RegInvertIQ; // 0x33
uint8_t RegTestReserved34[0x36 - 0x34]; // 0x34-0x36
uint8_t RegDetectionThreshold; // 0x37
uint8_t RegTestReserved38[0x3F - 0x38]; // 0x38-0x3F
// I/O settings
uint8_t RegDioMapping1; // 0x40
uint8_t RegDioMapping2; // 0x41
// Version
uint8_t RegVersion; // 0x42
// Additional settings
uint8_t RegAgcRef; // 0x43
uint8_t RegAgcThresh1; // 0x44
uint8_t RegAgcThresh2; // 0x45
uint8_t RegAgcThresh3; // 0x46
// Test
uint8_t RegTestReserved47[0x4B - 0x47]; // 0x47-0x4A
// Additional settings
uint8_t RegPllHop; // 0x4B
// Test
uint8_t RegTestReserved4C[0x58-0x4C]; // 0x4C-0x57
// Additional settings
uint8_t RegTcxo; // 0x58
// Test
uint8_t RegTestReserved59; // 0x59
// Additional settings
uint8_t RegPaDac; // 0x5A
// Test
uint8_t RegTestReserved5B; // 0x5B
// Additional settings
uint8_t RegPll; // 0x5C
// Test
uint8_t RegTestReserved5D; // 0x5D
// Additional settings
uint8_t RegPllLowPn; // 0x5E
// Test
uint8_t RegTestReserved5F[0x6C - 0x5F]; // 0x5F-0x6B
// Additional settings
uint8_t RegFormerTemp; // 0x6C
// Test
uint8_t RegTestReserved6D[0x71 - 0x6D]; // 0x6D-0x70
}tSX1272LR;
extern tSX1272LR* SX1272LR;
// RXTX pin control see errata note
#define RXTX( txEnable ) SX1272WriteRxTx( txEnable );
#define TICK_RATE_MS( ms ) ( ms )
typedef enum
{
RADIO_RESET_OFF,
RADIO_RESET_ON,
}tRadioResetState;
#ifdef __cplusplus
extern "C" {
#endif
/*!
* \brief Initializes the RadioDriver structure with specific radio
* functions.
*
* \retval radioDriver Pointer to the radio driver variable
*/
tRadioDriver* RadioDriverInit( void );
/*!
* \brief SX1272 registers array
*/
extern uint8_t SX1272Regs[0x70];
/*!
* \brief Enables LoRa modem
*
* \param [IN] opMode New operating mode
*/
void SX1272SetLoRaOn( bool enable );
/*!
* \brief Gets the LoRa modem state
*
* \retval LoraOn Current LoRa modem mode
*/
bool SX1272GetLoRaOn( void );
/*!
* \brief Initializes the SX1272
*/
void SX1272Init( void );
/*!
* \brief Resets the SX1272
*/
void SX1272Reset( void );
/*!
* \brief Sets the SX1272 operating mode
*
* \param [IN] opMode New operating mode
*/
void SX1272SetOpMode( uint8_t opMode );
/*!
* \brief Gets the SX1272 operating mode
*
* \retval opMode Current operating mode
*/
uint8_t SX1272GetOpMode( void );
/*!
* \brief Reads the current Rx gain setting
*
* \retval rxGain Current gain setting
*/
uint8_t SX1272ReadRxGain( void );
/*!
* \brief Trigs and reads the current RSSI value
*
* \retval rssiValue Current RSSI value in [dBm]
*/
double SX1272ReadRssi( void );
/*!
* \brief Gets the Rx gain value measured while receiving the packet
*
* \retval rxGainValue Current Rx gain value
*/
uint8_t SX1272GetPacketRxGain( void );
/*!
* \brief Gets the SNR value measured while receiving the packet
*
* \retval snrValue Current SNR value in [dB]
*/
int8_t SX1272GetPacketSnr( void );
/*!
* \brief Gets the RSSI value measured while receiving the packet
*
* \retval rssiValue Current RSSI value in [dBm]
*/
double SX1272GetPacketRssi( void );
/*!
* \brief Sets the new state of the RF state machine
*
* \param [IN]: state New RF state machine state
*/
void SX1272SetRFState( uint8_t state );
/*!
* \brief Initializes the radio interface I/Os
*/
void SX1272InitIo( void );
/*!
* \brief Set the radio reset pin state
*
* \param state New reset pin state
*/
void SX1272SetReset( uint8_t state );
/*!
* \brief Writes the radio register at the specified address
*
* \param [IN]: addr Register address
* \param [IN]: data New register value
*/
void SX1272Write( uint8_t addr, uint8_t data );
/*!
* \brief Reads the radio register at the specified address
*
* \param [IN]: addr Register address
* \param [OUT]: data Register value
*/
void SX1272Read( uint8_t addr, uint8_t *data );
/*!
* \brief Writes multiple radio registers starting at address
*
* \param [IN] addr First Radio register address
* \param [IN] buffer Buffer containing the new register's values
* \param [IN] size Number of registers to be written
*/
void SX1272WriteBuffer( uint8_t addr, uint8_t *buffer, uint8_t size );
/*!
* \brief Reads multiple radio registers starting at address
*
* \param [IN] addr First Radio register address
* \param [OUT] buffer Buffer where to copy the registers data
* \param [IN] size Number of registers to be read
*/
void SX1272ReadBuffer( uint8_t addr, uint8_t *buffer, uint8_t size );
/*!
* \brief Writes the buffer contents to the radio FIFO
*
* \param [IN] buffer Buffer containing data to be put on the FIFO.
* \param [IN] size Number of bytes to be written to the FIFO
*/
void SX1272WriteFifo( uint8_t *buffer, uint8_t size );
/*!
* \brief Reads the contents of the radio FIFO
*
* \param [OUT] buffer Buffer where to copy the FIFO read data.
* \param [IN] size Number of bytes to be read from the FIFO
*/
void SX1272ReadFifo( uint8_t *buffer, uint8_t size );
/*!
* \brief Gets the SX1272 DIO0 hardware pin status
*
* \retval status Current hardware pin status [1, 0]
*/
inline uint8_t SX1272ReadDio0( void );
/*!
* \brief Gets the SX1272 DIO1 hardware pin status
*
* \retval status Current hardware pin status [1, 0]
*/
inline uint8_t SX1272ReadDio1( void );
/*!
* \brief Gets the SX1272 DIO2 hardware pin status
*
* \retval status Current hardware pin status [1, 0]
*/
inline uint8_t SX1272ReadDio2( void );
/*!
* \brief Gets the SX1272 DIO3 hardware pin status
*
* \retval status Current hardware pin status [1, 0]
*/
inline uint8_t SX1272ReadDio3( void );
/*!
* \brief Gets the SX1272 DIO4 hardware pin status
*
* \retval status Current hardware pin status [1, 0]
*/
inline uint8_t SX1272ReadDio4( void );
/*!
* \brief Gets the SX1272 DIO5 hardware pin status
*
* \retval status Current hardware pin status [1, 0]
*/
inline uint8_t SX1272ReadDio5( void );
/*!
* \brief Writes the external RxTx pin value
*
* \remark see errata note
*
* \param [IN] txEnable [1: Tx, 0: Rx]
*/
inline void SX1272WriteRxTx( uint8_t txEnable );
/*!
* \brief Initializes the SX1272
*/
void SX1272LoRaInit( void );
/*!
* \brief Sets the SX1272 to datasheet default values
*/
void SX1272LoRaSetDefaults( void );
/*!
* \brief Enables/Disables the LoRa modem
*
* \param [IN]: enable [true, false]
*/
void SX1272LoRaSetLoRaOn( bool enable );
/*!
* \brief Sets the SX1272 operating mode
*
* \param [IN] opMode New operating mode
*/
void SX1272LoRaSetOpMode( uint8_t opMode );
/*!
* \brief Gets the SX1272 operating mode
*
* \retval opMode Current operating mode
*/
uint8_t SX1272LoRaGetOpMode( void );
/*!
* \brief Reads the current Rx gain setting
*
* \retval rxGain Current gain setting
*/
uint8_t SX1272LoRaReadRxGain( void );
/*!
* \brief Trigs and reads the current RSSI value
*
* \retval rssiValue Current RSSI value in [dBm]
*/
double SX1272LoRaReadRssi( void );
/*!
* \brief Sets the radio in Rx mode. Waiting for a packet
*/
void SX1272LoRaStartRx( void );
/*!
* \brief Gets a copy of the current received buffer
*
* \param [IN]: buffer Buffer pointer
* \param [IN]: size Buffer size
*/
void SX1272LoRaGetRxPacket( void *buffer, uint16_t *size );
/*!
* \brief Sets a copy of the buffer to be transmitted
*
* \param [IN]: buffer Buffer pointer
* \param [IN]: size Buffer size
*/
void SX1272LoRaSetTxPacket( const void *buffer, uint16_t size );
/*!
* \brief Gets the current RFState
*
* \retval rfState Current RF state [RF_IDLE, RF_BUSY,
* RF_RX_DONE, RF_RX_TIMEOUT,
* RF_TX_DONE, RF_TX_TIMEOUT]
*/
uint8_t SX1272LoRaGetRFState( void );
/*!
* \brief Sets the new state of the RF state machine
*
* \param [IN]: state New RF state machine state
*/
void SX1272LoRaSetRFState( uint8_t state );
/*!
* \brief Process the LoRa modem Rx and Tx state machines depending on the
* SX1272 operating mode.
*
* \retval rfState Current RF state [RF_IDLE, RF_BUSY,
* RF_RX_DONE, RF_RX_TIMEOUT,
* RF_TX_DONE, RF_TX_TIMEOUT]
*/
uint32_t SX1272LoRaProcess( void );
/*!
* \brief Writes the new RF frequency value
*
* \param [IN] freq New RF frequency value in [Hz]
*/
void SX1272LoRaSetRFFrequency( uint32_t freq );
/*!
* \brief Reads the current RF frequency value
*
* \retval freq Current RF frequency value in [Hz]
*/
uint32_t SX1272LoRaGetRFFrequency( void );
/*!
* \brief Writes the new RF output power value
*
* \param [IN] power New output power value in [dBm]
*/
void SX1272LoRaSetRFPower( int8_t power );
/*!
* \brief Reads the current RF output power value
*
* \retval power Current output power value in [dBm]
*/
int8_t SX1272LoRaGetRFPower( void );
/*!
* \brief Writes the new Signal Bandwidth value
*
* \remark This function sets the IF frequency according to the datasheet
*
* \param [IN] factor New Signal Bandwidth value [0: 125 kHz, 1: 250 kHz, 2: 500 kHz]
*/
void SX1272LoRaSetSignalBandwidth( uint8_t bw );
/*!
* \brief Reads the current Signal Bandwidth value
*
* \retval factor Current Signal Bandwidth value [0: 125 kHz, 1: 250 kHz, 2: 500 kHz]
*/
uint8_t SX1272LoRaGetSignalBandwidth( void );
/*!
* \brief Writes the new Spreading Factor value
*
* \param [IN] factor New Spreading Factor value [7, 8, 9, 10, 11, 12]
*/
void SX1272LoRaSetSpreadingFactor( uint8_t factor );
/*!
* \brief Reads the current Spreading Factor value
*
* \retval factor Current Spreading Factor value [7, 8, 9, 10, 11, 12]
*/
uint8_t SX1272LoRaGetSpreadingFactor( void );
/*!
* \brief Writes the new Error Coding value
*
* \param [IN] value New Error Coding value [1: 4/5, 2: 4/6, 3: 4/7, 4: 4/8]
*/
void SX1272LoRaSetErrorCoding( uint8_t value );
/*!
* \brief Reads the current Error Coding value
*
* \retval value Current Error Coding value [1: 4/5, 2: 4/6, 3: 4/7, 4: 4/8]
*/
uint8_t SX1272LoRaGetErrorCoding( void );
/*!
* \brief Enables/Disables the packet CRC generation
*
* \param [IN] enaable [true, false]
*/
void SX1272LoRaSetPacketCrcOn( bool enable );
/*!
* \brief Reads the current packet CRC generation status
*
* \retval enable [true, false]
*/
bool SX1272LoRaGetPacketCrcOn( void );
/*!
* \brief Enables/Disables the Implicit Header mode in LoRa
*
* \param [IN] enable [true, false]
*/
void SX1272LoRaSetImplicitHeaderOn( bool enable );
/*!
* \brief Check if implicit header mode in LoRa in enabled or disabled
*
* \retval enable [true, false]
*/
bool SX1272LoRaGetImplicitHeaderOn( void );
/*!
* \brief Enables/Disables Rx single instead of Rx continuous
*
* \param [IN] enable [true, false]
*/
void SX1272LoRaSetRxSingleOn( bool enable );
/*!
* \brief Check if LoRa is in Rx Single mode
*
* \retval enable [true, false]
*/
bool SX1272LoRaGetRxSingleOn( void );
/*!
* \brief Enables/Disables the frequency hopping
*
* \param [IN] enable [true, false]
*/
void SX1272LoRaSetFreqHopOn( bool enable );
/*!
* \brief Get the frequency hopping status
*
* \param [IN] enable [true, false]
*/
bool SX1272LoRaGetFreqHopOn( void );
/*!
* \brief Set symbol period between frequency hops
*
* \param [IN] value
*/
void SX1272LoRaSetHopPeriod( uint8_t value );
/*!
* \brief Get symbol period between frequency hops
*
* \retval value symbol period between frequency hops
*/
uint8_t SX1272LoRaGetHopPeriod( void );
/*!
* \brief Set timeout Tx packet (based on MCU timer, timeout between Tx Mode entry Tx Done IRQ)
*
* \param [IN] value timeout (ms)
*/
void SX1272LoRaSetTxPacketTimeout( uint32_t value );
/*!
* \brief Get timeout between Tx packet (based on MCU timer, timeout between Tx Mode entry Tx Done IRQ)
*
* \retval value timeout (ms)
*/
uint32_t SX1272LoRaGetTxPacketTimeout( void );
/*!
* \brief Set timeout Rx packet (based on MCU timer, timeout between Rx Mode entry and Rx Done IRQ)
*
* \param [IN] value timeout (ms)
*/
void SX1272LoRaSetRxPacketTimeout( uint32_t value );
/*!
* \brief Get timeout Rx packet (based on MCU timer, timeout between Rx Mode entry and Rx Done IRQ)
*
* \retval value timeout (ms)
*/
uint32_t SX1272LoRaGetRxPacketTimeout( void );
/*!
* \brief Set payload length
*
* \param [IN] value payload length
*/
void SX1272LoRaSetPayloadLength( uint8_t value );
/*!
* \brief Get payload length
*
* \retval value payload length
*/
uint8_t SX1272LoRaGetPayloadLength( void );
/*!
* \brief Enables/Disables the 20 dBm PA
*
* \param [IN] enable [true, false]
*/
void SX1272LoRaSetPa20dBm( bool enale );
/*!
* \brief Gets the current 20 dBm PA status
*
* \retval enable [true, false]
*/
bool SX1272LoRaGetPa20dBm( void );
/*!
* \brief Set the RF Output pin
*
* \param [IN] RF_PACONFIG_PASELECT_PABOOST or RF_PACONFIG_PASELECT_RFO
*/
void SX1272LoRaSetPAOutput( uint8_t outputPin );
/*!
* \brief Gets the used RF Ouptu pin
*
* \retval RF_PACONFIG_PASELECT_PABOOST or RF_PACONFIG_PASELECT_RFO
*/
uint8_t SX1272LoRaGetPAOutput( void );
/*!
* \brief Writes the new PA rise/fall time of ramp up/down value
*
* \param [IN] value New PaRamp value
*/
void SX1272LoRaSetPaRamp( uint8_t value );
/*!
* \brief Reads the current PA rise/fall time of ramp up/down value
*
* \retval freq Current PaRamp value
*/
uint8_t SX1272LoRaGetPaRamp( void );
/*!
* \brief Set Symbol Timeout based on symbol length
*
* \param [IN] value number of symbol
*/
void SX1272LoRaSetSymbTimeout( uint16_t value );
/*!
* \brief Get Symbol Timeout based on symbol length
*
* \retval value number of symbol
*/
uint16_t SX1272LoRaGetSymbTimeout( void );
/*!
* \brief Configure the device to optimize low datarate transfers
*
* \param [IN] enable Enables/Disables the low datarate optimization
*/
void SX1272LoRaSetLowDatarateOptimize( bool enable );
/*!
* \brief Get the status of optimize low datarate transfers
*
* \retval LowDatarateOptimize enable or disable
*/
bool SX1272LoRaGetLowDatarateOptimize( void );
/*!
* \brief Get the preamble length
*
* \retval value preamble length
*/
uint16_t SX1272LoRaGetPreambleLength( void );
/*!
* \brief Set the preamble length
*
* \param [IN] value preamble length
*/
void SX1272LoRaSetPreambleLength( uint16_t value );
/*!
* \brief Set the number or rolling preamble symbol needed for detection
*
* \param [IN] value number of preamble symbol
*/
void SX1272LoRaSetNbTrigPeaks( uint8_t value );
/*!
* \brief Get the number or rolling preamble symbol needed for detection
*
* \retval value number of preamble symbol
*/
uint8_t SX1272LoRaGetNbTrigPeaks( void );
/*!
* Initializes board peripherals
*/
void BoardInit( void );
void SpiInit( void );
uint8_t SpiInOut( uint8_t outData );
void RTC_Config(void);
#ifdef __cplusplus
}
#endif
#endif //__RADINO32_SX1272_H__
|
aha-app/librdkafka
|
src/rdkafka_sasl_aws_msk_iam.c
|
/*
* librdkafka - The Apache Kafka C/C++ library
*
* Copyright (c) 2017 <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Builtin SASL AWS MSK IAM support
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <curl/curl.h>
#include <sys/time.h>
#include "rdkafka_int.h"
#include "rdkafka_transport.h"
#include "rdkafka_transport_int.h"
#include "rdkafka_sasl.h"
#include "rdkafka_sasl_int.h"
#include "rdstringbuilder.h"
#include "rdtypes.h"
#include "rdunittest.h"
#if WITH_SSL
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include "rdkafka_aws.h"
#else
#error "WITH_SSL (OpenSSL) is required for SASL AWS MSK IAM"
#endif
/**
* @struct Per-client-instance SASL/AWS_MSK_IAM handle.
*/
typedef struct rd_kafka_sasl_aws_msk_iam_handle_s {
/**< Read-write lock for fields in the handle. */
rwlock_t lock;
/**< Required AWS credential values. */
char *aws_access_key_id; /* AWS access key id from conf */
char *aws_secret_access_key; /* AWS secret access key from conf */
char *aws_region; /* AWS region from conf */
char *aws_security_token; /* AWS security token from conf (optional) */
/**< When the credentials expire, in terms of the number of
* milliseconds since the epoch. Wall clock time.
*/
rd_ts_t wts_md_lifetime;
/**< The point after which credentials should be replaced with
* new ones, in terms of the number of milliseconds since the
* epoch. Wall clock time.
*/
rd_ts_t wts_refresh_after;
/**< When the last credential refresh was enqueued (0 = never)
* in terms of the number of milliseconds since the epoch.
* Wall clock time.
*/
rd_ts_t wts_enqueued_refresh;
/**< Error message for validation and/or credential retrieval problems. */
char *errstr;
/**< Back-pointer to client instance. */
rd_kafka_t *rk;
/**< Credential refresh timer */
rd_kafka_timer_t credential_refresh_tmr;
} rd_kafka_sasl_aws_msk_iam_handle_t;
/**
* @brief Per-connection state
*/
struct rd_kafka_sasl_aws_msk_iam_state {
enum {
RD_KAFKA_SASL_AWS_MSK_IAM_SEND_CLIENT_FIRST_MESSAGE,
RD_KAFKA_SASL_AWS_MSK_IAM_RECEIVE_SERVER_RESPONSE,
} state;
const EVP_MD *md; /* hash function pointer */
char *hostname; /* hostname from client_new */
/*
* A place to store a consistent view of the token and extensions
* throughout the authentication process -- even if it is refreshed
* midway through this particular authentication.
*/
char *aws_access_key_id; /* AWS access key id from conf */
char *aws_secret_access_key; /* AWS secret access key from conf */
char *aws_region; /* AWS region from conf */
char *aws_security_token; /* AWS security token from conf (optional) */
};
/**
* @brief free memory inside the given credential
*/
static void rd_kafka_sasl_aws_msk_iam_credential_free (
rd_kafka_aws_credential_t *credential) {
RD_IF_FREE(credential->aws_access_key_id, rd_free);
RD_IF_FREE(credential->aws_secret_access_key, rd_free);
RD_IF_FREE(credential->aws_region, rd_free);
RD_IF_FREE(credential->aws_security_token, rd_free);
memset(credential, 0, sizeof(*credential));
}
/**
* @brief Set SASL/AWS_MSK_IAM token and metadata
*
* @param rk Client instance.
* @param aws_access_key_id Access key id.
* @param aws_secret_access_key Secret access key.
* @param aws_region AWS region used in signing and for STS endpoint.
* @param aws_security_token Temporary AWS security token. Required for using STS.
* Use rd_kafka_sasl_aws_msk_iam_credential_free() to free members if
* return value is not -1.
* @param md_lifetime_ms when the credential expires, in terms of the number of
* milliseconds since the epoch. See https://currentmillis.com/.
*
* @returns \c RD_KAFKA_RESP_ERR_NO_ERROR on success, otherwise errstr set and:
* \c RD_KAFKA_RESP_ERR__INVALID_ARG if any of the arguments are
* invalid;
* \c RD_KAFKA_RESP_ERR__STATE if SASL/OAUTHBEARER is not configured as
* the client's authentication mechanism.
*
* @sa rd_kafka_aws_msk_iam_set_credential_failure
*/
static rd_kafka_resp_err_t
rd_kafka_aws_msk_iam_set_credential (rd_kafka_t *rk,
const char *aws_access_key_id,
const char *aws_secret_access_key,
const char *aws_region,
const char *aws_security_token,
int64_t md_lifetime_ms,
char *errstr, size_t errstr_size) {
rd_kafka_sasl_aws_msk_iam_handle_t *handle = rk->rk_sasl.handle;
rd_ts_t now_wallclock;
rd_ts_t wts_md_lifetime = md_lifetime_ms * 1000;
/* Check if SASL/AWS_MSK_IAM is the configured auth mechanism */
if (rk->rk_conf.sasl.provider != &rd_kafka_sasl_aws_msk_iam_provider ||
!handle) {
rd_snprintf(errstr, errstr_size, "SASL/AWS_MSK_IAM is not the "
"configured authentication mechanism");
return RD_KAFKA_RESP_ERR__STATE;
}
/* Check args for correct format/value */
now_wallclock = rd_uclock();
if (wts_md_lifetime <= now_wallclock) {
rd_snprintf(errstr, errstr_size,
"Must supply an unexpired token: "
"now=%"PRId64"ms, exp=%"PRId64"ms",
now_wallclock/1000, wts_md_lifetime/1000);
return RD_KAFKA_RESP_ERR__INVALID_ARG;
}
rwlock_wrlock(&handle->lock);
RD_IF_FREE(handle->aws_access_key_id, rd_free);
handle->aws_access_key_id = rd_strdup(aws_access_key_id);
RD_IF_FREE(handle->aws_secret_access_key, rd_free);
handle->aws_secret_access_key = rd_strdup(aws_secret_access_key);
RD_IF_FREE(handle->aws_region, rd_free);
handle->aws_region = rd_strdup(aws_region);
RD_IF_FREE(handle->aws_security_token, rd_free);
handle->aws_security_token = rd_strdup(aws_security_token);
handle->wts_md_lifetime = wts_md_lifetime;
/* Schedule a refresh 80% through its remaining lifetime */
handle->wts_refresh_after =
(rd_ts_t)(now_wallclock + 0.8 *
(wts_md_lifetime - now_wallclock));
RD_IF_FREE(handle->errstr, rd_free);
handle->errstr = NULL;
rwlock_wrunlock(&handle->lock);
rd_kafka_dbg(rk, SECURITY, "BRKMAIN",
"Waking up waiting broker threads after "
"setting AWS_MSK_IAM credential");
rd_kafka_all_brokers_wakeup(rk, RD_KAFKA_BROKER_STATE_TRY_CONNECT);
return RD_KAFKA_RESP_ERR_NO_ERROR;
}
/**
* @brief SASL/AWS_MSK_IAM credential refresh failure indicator.
*
* @param rk Client instance.
* @param errstr mandatory human readable error reason for failing to acquire
* a credential.
*
* @returns \c RD_KAFKA_RESP_ERR_NO_ERROR on success, otherwise
* \c RD_KAFKA_RESP_ERR__STATE if SASL/AWS_MSK_IAM is enabled but is
* not configured to be the client's authentication mechanism,
* \c RD_KAFKA_RESP_ERR__INVALID_ARG if no error string is supplied.
* @sa rd_kafka_aws_msk_iam_set_credential
*/
static rd_kafka_resp_err_t
rd_kafka_aws_msk_iam_set_credential_failure (rd_kafka_t *rk, const char *errstr) {
rd_kafka_sasl_aws_msk_iam_handle_t *handle = rk->rk_sasl.handle;
rd_bool_t error_changed;
/* Check if SASL/AWS_MSK_IAM is the configured auth mechanism */
if (rk->rk_conf.sasl.provider != &rd_kafka_sasl_aws_msk_iam_provider ||
!handle) {
return RD_KAFKA_RESP_ERR__STATE;
}
if (!errstr || !*errstr) {
return RD_KAFKA_RESP_ERR__INVALID_ARG;
}
rwlock_wrlock(&handle->lock);
error_changed = !handle->errstr ||
strcmp(handle->errstr, errstr);
RD_IF_FREE(handle->errstr, rd_free);
handle->errstr = rd_strdup(errstr);
/* Leave any existing credential because it may have some life left,
* schedule a refresh for 10 seconds later. */
handle->wts_refresh_after = rd_uclock() + (10*1000*1000);
rwlock_wrunlock(&handle->lock);
/* Trigger an ERR__AUTHENTICATION error if the error changed. */
if (error_changed) {
rd_kafka_op_err(rk, RD_KAFKA_RESP_ERR__AUTHENTICATION,
"Failed to acquire SASL AWS_MSK_IAM credential: %s",
errstr);
}
return RD_KAFKA_RESP_ERR_NO_ERROR;
}
static int
rd_kafka_aws_msk_iam_credential_refresh0 (
rd_kafka_t *rk,
rd_kafka_aws_credential_t *credential,
int64_t now_wallclock_ms,
char *errstr, size_t errstr_size) {
const rd_kafka_conf_t *conf = &rk->rk_conf;
rd_kafka_sasl_aws_msk_iam_handle_t *handle = rk->rk_sasl.handle;
str_builder_t *sb;
sb = str_builder_create();
int r = 1;
char *handle_aws_access_key_id;
char *handle_aws_secret_access_key;
char *handle_aws_region;
char *handle_aws_security_token = NULL;
memset(credential, 0, sizeof(*credential));
time_t t = time(&t);
struct tm *tmp = gmtime(&t); // must use UTC time
char *ymd = rd_malloc(sizeof(char) * 9);
char *hms = rd_malloc(sizeof(char) * 7);
strftime(ymd, sizeof(char) * 9, "%Y%m%d", tmp);
strftime(hms, sizeof(char) * 7, "%H%M%S", tmp);
rwlock_wrlock(&handle->lock);
handle_aws_access_key_id = rd_strdup(handle->aws_access_key_id);
handle_aws_secret_access_key = rd_strdup(handle->aws_secret_access_key);
handle_aws_region = rd_strdup(handle->aws_region);
handle_aws_security_token = rd_strdup(handle->aws_security_token);
/* parameters to build request_parameters */
char *role_arn = rd_kafka_aws_uri_encode(conf->sasl.role_arn);
char *role_session_name = rd_strdup(conf->sasl.role_session_name);
char duration_sec[256];
rd_snprintf(duration_sec, sizeof(duration_sec), "%d", conf->sasl.duration_sec);
char *action = "AssumeRole";
char *version = "2011-06-15";
/******************************************/
rwlock_wrunlock(&handle->lock);
char *host = "sts.amazonaws.com";
char *aws_service = "sts";
char *method = "POST";
char *algorithm = "AWS4-HMAC-SHA256";
const EVP_MD *md = EVP_get_digestbyname("SHA256");
char *signed_headers = "content-length;content-type;host;x-amz-date";
str_builder_add_str(sb, "Action=");
str_builder_add_str(sb, action);
str_builder_add_str(sb, "&DurationSeconds=");
str_builder_add_str(sb, duration_sec);
str_builder_add_str(sb, "&RoleArn=");
str_builder_add_str(sb, role_arn);
str_builder_add_str(sb, "&RoleSessionName=");
str_builder_add_str(sb, role_session_name);
str_builder_add_str(sb, "&Version=");
str_builder_add_str(sb, version);
char *request_parameters = str_builder_dump(sb);
str_builder_clear(sb);
char content_length[256];
rd_snprintf(content_length, sizeof(content_length), "%zu", strlen(request_parameters));
str_builder_add_str(sb, "content-length:");
str_builder_add_str(sb, content_length);
str_builder_add_str(sb, "\n");
str_builder_add_str(sb, "content-type:application/x-www-form-urlencoded; charset=utf-8");
str_builder_add_str(sb, "\n");
str_builder_add_str(sb, "host:");
str_builder_add_str(sb, host);
str_builder_add_str(sb, "\n");
str_builder_add_str(sb, "x-amz-date:");
str_builder_add_str(sb, ymd);
str_builder_add_str(sb, "T");
str_builder_add_str(sb, hms);
str_builder_add_str(sb, "Z");
char *canonical_headers = str_builder_dump(sb);
str_builder_destroy(sb);
credential->aws_region = rd_strdup(handle_aws_region);
credential->md_lifetime_ms = now_wallclock_ms + conf->sasl.duration_sec * 1000;
int check = rd_kafka_aws_send_request(credential,
ymd,
hms,
host,
handle_aws_access_key_id,
handle_aws_secret_access_key,
handle_aws_security_token,
handle_aws_region,
aws_service,
method,
algorithm,
canonical_headers,
signed_headers,
request_parameters,
md);
if (r == -1) {
rd_kafka_sasl_aws_msk_iam_credential_free(credential);
}
RD_IF_FREE(handle_aws_access_key_id, rd_free);
RD_IF_FREE(handle_aws_secret_access_key, rd_free);
RD_IF_FREE(handle_aws_region, rd_free);
RD_IF_FREE(handle_aws_security_token, rd_free);
RD_IF_FREE(ymd, rd_free);
RD_IF_FREE(hms, rd_free);
RD_IF_FREE(role_session_name, rd_free);
RD_IF_FREE(role_arn, rd_free);
RD_IF_FREE(canonical_headers, rd_free);
RD_IF_FREE(request_parameters, rd_free);
return r;
}
/**
* @brief SASL/AWS_MSK_IAM credential refresher used for retrieving new temporary
* credentials from AWS STS service. The refresher will make use of the regional STS
* endpoints as per https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html.
*
* If STS is not used and permanent credentials are provided, the refresher essentially performs a NOOP
* and will not update the AWS credential information.
*/
static void
rd_kafka_aws_msk_iam_credential_refresh (rd_kafka_t *rk, void *opaque) {
char errstr[512];
rd_kafka_aws_credential_t credential = RD_ZERO_INIT;
rd_kafka_dbg(rk, SECURITY, "SASLAWSMSKIAM", "Refreshing AWS credentials");
if (rk->rk_conf.sasl.enable_use_sts) {
if (rd_kafka_aws_msk_iam_credential_refresh0(
rk, &credential,
rd_uclock() / 1000, errstr, sizeof(errstr)) == -1 ||
rd_kafka_aws_msk_iam_set_credential(
rk, credential.aws_access_key_id,
credential.aws_secret_access_key, credential.aws_region,
credential.aws_security_token, credential.md_lifetime_ms,
errstr, sizeof(errstr)) == -1) {
rd_kafka_aws_msk_iam_set_credential_failure(rk, errstr);
}
} else {
rd_kafka_dbg(rk, SECURITY, "SASLAWSMSKIAM", "Use STS not enabled, will not refresh credentials");
}
rd_kafka_sasl_aws_msk_iam_credential_free(&credential);
}
/**
* @brief Op callback for RD_KAFKA_OP_AWS_MSK_IAM_REFRESH
*
* @locality Application thread
*/
static rd_kafka_op_res_t
rd_kafka_aws_msk_iam_refresh_op (rd_kafka_t *rk,
rd_kafka_q_t *rkq,
rd_kafka_op_t *rko) {
/* The op callback is invoked when the op is destroyed via
* rd_kafka_op_destroy() or rd_kafka_event_destroy(), so
* make sure we don't refresh upon destruction since
* the op has already been handled by this point.
*/
rd_kafka_aws_msk_iam_credential_refresh(rk, rk->rk_conf.opaque);
return RD_KAFKA_OP_RES_HANDLED;
}
/**
* @brief Enqueue a credential refresh.
* @locks rwlock_wrlock(&handle->lock) MUST be held
*/
static void rd_kafka_aws_msk_iam_enqueue_credential_refresh (
rd_kafka_sasl_aws_msk_iam_handle_t *handle) {
rd_kafka_op_t *rko;
rko = rd_kafka_op_new_cb(handle->rk, RD_KAFKA_OP_AWS_MSK_IAM_REFRESH,
rd_kafka_aws_msk_iam_refresh_op);
rd_kafka_op_set_prio(rko, RD_KAFKA_PRIO_FLASH);
handle->wts_enqueued_refresh = rd_uclock();
rd_kafka_q_enq(handle->rk->rk_rep, rko);
}
/**
* @brief Enqueue a credential refresh if necessary.
*
* The method rd_kafka_aws_msk_iam_enqueue_credential_refresh() is invoked
* if necessary; the required lock is acquired and released. This method
* returns immediately when SASL/AWS_MSK_IAM is not in use by the client.
*/
static void
rd_kafka_aws_msk_iam_enqueue_credential_refresh_if_necessary (
rd_kafka_sasl_aws_msk_iam_handle_t *handle) {
rd_ts_t now_wallclock;
now_wallclock = rd_uclock();
rwlock_wrlock(&handle->lock);
if (handle->wts_refresh_after < now_wallclock &&
handle->wts_enqueued_refresh <= handle->wts_refresh_after) {
rd_kafka_aws_msk_iam_enqueue_credential_refresh(handle);
}
rwlock_wrunlock(&handle->lock);
}
/**
* @brief Build client first message
*
* Builds the first message for the payload
* by combining canonical request, signature, and credentials.
*
* @remark out->ptr is allocated and will need to be freed.
*/
static void
rd_kafka_sasl_aws_msk_iam_build_client_first_message (
rd_kafka_transport_t *rktrans,
rd_chariov_t *out) {
struct rd_kafka_sasl_aws_msk_iam_state *state = rktrans->rktrans_sasl.state;
char *aws_service = "kafka-cluster";
char *algorithm = "AWS4-HMAC-SHA256";
char *signed_headers = "host";
char *method = "GET";
char *request_parameters = "";
char *action = "kafka-cluster:Connect";
time_t t = time(&t);
struct tm *tmp = gmtime(&t); // must use UTC time
char *ymd = rd_malloc(sizeof(char) * 9);
char *hms = rd_malloc(sizeof(char) * 7);
strftime(ymd, sizeof(char) * 9, "%Y%m%d", tmp);
strftime(hms, sizeof(char) * 7, "%H%M%S", tmp);
char *canonical_querystring = rd_kafka_aws_build_sasl_canonical_querystring(
action,
state->aws_access_key_id,
state->aws_region,
ymd,
hms,
aws_service,
state->aws_security_token
);
str_builder_t *sb;
sb = str_builder_create();
str_builder_add_str(sb, "host:");
str_builder_add_str(sb, state->hostname);
char *canonical_headers = str_builder_dump(sb);
str_builder_destroy(sb);
char *sasl_payload = rd_kafka_aws_build_sasl_payload(ymd,
hms,
state->hostname,
state->aws_access_key_id,
state->aws_secret_access_key,
state->aws_security_token,
state->aws_region,
aws_service,
method,
algorithm,
canonical_headers,
canonical_querystring,
signed_headers,
request_parameters,
state->md);
rd_rkb_dbg(rktrans->rktrans_rkb, SECURITY,
"SASLAWSMSKIAM",
"SASL payload calculated as %s",
sasl_payload);
/* Save JSON to out pointer for sending */
out->size = strlen(sasl_payload);
out->ptr = rd_malloc(out->size + 1);
rd_snprintf(out->ptr, out->size + 1,
"%s", sasl_payload);
RD_IF_FREE(ymd, rd_free);
RD_IF_FREE(hms, rd_free);
RD_IF_FREE(canonical_querystring, rd_free);
RD_IF_FREE(canonical_headers, rd_free);
RD_IF_FREE(sasl_payload, rd_free);
}
/**
* @brief Handle server-response
*
* This is the end of authentication and the AWS MSK IAM state
* will be freed at the end of this function regardless of
* authentication outcome.
*
* @returns -1 on failure
*/
static int
rd_kafka_sasl_aws_msk_iam_handle_server_response (
rd_kafka_transport_t *rktrans,
const rd_chariov_t *in,
char *errstr, size_t errstr_size) {
if (in->size) {
rd_rkb_dbg(rktrans->rktrans_rkb, SECURITY | RD_KAFKA_DBG_BROKER, "SASLAWSMSKIAM",
"Received non-empty SASL AWS MSK IAM (builtin) "
"response from broker (%s)", in->ptr);
rd_kafka_sasl_auth_done(rktrans);
return 0;
} else {
rd_snprintf(errstr, errstr_size,
"SASL AWS MSK IAM authentication failed: "
"Broker response: %s", in->ptr);
return -1;
}
}
/**
* @brief SASL AWS MSK IAM client state machine
* @returns -1 on failure (errstr set), else 0.
*/
static int rd_kafka_sasl_aws_msk_iam_fsm (rd_kafka_transport_t *rktrans,
const rd_chariov_t *in,
char *errstr, size_t errstr_size) {
static const char *state_names[] = {
"client-first-message",
"server-response",
};
struct rd_kafka_sasl_aws_msk_iam_state *state = rktrans->rktrans_sasl.state;
rd_chariov_t out = RD_ZERO_INIT;
int r = -1;
rd_ts_t ts_start = rd_clock();
int prev_state = state->state;
rd_rkb_dbg(rktrans->rktrans_rkb, SECURITY | RD_KAFKA_DBG_BROKER, "SASLAWSMSKIAM",
"SASL AWS MSK IAM client in state %s",
state_names[state->state]);
switch (state->state)
{
case RD_KAFKA_SASL_AWS_MSK_IAM_SEND_CLIENT_FIRST_MESSAGE:
rd_assert(!in); /* Not expecting any server-input */
rd_kafka_sasl_aws_msk_iam_build_client_first_message(rktrans, &out);
state->state = RD_KAFKA_SASL_AWS_MSK_IAM_RECEIVE_SERVER_RESPONSE;
break;
case RD_KAFKA_SASL_AWS_MSK_IAM_RECEIVE_SERVER_RESPONSE:
rd_assert(in); /* Requires server-input */
r = rd_kafka_sasl_aws_msk_iam_handle_server_response(
rktrans, in, errstr, errstr_size);
break;
}
if (out.ptr) {
r = rd_kafka_sasl_send(rktrans, out.ptr, (int)out.size,
errstr, errstr_size);
RD_IF_FREE(out.ptr, rd_free);
}
ts_start = (rd_clock() - ts_start) / 1000;
if (ts_start >= 100) {
rd_rkb_dbg(rktrans->rktrans_rkb, SECURITY | RD_KAFKA_DBG_BROKER, "SASLAWSMSKIAM",
"SASL AWS MSK IAM state %s handled in %"PRId64"ms",
state_names[prev_state], ts_start);
}
return r;
}
/**
* @brief Handle received frame from broker.
*/
static int rd_kafka_sasl_aws_msk_iam_recv (rd_kafka_transport_t *rktrans,
const void *buf, size_t size,
char *errstr, size_t errstr_size) {
const rd_chariov_t in = { .ptr = (char *)buf, .size = size };
return rd_kafka_sasl_aws_msk_iam_fsm(rktrans, &in, errstr, errstr_size);
}
/**
* @brief Initialize and start SASL AWS MSK IAM (builtin) authentication.
*
* Returns 0 on successful init and -1 on error.
*
* @locality broker thread
*/
static int rd_kafka_sasl_aws_msk_iam_client_new (rd_kafka_transport_t *rktrans,
const char *hostname,
char *errstr, size_t errstr_size) {
rd_kafka_sasl_aws_msk_iam_handle_t *handle =
rktrans->rktrans_rkb->rkb_rk->rk_sasl.handle;
struct rd_kafka_sasl_aws_msk_iam_state *state;
const rd_kafka_conf_t *conf = &rktrans->rktrans_rkb->rkb_rk->rk_conf;
rd_rkb_dbg(rktrans->rktrans_rkb, SECURITY | RD_KAFKA_DBG_BROKER, "SASLAWSMSKIAM",
"SASL AWS MSK IAM new client initializing");
state = rd_calloc(1, sizeof(*state));
state->state = RD_KAFKA_SASL_AWS_MSK_IAM_SEND_CLIENT_FIRST_MESSAGE;
/*
* Save off the state structure now, before any possibility of
* returning, so that we will always free up the allocated memory in
* rd_kafka_sasl_aws_msk_iam_close().
*/
rktrans->rktrans_sasl.state = state;
/*
* Make sure we have a consistent view of the token and extensions
* throughout the authentication process -- even if it is refreshed
* midway through this particular authentication.
*/
rwlock_rdlock(&handle->lock);
if (!handle->aws_access_key_id || !handle->aws_secret_access_key || !handle->aws_region) {
rd_snprintf(errstr, errstr_size,
"AWS_MSK_IAM cannot log in because there "
"is no credentials available; last error: %s",
handle->errstr ?
handle->errstr : "(not available)");
rwlock_rdunlock(&handle->lock);
return -1;
}
state->hostname = (char *)hostname;
state->md = EVP_get_digestbyname("SHA256");
state->aws_access_key_id = rd_strdup(handle->aws_access_key_id);
state->aws_secret_access_key = rd_strdup(handle->aws_secret_access_key);
state->aws_region = rd_strdup(handle->aws_region);
if (conf->sasl.aws_security_token != NULL) {
state->aws_security_token = rd_strdup(handle->aws_security_token);
}
rwlock_rdunlock(&handle->lock);
/* Kick off the FSM */
return rd_kafka_sasl_aws_msk_iam_fsm(rktrans, NULL, errstr, errstr_size);
}
/**
* @brief Credential refresh timer callback.
*
* @locality rdkafka main thread
*/
static void
rd_kafka_sasl_aws_msk_iam_credential_refresh_tmr_cb (rd_kafka_timers_t *rkts,
void *arg) {
rd_kafka_t *rk = arg;
rd_kafka_sasl_aws_msk_iam_handle_t *handle = rk->rk_sasl.handle;
/* Enqueue a token refresh if necessary */
rd_kafka_aws_msk_iam_enqueue_credential_refresh_if_necessary(handle);
}
/**
* @brief Per-client-instance initializer
*/
static int rd_kafka_sasl_aws_msk_iam_init (rd_kafka_t *rk,
char *errstr, size_t errstr_size) {
rd_kafka_sasl_aws_msk_iam_handle_t *handle;
const rd_kafka_conf_t *conf = &rk->rk_conf;
rd_ts_t now_wallclock;
handle = rd_calloc(1, sizeof(*handle));
rk->rk_sasl.handle = handle;
rwlock_init(&handle->lock);
handle->rk = rk;
rd_kafka_timer_start(&rk->rk_timers, &handle->credential_refresh_tmr,
1 * 1000 * 1000,
rd_kafka_sasl_aws_msk_iam_credential_refresh_tmr_cb,
rk);
rd_kafka_dbg(rk, SECURITY, "SASLAWSMSKIAM", "Enqueuing credential refresh");
// Set initial handle creds which will be passed into *state in client_new()
/* Check if SASL/AWS_MSK_IAM is the configured auth mechanism */
if (rk->rk_conf.sasl.provider != &rd_kafka_sasl_aws_msk_iam_provider ||
!handle) {
rd_snprintf(errstr, errstr_size, "SASL/AWS_MSK_IAM is not the "
"configured authentication mechanism");
return RD_KAFKA_RESP_ERR__STATE;
}
now_wallclock = rd_uclock();
int refresh_sec = conf->sasl.duration_sec;
rd_ts_t wts_md_lifetime = (rd_ts_t)(now_wallclock + ((refresh_sec) * 1000 * 1000));
rwlock_wrlock(&handle->lock);
handle->aws_access_key_id = rd_strdup(conf->sasl.aws_access_key_id);
handle->aws_secret_access_key = rd_strdup(conf->sasl.aws_secret_access_key);
handle->aws_region = rd_strdup(conf->sasl.aws_region);
if (conf->sasl.aws_security_token != NULL) {
handle->aws_security_token = rd_strdup(conf->sasl.aws_security_token);
}
handle->wts_md_lifetime = wts_md_lifetime;
/* Schedule a refresh 80% through its remaining lifetime */
handle->wts_refresh_after =
(rd_ts_t)(now_wallclock + 0.8 *
(wts_md_lifetime - now_wallclock));
handle->errstr = NULL;
rwlock_wrunlock(&handle->lock);
return 0;
}
/**
* @brief Per-client-instance destructor
*/
static void rd_kafka_sasl_aws_msk_iam_term (rd_kafka_t *rk) {
rd_kafka_sasl_aws_msk_iam_handle_t *handle = rk->rk_sasl.handle;
if (!handle) {
return;
}
rk->rk_sasl.handle = NULL;
rd_kafka_timer_stop(&rk->rk_timers, &handle->credential_refresh_tmr, 1);
RD_IF_FREE(handle->aws_access_key_id, rd_free);
RD_IF_FREE(handle->aws_secret_access_key, rd_free);
RD_IF_FREE(handle->aws_region, rd_free);
RD_IF_FREE(handle->aws_security_token, rd_free);
RD_IF_FREE(handle->errstr, rd_free);
rwlock_destroy(&handle->lock);
rd_free(handle);
}
/**
* @brief Close and free authentication state
*/
static void rd_kafka_sasl_aws_msk_iam_close (rd_kafka_transport_t *rktrans) {
struct rd_kafka_sasl_aws_msk_iam_state *state =
rktrans->rktrans_sasl.state;
if (!state) {
return;
}
rd_free(state);
}
/**
* @brief Validate AWS MSK IAM config and look up the hash function
*/
static int rd_kafka_sasl_aws_msk_iam_conf_validate (rd_kafka_t *rk,
char *errstr,
size_t errstr_size) {
if (!rk->rk_conf.sasl.aws_access_key_id || !rk->rk_conf.sasl.aws_secret_access_key || !rk->rk_conf.sasl.aws_region) {
rd_snprintf(errstr, errstr_size,
"sasl.aws_access_key_id, sasl.aws_secret_access_key, and sasl.aws_region must be set");
return -1;
}
if (rk->rk_conf.sasl.enable_use_sts &&
(!rk->rk_conf.sasl.aws_security_token || !rk->rk_conf.sasl.role_arn || !rk->rk_conf.sasl.role_session_name)) {
rd_snprintf(errstr, errstr_size,
"sasl.enable_use_sts is true but missing sasl.aws_security_token or sasl.role_arn or sasl.role_session_name");
return -1;
}
return 0;
}
const struct rd_kafka_sasl_provider rd_kafka_sasl_aws_msk_iam_provider = {
.name = "AWS_MSK_IAM",
.init = rd_kafka_sasl_aws_msk_iam_init,
.term = rd_kafka_sasl_aws_msk_iam_term,
.client_new = rd_kafka_sasl_aws_msk_iam_client_new,
.recv = rd_kafka_sasl_aws_msk_iam_recv,
.close = rd_kafka_sasl_aws_msk_iam_close,
.conf_validate = rd_kafka_sasl_aws_msk_iam_conf_validate,
};
/**
* @name Unit tests
*/
int unittest_aws_msk_iam (void) {
int fails = 0;
return fails;
}
|
aha-app/librdkafka
|
src/rdkafka_aws.c
|
<gh_stars>0
/*
* librdkafka - The Apache Kafka C/C++ library
*
* Copyright (c) 2017 <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* AWS API utilities
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <curl/curl.h>
#include <libxml/parser.h>
#include "rdkafka_int.h"
#include "rdkafka_transport.h"
#include "rdkafka_transport_int.h"
#include "rdkafka_sasl.h"
#include "rdkafka_sasl_int.h"
#include "rdkafka_aws.h"
#include "rdstringbuilder.h"
#include "rdtypes.h"
#include "rdunittest.h"
#if WITH_SSL
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include <openssl/ossl_typ.h>
#else
#error "WITH_SSL (OpenSSL) is required for AWS API calls"
#endif
#define CHUNK_SIZE 2048
/**
* @struct Curl get in-memory buffer.
*/
typedef struct {
unsigned char *buffer;
size_t len;
size_t buflen;
} curl_in_mem_buf;
/**
* @brief Curl callback to write response contents
*/
static size_t rd_kafka_aws_curl_write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{
size_t realsize = size * nmemb;
curl_in_mem_buf *req = (curl_in_mem_buf *) userdata;
printf("receive chunk of %zu bytes\n", realsize);
while (req->buflen < req->len + realsize + 1)
{
req->buffer = realloc(req->buffer, req->buflen + CHUNK_SIZE);
req->buflen += CHUNK_SIZE;
}
memcpy(&req->buffer[req->len], ptr, realsize);
req->len += realsize;
req->buffer[req->len] = 0;
return realsize;
}
/**
* @brief Uri escapes a string
* @remark ret string will be allocated and must be freed.
*/
char *rd_kafka_aws_uri_encode (const char *in) {
char *ret;
int ret_len;
CURL *curl = curl_easy_init();
if (curl) {
char *encoded = curl_easy_escape(curl, in, (int)strlen(in));
ret_len = strlen(encoded)+1;
ret = rd_malloc(ret_len);
memcpy(ret, encoded, ret_len);
curl_free(encoded);
curl_easy_cleanup(curl);
return ret;
}
return NULL;
}
/**
* @brief HMAC_SHA256 encoding
*/
static unsigned char *rd_kafka_aws_hmac_sha256 (const void *key, int keylen,
const unsigned char *data, int datalen,
unsigned char *result, unsigned int *resultlen) {
return HMAC(EVP_sha256(), key, keylen, data, datalen, result, resultlen);
}
/**
* @brief constructs full date format of yyyymmddTHHMMssZ
* @remark amz_date_buf will be allocated and must be freed.
*/
static char *rd_kafka_aws_construct_amz_date (const char *ymd, const char *hms) {
int amz_date_size = strlen(ymd) + strlen(hms) + strlen("TZ") + 1;
char *amz_date_buf;
amz_date_buf = rd_malloc(amz_date_size);
rd_snprintf(amz_date_buf, amz_date_size, "%sT%sZ", ymd, hms);
return amz_date_buf;
}
/**
* @brief constructs authorization_header
* @remark authorization_header will be allocated and must be freed.
*/
static char *rd_kafka_aws_construct_authorization_header (const char *algorithm,
const char *aws_access_key_id,
const char *credential_scope,
const char *signed_headers,
const char *signature) {
str_builder_t *sb;
sb = str_builder_create();
str_builder_add_str(sb, algorithm);
str_builder_add_str(sb, " Credential=");
str_builder_add_str(sb, aws_access_key_id);
str_builder_add_str(sb, "/");
str_builder_add_str(sb, credential_scope);
str_builder_add_str(sb, ", SignedHeaders=");
str_builder_add_str(sb, signed_headers);
str_builder_add_str(sb, ", Signature=");
str_builder_add_str(sb, signature);
char *authorization_header = str_builder_dump(sb);
str_builder_destroy(sb);
return authorization_header;
}
/**
* @brief constructs credential_scope
* @remark credential_scope will be allocated and must be freed.
*/
static char *rd_kafka_aws_construct_credential_scope (const char *ymd,
const char *aws_region,
const char *aws_service) {
int credential_scope_size = strlen(ymd) + strlen(aws_region) + strlen(aws_service) + strlen("///aws4_request") + 1;
char *credential_scope;
credential_scope = rd_malloc(credential_scope_size);
rd_snprintf(credential_scope, credential_scope_size, "%s/%s/%s/aws4_request", ymd, aws_region, aws_service);
return credential_scope;
}
/**
* @brief Generates a canonical query string
* @remark canonical_query_string will be allocated and must be freed.
*/
char *rd_kafka_aws_build_sasl_canonical_querystring (const char *action,
const char *aws_access_key_id,
const char *aws_region,
const char *ymd,
const char *hms,
const char *aws_service,
const char *aws_security_token) {
char *uri_action = rd_kafka_aws_uri_encode(action);
char *credential_scope = rd_kafka_aws_construct_credential_scope(
ymd,
aws_region,
aws_service
);
str_builder_t *sb;
sb = str_builder_create();
str_builder_add_str(sb, aws_access_key_id);
str_builder_add_str(sb, "/");
str_builder_add_str(sb, credential_scope);
char *credential = str_builder_dump(sb);
str_builder_clear(sb);
char *uri_credential = rd_kafka_aws_uri_encode(credential);
char *amz_date = rd_kafka_aws_construct_amz_date(ymd, hms);
char *uri_amz_date = rd_kafka_aws_uri_encode(amz_date);
str_builder_add_str(sb, "Action=");
str_builder_add_str(sb, uri_action);
str_builder_add_str(sb, "&");
str_builder_add_str(sb, "X-Amz-Algorithm=AWS4-HMAC-SHA256&");
str_builder_add_str(sb, "X-Amz-Credential=");
str_builder_add_str(sb, uri_credential);
str_builder_add_str(sb, "&");
str_builder_add_str(sb, "X-Amz-Date=");
str_builder_add_str(sb, uri_amz_date);
str_builder_add_str(sb, "&");
str_builder_add_str(sb, "X-Amz-Expires=900&"); // AWS recommends 900 seconds
if (aws_security_token != NULL) {
char *uri_amz_security_token = rd_kafka_aws_uri_encode(aws_security_token);
str_builder_add_str(sb, "X-Amz-Security-Token=");
str_builder_add_str(sb, uri_amz_security_token);
str_builder_add_str(sb, "&");
RD_IF_FREE(uri_amz_security_token, rd_free);
}
str_builder_add_str(sb, "X-Amz-SignedHeaders=host");
char *canonical_query_string = str_builder_dump(sb);
str_builder_destroy(sb);
RD_IF_FREE(uri_action, rd_free);
RD_IF_FREE(credential_scope, rd_free);
RD_IF_FREE(credential, rd_free);
RD_IF_FREE(uri_credential, rd_free);
RD_IF_FREE(amz_date, rd_free);
RD_IF_FREE(uri_amz_date, rd_free);
return canonical_query_string;
}
/**
* @brief Generates a generic canonical request
* @remark canonical_request will be allocated and must be freed.
*/
static char *rd_kafka_aws_build_canonical_request (const char *hostname,
const char *method,
const char *canonical_query_string,
const char *canonical_headers,
const char *signed_headers,
const char *request_parameters,
const EVP_MD *md) {
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len, i;
EVP_MD_CTX *mdctx;
mdctx = EVP_MD_CTX_new();
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, request_parameters, strlen(request_parameters));
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_free(mdctx);
char payload_hash[65];
for (i = 0; i < md_len; i++)
sprintf(&(payload_hash[i * 2]), "%02x", md_value[i]); // save string in hex base 16
payload_hash[64] = '\0';
str_builder_t *sb;
sb = str_builder_create();
str_builder_add_str(sb, method);
str_builder_add_str(sb, "\n");
str_builder_add_str(sb, "/"); // canonical URI (usually "/")
str_builder_add_str(sb, "\n");
str_builder_add_str(sb, canonical_query_string);
str_builder_add_str(sb, "\n");
str_builder_add_str(sb, canonical_headers);
str_builder_add_str(sb, "\n\n");
str_builder_add_str(sb, signed_headers);
str_builder_add_str(sb, "\n");
str_builder_add_str(sb, payload_hash);
char *canonical_request = str_builder_dump(sb);
str_builder_destroy(sb);
return canonical_request;
}
/**
* @brief Generates a string_to_sign
* @remark string_to_sign will be allocated and must be freed.
*/
static char *rd_kafka_aws_build_string_to_sign (const char *algorithm,
const char *credential_scope,
const char *amz_date,
const char *canonical_request,
const EVP_MD *md) {
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len, i;
EVP_MD_CTX *mdctx;
mdctx = EVP_MD_CTX_new();
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, canonical_request, strlen(canonical_request));
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_free(mdctx);
char hashed_canonical_request[65];
for (i = 0; i < md_len; i++)
sprintf(&(hashed_canonical_request[i * 2]), "%02x", md_value[i]); // save string in hex base 16
hashed_canonical_request[64] = '\0';
str_builder_t *sb;
sb = str_builder_create();
str_builder_add_str(sb, algorithm);
str_builder_add_str(sb, "\n");
str_builder_add_str(sb, amz_date);
str_builder_add_str(sb, "\n");
str_builder_add_str(sb, credential_scope);
str_builder_add_str(sb, "\n");
str_builder_add_str(sb, hashed_canonical_request);
char *string_to_sign = str_builder_dump(sb);
str_builder_destroy(sb);
return string_to_sign;
}
/**
* @brief Generates a signature
* @remark signature will be allocated and must be freed.
*/
static char *rd_kafka_aws_build_signature (const char *aws_secret_access_key,
const char *aws_region,
const char *ymd,
const char *aws_service,
const char *string_to_sign) {
unsigned int i;
str_builder_t *sb;
sb = str_builder_create();
str_builder_add_str(sb, "AWS4");
str_builder_add_str(sb, aws_secret_access_key);
char *date_key = str_builder_dump(sb);
str_builder_destroy(sb);
unsigned char *hmac_date_key;
unsigned int hmac_date_key_len = 32;
hmac_date_key = rd_kafka_aws_hmac_sha256((unsigned char *)date_key, strlen(date_key), (unsigned char *)ymd, strlen(ymd), NULL, NULL);
unsigned char *hmac_date_region_key;
unsigned int hmac_date_region_key_len = 32;
hmac_date_region_key = rd_kafka_aws_hmac_sha256(hmac_date_key, hmac_date_key_len, (unsigned char *)aws_region, strlen(aws_region), NULL, NULL);
unsigned char *hmac_date_region_service_key;
unsigned int hmac_date_region_service_key_len = 32;
hmac_date_region_service_key = rd_kafka_aws_hmac_sha256(hmac_date_region_key, hmac_date_region_key_len, (unsigned char *)aws_service, strlen(aws_service), NULL, NULL);
unsigned char *hmac_signing_key;
unsigned int hmac_signing_key_len = 32;
hmac_signing_key = rd_kafka_aws_hmac_sha256(hmac_date_region_service_key, hmac_date_region_service_key_len, (unsigned char *)"aws4_request", strlen("aws4_request"), NULL, NULL);
unsigned char *hmac_signature;
unsigned int hmac_signature_len = 32;
hmac_signature = rd_kafka_aws_hmac_sha256(hmac_signing_key, hmac_signing_key_len, (unsigned char *)string_to_sign, strlen(string_to_sign), NULL, NULL);
char res_hexstring[65];
for (i = 0; i < hmac_signature_len; i++)
sprintf(&(res_hexstring[i * 2]), "%02x", hmac_signature[i]); // save string in hex base 16
res_hexstring[64] = '\0';
char *signature = rd_strdup(res_hexstring);
RD_IF_FREE(date_key, rd_free);
return signature;
}
int rd_kafka_aws_send_request (rd_kafka_aws_credential_t *credential,
const char *ymd,
const char *hms,
const char *host,
const char *aws_access_key_id,
const char *aws_secret_access_key,
const char *aws_security_token,
const char *aws_region,
const char *aws_service,
const char *method,
const char *algorithm,
const char *canonical_headers,
const char *signed_headers,
const char *request_parameters,
const EVP_MD *md) {
int r = 1;
char *canonical_request = rd_kafka_aws_build_canonical_request(
host,
method,
"",
canonical_headers,
signed_headers,
request_parameters,
md
);
char *credential_scope = rd_kafka_aws_construct_credential_scope(
ymd,
aws_region,
aws_service
);
char *amz_date = rd_kafka_aws_construct_amz_date(ymd, hms);
char *string_to_sign = rd_kafka_aws_build_string_to_sign(
algorithm,
credential_scope,
amz_date,
canonical_request,
md
);
char *signature = rd_kafka_aws_build_signature(
aws_secret_access_key,
aws_region,
ymd,
aws_service,
string_to_sign
);
char *authorization_header = rd_kafka_aws_construct_authorization_header(
algorithm,
aws_access_key_id,
credential_scope,
signed_headers,
signature
);
CURL *curl;
CURLcode res;
curl = curl_easy_init();
curl_in_mem_buf req = {.buffer = NULL, .len = 0, .buflen = 0};
if (curl) {
str_builder_t *sb;
sb = str_builder_create();
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method);
str_builder_add_str(sb, "https://");
str_builder_add_str(sb, host);
char *curl_host = str_builder_dump(sb);
str_builder_clear(sb);
curl_easy_setopt(curl, CURLOPT_URL, curl_host);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
req.buffer = rd_malloc(CHUNK_SIZE);
req.buflen = CHUNK_SIZE;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rd_kafka_aws_curl_write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&req);
/* Set Curl data */
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request_parameters);
// /* Set Curl headers */
struct curl_slist *headers = NULL;
str_builder_add_str(sb, "Host: ");
str_builder_add_str(sb, host);
char *curl_host_header = str_builder_dump(sb);
str_builder_clear(sb);
headers = curl_slist_append(headers, curl_host_header);
headers = curl_slist_append(headers, "User-Agent: librdkafka");
char content_length[256];
rd_snprintf(content_length, sizeof(content_length), "%zu", strlen(request_parameters));
str_builder_add_str(sb, "Content-Length: ");
str_builder_add_str(sb, content_length);
char *curl_content_length_header = str_builder_dump(sb);
str_builder_clear(sb);
headers = curl_slist_append(headers, curl_content_length_header);
headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded; charset=utf-8");
str_builder_add_str(sb, "Authorization: ");
str_builder_add_str(sb, authorization_header);
char *curl_auth_header = str_builder_dump(sb);
str_builder_clear(sb);
headers = curl_slist_append(headers, curl_auth_header);
str_builder_add_str(sb, "X-Amz-Date: ");
str_builder_add_str(sb, amz_date);
char *curl_amz_date_header = str_builder_dump(sb);
str_builder_clear(sb);
headers = curl_slist_append(headers, curl_amz_date_header);
headers = curl_slist_append(headers, "Accept-Encoding: gzip");
char *curl_amz_security_token_header = NULL;
if (aws_security_token != NULL) {
str_builder_add_str(sb, "X-Amz-Security-Token: ");
str_builder_add_str(sb, aws_security_token);
curl_amz_security_token_header = str_builder_dump(sb);
str_builder_clear(sb);
headers = curl_slist_append(headers, curl_amz_security_token_header);
}
str_builder_destroy(sb);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
/* add errstr handling */
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
return -1;
}
xmlDoc *document;
xmlNode *cur;
document = xmlReadMemory(req.buffer, req.len, "assume_role_response.xml", NULL, 0);
if (document == NULL) {
/* add errstr handling */
fprintf(stderr, "Failed to parse document\n");
// return -1;
}
cur = xmlDocGetRootElement(document);
cur = cur->children;
while (cur != NULL) {
if ((!xmlStrcmp(cur->name, (const xmlChar *)"AssumeRoleResult"))) {
break;
}
cur = cur->next;
}
cur = cur->children;
while (cur != NULL) {
if ((!xmlStrcmp(cur->name, (const xmlChar *)"Credentials"))) {
break;
}
cur = cur->next;
}
cur = cur->children;
while (cur != NULL) {
if ((!xmlStrcmp(cur->name, (const xmlChar *)"AccessKeyId"))) {
xmlChar *content = xmlNodeListGetString(document, cur->children, 1);
credential->aws_access_key_id = rd_strdup((const char *)content);
xmlFree(content);
}
if ((!xmlStrcmp(cur->name, (const xmlChar *)"SecretAccessKey"))) {
xmlChar *content = xmlNodeListGetString(document, cur->children, 1);
credential->aws_secret_access_key = rd_strdup((const char *)content);
xmlFree(content);
}
if ((!xmlStrcmp(cur->name, (const xmlChar *)"SessionToken"))) {
xmlChar *content = xmlNodeListGetString(document, cur->children, 1);
credential->aws_security_token = rd_strdup((const char *)content);
xmlFree(content);
}
cur = cur->next;
}
xmlFreeDoc(document);
xmlCleanupParser();
rd_free(req.buffer);
rd_free(curl_host);
rd_free(curl_host_header);
rd_free(curl_content_length_header);
rd_free(curl_auth_header);
rd_free(curl_amz_date_header);
RD_IF_FREE(curl_amz_security_token_header, rd_free);
}
curl_easy_cleanup(curl);
return r;
}
/**
* @brief Generates a sasl_payload
* @remark sasl_payload will be allocated and must be freed.
*/
char *rd_kafka_aws_build_sasl_payload (const char *ymd,
const char *hms,
const char *host,
const char *aws_access_key_id,
const char *aws_secret_access_key,
const char *aws_security_token,
const char *aws_region,
const char *aws_service,
const char *method,
const char *algorithm,
const char *canonical_headers,
const char *canonical_querystring,
const char *signed_headers,
const char *request_parameters,
const EVP_MD *md) {
char *canonical_request = rd_kafka_aws_build_canonical_request(
host,
method,
canonical_querystring,
canonical_headers,
signed_headers,
request_parameters,
md
);
char *credential_scope = rd_kafka_aws_construct_credential_scope(
ymd,
aws_region,
aws_service
);
char *amz_date = rd_kafka_aws_construct_amz_date(ymd, hms);
char *string_to_sign = rd_kafka_aws_build_string_to_sign(
algorithm,
credential_scope,
amz_date,
canonical_request,
md
);
char *signature = rd_kafka_aws_build_signature(
aws_secret_access_key,
aws_region,
ymd,
aws_service,
string_to_sign
);
/* Construct JSON payload */
str_builder_t *sb;
sb = str_builder_create();
str_builder_add_str(sb, "{\"version\":\"2020_10_22\",");
str_builder_add_str(sb, "\"host\":\"");
str_builder_add_str(sb, host);
str_builder_add_str(sb, "\",");
str_builder_add_str(sb, "\"user-agent\":\"librdkafka\",");
str_builder_add_str(sb, "\"action\":\"");
str_builder_add_str(sb, "kafka-cluster:Connect");
str_builder_add_str(sb, "\",");
str_builder_add_str(sb, "\"x-amz-algorithm\":\"AWS4-HMAC-SHA256\",");
str_builder_add_str(sb, "\"x-amz-credential\":\"");
str_builder_add_str(sb, aws_access_key_id);
str_builder_add_str(sb, "/");
str_builder_add_str(sb, credential_scope);
str_builder_add_str(sb, "\",");
str_builder_add_str(sb, "\"x-amz-date\":\"");
str_builder_add_str(sb, amz_date);
str_builder_add_str(sb, "\",");
if (aws_security_token != NULL) {
str_builder_add_str(sb, "\"x-amz-security-token\":\"");
str_builder_add_str(sb, aws_security_token);
str_builder_add_str(sb, "\",");
}
str_builder_add_str(sb, "\"x-amz-signedheaders\":\"host\",");
str_builder_add_str(sb, "\"x-amz-expires\":\"900\",");
str_builder_add_str(sb, "\"x-amz-signature\":\"");
str_builder_add_str(sb, signature);
str_builder_add_str(sb, "\"}");
char *sasl_payload = str_builder_dump(sb);
str_builder_destroy(sb);
RD_IF_FREE(canonical_request, rd_free);
RD_IF_FREE(amz_date, rd_free);
RD_IF_FREE(credential_scope, rd_free);
RD_IF_FREE(string_to_sign, rd_free);
RD_IF_FREE(signature, rd_free);
return sasl_payload;
}
/**
* @name Unit tests
*/
/**
* @brief Verify that a sasl payload JSON can be formed properly.
*/
static int unittest_build_sasl_payload (void) {
RD_UT_BEGIN();
const EVP_MD *md = EVP_get_digestbyname("SHA256");
char *ymd = "20100101";
char *hms = "000000";
char *aws_region = "us-east-1";
char *aws_service = "kafka-cluster";
char *aws_access_key_id = "AWS_ACCESS_KEY_ID";
char *aws_secret_access_key = "AWS_SECRET_ACCESS_KEY";
char *aws_security_token = NULL;
char *algorithm = "AWS4-HMAC-SHA256";
char *canonical_headers = "host:hostname";
char *signed_headers = "host";
char *host = "hostname";
char *method = "GET";
char *request_parameters = "";
char *canonical_querystring = rd_kafka_aws_build_sasl_canonical_querystring(
"kafka-cluster:Connect",
aws_access_key_id,
aws_region,
ymd,
hms,
aws_service,
aws_security_token
);
char *expected_canonical_querystring = "Action=kafka-cluster%3AConnect&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AWS_ACCESS_KEY_ID%2F20100101%2Fus-east-1%2Fkafka-cluster%2Faws4_request&X-Amz-Date=20100101T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host";
RD_UT_ASSERT(strcmp(expected_canonical_querystring, canonical_querystring) == 0, "expected: %s\nactual: %s", expected_canonical_querystring, canonical_querystring);
char *sasl_payload = rd_kafka_aws_build_sasl_payload(
ymd,
hms,
host,
aws_access_key_id,
aws_secret_access_key,
aws_security_token,
aws_region,
aws_service,
method,
algorithm,
canonical_headers,
canonical_querystring,
signed_headers,
request_parameters,
md
);
const char *expected =
"{\"version\":\"2020_10_22\",\"host\":\"hostname\","
"\"user-agent\":\"librdkafka\",\"action\":\"kafka-cluster:Connect\","
"\"x-amz-algorithm\":\"AWS4-HMAC-SHA256\","
"\"x-amz-credential\":\"AWS_ACCESS_KEY_ID/20100101/us-east-1/kafka-cluster/aws4_request\","
"\"x-amz-date\":\"20100101T000000Z\","
"\"x-amz-signedheaders\":\"host\","
"\"x-amz-expires\":\"900\","
"\"x-amz-signature\":\"d3eeeddfb2c2b76162d583d7499c2364eb9a92b248218e31866659b18997ef44\"}";
RD_UT_ASSERT(strcmp(expected, sasl_payload) == 0, "expected: %s\nactual: %s", expected, sasl_payload);
RD_IF_FREE(sasl_payload, rd_free);
RD_UT_PASS();
}
/**
* @brief Verify that a request JSON can be formed properly.
*/
static int unittest_build_sts_request (void) {
RD_UT_BEGIN();
const EVP_MD *md = EVP_get_digestbyname("SHA256");
char *ymd = "20210910";
char *hms = "190714";
char *aws_region = "us-east-1";
char *aws_service = "sts";
char *aws_access_key_id = "TESTKEY";
char *aws_secret_access_key = "TESTSECRET";
char *algorithm = "AWS4-HMAC-SHA256";
char *canonical_headers = "content-length:171\ncontent-type:application/x-www-form-urlencoded; charset=utf-8\nhost:sts.amazonaws.com\nx-amz-date:20210910T190714Z";
char *signed_headers = "content-length;content-type;host;x-amz-date";
char *host = "sts.amazonaws.com";
char *method = "POST";
char *canonical_querystring = "";
char *request_parameters = "Action=AssumeRole&DurationSeconds=900&RoleArn=arn%3Aaws%3Aiam%3A%3A789750736714%3Arole%2FIdentity_Account_Access_Role&RoleSessionName=librdkafka_session&Version=2011-06-15";
char *canonical_request = rd_kafka_aws_build_canonical_request(
host,
method,
canonical_querystring,
canonical_headers,
signed_headers,
request_parameters,
md
);
// printf("DEBUGGING: canonical request\n%s\n", canonical_request);
char *expected_canonical_request = "POST\n/\n\ncontent-length:171\ncontent-type:application/x-www-form-urlencoded; charset=utf-8\nhost:sts.amazonaws.com\nx-amz-date:20210910T190714Z\n\ncontent-length;content-type;host;x-amz-date\n452ff5eb28a9cd9928d29dd4e27815e5e4f0f3e8e7e59b37700f55584f43ffaa";
RD_UT_ASSERT(strcmp(canonical_request, expected_canonical_request) == 0, "expected: %s\nactual: %s", expected_canonical_request, canonical_request);
char *credential_scope = rd_kafka_aws_construct_credential_scope(
ymd,
aws_region,
aws_service
);
char *expected_credential_scope = "20210910/us-east-1/sts/aws4_request";
RD_UT_ASSERT(strcmp(credential_scope, expected_credential_scope) == 0, "expected: %s\nactual: %s", expected_credential_scope, credential_scope);
char *amz_date = rd_kafka_aws_construct_amz_date(ymd, hms);
char *string_to_sign = rd_kafka_aws_build_string_to_sign(
algorithm,
credential_scope,
amz_date,
canonical_request,
md
);
// printf("DEBUGGING: string to sign\n%s\n", string_to_sign);
char *expected_string_to_sign = "AWS4-HMAC-SHA256\n20210910T190714Z\n20210910/us-east-1/sts/aws4_request\nd66dff688ce93a268731fee21e3751669e2c27b8b54ce6d2d627b2c6f7049a7f";
RD_UT_ASSERT(strcmp(string_to_sign, expected_string_to_sign) == 0, "expected: %s\nactual: %s", expected_string_to_sign, string_to_sign);
char *signature = rd_kafka_aws_build_signature(
aws_secret_access_key,
aws_region,
ymd,
aws_service,
string_to_sign
);
// printf("DEBUGGING: signature\n%s\n", signature);
char *expected_signature = "a825a6136b83c3feb7993b9d2947f6e479901f805089b08f717c0f2a03cd98f0";
RD_UT_ASSERT(strcmp(signature, expected_signature) == 0, "expected: %s\nactual: %s", expected_signature, signature);
char *authorization_header = rd_kafka_aws_construct_authorization_header(
algorithm,
aws_access_key_id,
credential_scope,
signed_headers,
signature
);
char *expected_authorization_header = "AWS4-HMAC-SHA256 Credential=TESTKEY/20210910/us-east-1/sts/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=a825a6136b83c3feb7993b9d2947f6e479901f805089b08f717c0f2a03cd98f0";
RD_UT_ASSERT(strcmp(authorization_header, expected_authorization_header) == 0, "expected: %s\nactual: %s", expected_authorization_header, authorization_header);
RD_IF_FREE(canonical_request, rd_free);
RD_IF_FREE(string_to_sign, rd_free);
RD_IF_FREE(signature, rd_free);
RD_IF_FREE(authorization_header, rd_free);
RD_IF_FREE(credential_scope, rd_free);
RD_IF_FREE(amz_date, rd_free);
RD_UT_PASS();
}
/**
* @brief Verify that a signature can be calculated properly.
*/
static int unittest_build_signature (void) {
RD_UT_BEGIN();
const EVP_MD *md = EVP_get_digestbyname("SHA256");
char *ymd = "20100101";
char *hms = "000000";
char *aws_region = "us-east-1";
char *aws_service = "kafka-cluster";
char *aws_secret_access_key = "AWS_SECRET_ACCESS_KEY";
char *algorithm = "AWS4-HMAC-SHA256";
char *canonical_headers = "host:hostname";
char *signed_headers = "host";
char *host = "hostname";
char *method = "GET";
char *canonical_querystring = "Action=kafka-cluster%3AConnect&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AWS_ACCESS_KEY_ID%2F20100101%2Fus-east-1%2Fkafka-cluster%2Faws4_request&X-Amz-Date=20100101T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host";
char *request_parameters = "";
char *canonical_request = rd_kafka_aws_build_canonical_request(
host,
method,
canonical_querystring,
canonical_headers,
signed_headers,
request_parameters,
md
);
char *credential_scope = rd_kafka_aws_construct_credential_scope(
ymd,
aws_region,
aws_service
);
char *expected_credential_scope = "20100101/us-east-1/kafka-cluster/aws4_request";
RD_UT_ASSERT(strcmp(credential_scope, expected_credential_scope) == 0, "expected: %s\nactual: %s", expected_credential_scope, credential_scope);
char *amz_date = rd_kafka_aws_construct_amz_date(ymd, hms);
char *string_to_sign = rd_kafka_aws_build_string_to_sign(
algorithm,
credential_scope,
amz_date,
canonical_request,
md
);
// printf("DEBUGGING: string to sign\n%s\n", string_to_sign);
char *expected_string_to_sign = "AWS4-HMAC-SHA256\n20100101T000000Z\n20100101/us-east-1/kafka-cluster/aws4_request\n8a719fb6d4b33f7d9c5b25b65af85a44d3627bdca66e1287b1a366fa90bafaa1";
RD_UT_ASSERT(strcmp(string_to_sign, expected_string_to_sign) == 0, "expected: %s\nactual: %s", expected_string_to_sign, string_to_sign);
char *signature = rd_kafka_aws_build_signature(
aws_secret_access_key,
aws_region,
ymd,
aws_service,
string_to_sign
);
const char *expected = "d3eeeddfb2c2b76162d583d7499c2364eb9a92b248218e31866659b18997ef44";
RD_UT_ASSERT(strcmp(expected, signature) == 0, "expected: %s\nactual: %s", expected, signature);
RD_IF_FREE(canonical_request, rd_free);
RD_IF_FREE(string_to_sign, rd_free);
RD_IF_FREE(signature, rd_free);
RD_IF_FREE(credential_scope, rd_free);
RD_IF_FREE(amz_date, rd_free);
RD_UT_PASS();
}
/**
* @brief Verify that a canonical request can be formed properly.
*/
static int unittest_build_canonical_request_with_security_token (void) {
RD_UT_BEGIN();
const EVP_MD *md = EVP_get_digestbyname("SHA256");
char *canonical_headers = "host:hostname";
char *signed_headers = "host";
char *host = "hostname";
char *method = "GET";
char *canonical_querystring = "Action=kafka-cluster%3AConnect&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AWS_ACCESS_KEY_ID%2F20100101%2Fus-east-1%2Fkafka-cluster%2Faws4_request&X-Amz-Date=20100101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=security-token&X-Amz-SignedHeaders=host";
char *request_parameters = "";
char *canonical_request = rd_kafka_aws_build_canonical_request(
host,
method,
canonical_querystring,
canonical_headers,
signed_headers,
request_parameters,
md
);
const char *expected =
"GET\n/\n"
"Action=kafka-cluster%3AConnect&"
"X-Amz-Algorithm=AWS4-HMAC-SHA256&"
"X-Amz-Credential=AWS_ACCESS_KEY_ID%2F20100101%2Fus-east-1%2Fkafka-cluster%2Faws4_request&"
"X-Amz-Date=20100101T000000Z&"
"X-Amz-Expires=900&"
"X-Amz-Security-Token=security-token&"
"X-Amz-SignedHeaders=host\n"
"host:hostname\n\n"
"host\n"
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
RD_UT_ASSERT(strcmp(expected, canonical_request) == 0, "expected: %s\nactual: %s", expected, canonical_request);
RD_IF_FREE(canonical_request, rd_free);
RD_UT_PASS();
}
/**
* @brief Verify that a canonical request can be formed properly.
*/
static int unittest_build_canonical_request (void) {
RD_UT_BEGIN();
const EVP_MD *md = EVP_get_digestbyname("SHA256");
char *canonical_headers = "host:hostname";
char *signed_headers = "host";
char *host = "hostname";
char *method = "GET";
char *canonical_querystring = "Action=kafka-cluster%3AConnect&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AWS_ACCESS_KEY_ID%2F20100101%2Fus-east-1%2Fkafka-cluster%2Faws4_request&X-Amz-Date=20100101T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host";
char *request_parameters = "";
char *canonical_request = rd_kafka_aws_build_canonical_request(
host,
method,
canonical_querystring,
canonical_headers,
signed_headers,
request_parameters,
md
);
const char *expected =
"GET\n/\n"
"Action=kafka-cluster%3AConnect&"
"X-Amz-Algorithm=AWS4-HMAC-SHA256&"
"X-Amz-Credential=AWS_ACCESS_KEY_ID%2F20100101%2Fus-east-1%2Fkafka-cluster%2Faws4_request&"
"X-Amz-Date=20100101T000000Z&"
"X-Amz-Expires=900&"
"X-Amz-SignedHeaders=host\n"
"host:hostname\n\n"
"host\n"
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
RD_UT_ASSERT(strcmp(expected, canonical_request) == 0, "expected: %s\nactual: %s", expected, canonical_request);
RD_IF_FREE(canonical_request, rd_free);
RD_UT_PASS();
}
/**
* @brief Verify that a uri encoding / escaping works as expected.
*/
static int unittest_uri_encode (void) {
RD_UT_BEGIN();
int test_str_size = strlen("testString-123/*&") + 1;
char *test_str;
test_str = rd_malloc(test_str_size);
rd_snprintf(test_str, test_str_size, "testString-123/*&");
char *retval = rd_kafka_aws_uri_encode(test_str);
const char *expected = "testString-123%2F%2A%26";
RD_UT_ASSERT(strcmp(expected, retval) == 0, "expected: %s\nactual: %s", expected, retval);
RD_IF_FREE(retval, rd_free);
RD_IF_FREE(test_str, rd_free);
RD_UT_PASS();
}
int unittest_aws (void) {
int fails = 0;
fails += unittest_uri_encode();
fails += unittest_build_canonical_request();
fails += unittest_build_canonical_request_with_security_token();
fails += unittest_build_signature();
fails += unittest_build_sasl_payload();
fails += unittest_build_sts_request();
return fails;
}
|
aha-app/librdkafka
|
src/rdkafka_conf.h
|
/*
* librdkafka - Apache Kafka C library
*
* Copyright (c) 2014-2018 <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _RDKAFKA_CONF_H_
#define _RDKAFKA_CONF_H_
#include "rdlist.h"
#include "rdkafka_cert.h"
#if WITH_SSL && OPENSSL_VERSION_NUMBER >= 0x10100000
#include <openssl/engine.h>
#endif /* WITH_SSL && OPENSSL_VERSION_NUMBER >= 0x10100000 */
/**
* Forward declarations
*/
struct rd_kafka_transport_s;
/**
* MessageSet compression codecs
*/
typedef enum {
RD_KAFKA_COMPRESSION_NONE,
RD_KAFKA_COMPRESSION_GZIP = RD_KAFKA_MSG_ATTR_GZIP,
RD_KAFKA_COMPRESSION_SNAPPY = RD_KAFKA_MSG_ATTR_SNAPPY,
RD_KAFKA_COMPRESSION_LZ4 = RD_KAFKA_MSG_ATTR_LZ4,
RD_KAFKA_COMPRESSION_ZSTD = RD_KAFKA_MSG_ATTR_ZSTD,
RD_KAFKA_COMPRESSION_INHERIT, /* Inherit setting from global conf */
RD_KAFKA_COMPRESSION_NUM
} rd_kafka_compression_t;
static RD_INLINE RD_UNUSED const char *
rd_kafka_compression2str (rd_kafka_compression_t compr) {
static const char *names[RD_KAFKA_COMPRESSION_NUM] = {
[RD_KAFKA_COMPRESSION_NONE] = "none",
[RD_KAFKA_COMPRESSION_GZIP] = "gzip",
[RD_KAFKA_COMPRESSION_SNAPPY] = "snappy",
[RD_KAFKA_COMPRESSION_LZ4] = "lz4",
[RD_KAFKA_COMPRESSION_ZSTD] = "zstd",
[RD_KAFKA_COMPRESSION_INHERIT] = "inherit"
};
static RD_TLS char ret[32];
if ((int)compr < 0 || compr >= RD_KAFKA_COMPRESSION_NUM) {
rd_snprintf(ret, sizeof(ret),
"codec0x%x?", (int)compr);
return ret;
}
return names[compr];
}
/**
* MessageSet compression levels
*/
typedef enum {
RD_KAFKA_COMPLEVEL_DEFAULT = -1,
RD_KAFKA_COMPLEVEL_MIN = -1,
RD_KAFKA_COMPLEVEL_GZIP_MAX = 9,
RD_KAFKA_COMPLEVEL_LZ4_MAX = 12,
RD_KAFKA_COMPLEVEL_SNAPPY_MAX = 0,
RD_KAFKA_COMPLEVEL_ZSTD_MAX = 22,
RD_KAFKA_COMPLEVEL_MAX = 12
} rd_kafka_complevel_t;
typedef enum {
RD_KAFKA_PROTO_PLAINTEXT,
RD_KAFKA_PROTO_SSL,
RD_KAFKA_PROTO_SASL_PLAINTEXT,
RD_KAFKA_PROTO_SASL_SSL,
RD_KAFKA_PROTO_NUM,
} rd_kafka_secproto_t;
typedef enum {
RD_KAFKA_CONFIGURED,
RD_KAFKA_LEARNED,
RD_KAFKA_INTERNAL,
RD_KAFKA_LOGICAL
} rd_kafka_confsource_t;
static RD_INLINE RD_UNUSED
const char *rd_kafka_confsource2str (rd_kafka_confsource_t source) {
static const char *names[] = {
"configured",
"learned",
"internal",
"logical"
};
return names[source];
}
typedef enum {
_RK_GLOBAL = 0x1,
_RK_PRODUCER = 0x2,
_RK_CONSUMER = 0x4,
_RK_TOPIC = 0x8,
_RK_CGRP = 0x10,
_RK_DEPRECATED = 0x20,
_RK_HIDDEN = 0x40,
_RK_HIGH = 0x80, /* High Importance */
_RK_MED = 0x100, /* Medium Importance */
_RK_EXPERIMENTAL = 0x200, /* Experimental (unsupported) property */
_RK_SENSITIVE = 0x400 /* The configuration property's value
* might contain sensitive information. */
} rd_kafka_conf_scope_t;
/**< While the client groups is a generic concept, it is currently
* only implemented for consumers in librdkafka. */
#define _RK_CGRP _RK_CONSUMER
typedef enum {
_RK_CONF_PROP_SET_REPLACE, /* Replace current value (default) */
_RK_CONF_PROP_SET_ADD, /* Add value (S2F) */
_RK_CONF_PROP_SET_DEL /* Remove value (S2F) */
} rd_kafka_conf_set_mode_t;
typedef enum {
RD_KAFKA_OFFSET_METHOD_NONE,
RD_KAFKA_OFFSET_METHOD_FILE,
RD_KAFKA_OFFSET_METHOD_BROKER
} rd_kafka_offset_method_t;
typedef enum {
RD_KAFKA_SSL_ENDPOINT_ID_NONE,
RD_KAFKA_SSL_ENDPOINT_ID_HTTPS, /**< RFC2818 */
} rd_kafka_ssl_endpoint_id_t;
/* Increase in steps of 64 as needed.
* This must be larger than sizeof(rd_kafka_[topic_]conf_t) */
#define RD_KAFKA_CONF_PROPS_IDX_MAX (64*36)
/**
* @struct rd_kafka_anyconf_t
* @brief The anyconf header must be the first field in the
* rd_kafka_conf_t and rd_kafka_topic_conf_t structs.
* It provides a way to track which property has been modified.
*/
struct rd_kafka_anyconf_hdr {
uint64_t modified[RD_KAFKA_CONF_PROPS_IDX_MAX/64];
};
/**
* Optional configuration struct passed to rd_kafka_new*().
*
* The struct is populated ted through string properties
* by calling rd_kafka_conf_set().
*
*/
struct rd_kafka_conf_s {
struct rd_kafka_anyconf_hdr hdr; /**< Must be first field */
/*
* Generic configuration
*/
int enabled_events;
int max_msg_size;
int msg_copy_max_size;
int recv_max_msg_size;
int max_inflight;
int metadata_request_timeout_ms;
int metadata_refresh_interval_ms;
int metadata_refresh_fast_cnt;
int metadata_refresh_fast_interval_ms;
int metadata_refresh_sparse;
int metadata_max_age_ms;
int metadata_propagation_max_ms;
int debug;
int broker_addr_ttl;
int broker_addr_family;
int socket_timeout_ms;
int socket_blocking_max_ms;
int socket_sndbuf_size;
int socket_rcvbuf_size;
int socket_keepalive;
int socket_nagle_disable;
int socket_max_fails;
char *client_id_str;
char *brokerlist;
int stats_interval_ms;
int term_sig;
int reconnect_backoff_ms;
int reconnect_backoff_max_ms;
int reconnect_jitter_ms;
int connections_max_idle_ms;
int sparse_connections;
int sparse_connect_intvl;
int api_version_request;
int api_version_request_timeout_ms;
int api_version_fallback_ms;
char *broker_version_fallback;
rd_kafka_secproto_t security_protocol;
struct {
#if WITH_SSL
SSL_CTX *ctx;
#endif
char *cipher_suites;
char *curves_list;
char *sigalgs_list;
char *key_location;
char *key_pem;
rd_kafka_cert_t *key;
char *key_password;
char *cert_location;
char *cert_pem;
rd_kafka_cert_t *cert;
char *ca_location;
rd_kafka_cert_t *ca;
/** CSV list of Windows certificate stores */
char *ca_cert_stores;
char *crl_location;
#if WITH_SSL && OPENSSL_VERSION_NUMBER >= 0x10100000
ENGINE *engine;
#endif
char *engine_location;
char *engine_id;
void *engine_callback_data;
char *keystore_location;
char *keystore_password;
int endpoint_identification;
int enable_verify;
int (*cert_verify_cb) (rd_kafka_t *rk,
const char *broker_name,
int32_t broker_id,
int *x509_error,
int depth,
const char *buf, size_t size,
char *errstr, size_t errstr_size,
void *opaque);
} ssl;
struct {
const struct rd_kafka_sasl_provider *provider;
char *principal;
char *mechanisms;
char *service_name;
char *kinit_cmd;
char *keytab;
int relogin_min_time;
char *username;
char *password;
#if WITH_SASL_SCRAM
/* SCRAM EVP-wrapped hash function
* (return value from EVP_shaX()) */
const void/*EVP_MD*/ *scram_evp;
/* SCRAM direct hash function (e.g., SHA256()) */
unsigned char *(*scram_H) (const unsigned char *d, size_t n,
unsigned char *md);
/* Hash size */
size_t scram_H_size;
#endif
#if WITH_SASL_AWS_MSK_IAM
/* AWS credentials for SASL auth
* (standard toolchain not available in librdkafka) */
char *aws_access_key_id;
char *aws_secret_access_key;
char *aws_region;
int enable_use_sts;
char *aws_security_token; /* needed for STS AssumeRole */
char *role_arn; /* needed for STS AssumeRole */
char *role_session_name; /* needed for STS AssumeRole */
int duration_sec; /* needed for STS AssumeRole, defaults to 900 if not set */
/* SASL/AWS_MSK_IAM credential refresh event callback */
#endif
char *oauthbearer_config;
int enable_oauthbearer_unsecure_jwt;
/* SASL/OAUTHBEARER token refresh event callback */
void (*oauthbearer_token_refresh_cb) (
rd_kafka_t *rk,
const char *oauthbearer_config,
void *opaque);
} sasl;
char *plugin_paths;
#if WITH_PLUGINS
rd_list_t plugins;
#endif
/* Interceptors */
struct {
/* rd_kafka_interceptor_method_t lists */
rd_list_t on_conf_set; /* on_conf_set interceptors
* (not copied on conf_dup()) */
rd_list_t on_conf_dup; /* .. (not copied) */
rd_list_t on_conf_destroy; /* .. (not copied) */
rd_list_t on_new; /* .. (copied) */
rd_list_t on_destroy; /* .. (copied) */
rd_list_t on_send; /* .. (copied) */
rd_list_t on_acknowledgement; /* .. (copied) */
rd_list_t on_consume; /* .. (copied) */
rd_list_t on_commit; /* .. (copied) */
rd_list_t on_request_sent; /* .. (copied) */
rd_list_t on_response_received;/* .. (copied) */
rd_list_t on_thread_start; /* .. (copied) */
rd_list_t on_thread_exit; /* .. (copied) */
/* rd_strtup_t list */
rd_list_t config; /* Configuration name=val's
* handled by interceptors. */
} interceptors;
/* Client group configuration */
int coord_query_intvl_ms;
int max_poll_interval_ms;
int builtin_features;
/*
* Consumer configuration
*/
int check_crcs;
int queued_min_msgs;
int queued_max_msg_kbytes;
int64_t queued_max_msg_bytes;
int fetch_wait_max_ms;
int fetch_msg_max_bytes;
int fetch_max_bytes;
int fetch_min_bytes;
int fetch_error_backoff_ms;
char *group_id_str;
char *group_instance_id;
int allow_auto_create_topics;
rd_kafka_pattern_list_t *topic_blacklist;
struct rd_kafka_topic_conf_s *topic_conf; /* Default topic config
* for automatically
* subscribed topics. */
int enable_auto_commit;
int enable_auto_offset_store;
int auto_commit_interval_ms;
int group_session_timeout_ms;
int group_heartbeat_intvl_ms;
rd_kafkap_str_t *group_protocol_type;
char *partition_assignment_strategy;
rd_list_t partition_assignors;
int enabled_assignor_cnt;
void (*rebalance_cb) (rd_kafka_t *rk,
rd_kafka_resp_err_t err,
rd_kafka_topic_partition_list_t *partitions,
void *opaque);
void (*offset_commit_cb) (rd_kafka_t *rk,
rd_kafka_resp_err_t err,
rd_kafka_topic_partition_list_t *offsets,
void *opaque);
rd_kafka_offset_method_t offset_store_method;
rd_kafka_isolation_level_t isolation_level;
int enable_partition_eof;
rd_kafkap_str_t *client_rack;
/*
* Producer configuration
*/
struct {
/*
* Idempotence
*/
int idempotence; /**< Enable Idempotent Producer */
rd_bool_t gapless; /**< Raise fatal error if
* gapless guarantee can't be
* satisfied. */
/*
* Transactions
*/
char *transactional_id; /**< Transactional Id */
int transaction_timeout_ms; /**< Transaction timeout */
} eos;
int queue_buffering_max_msgs;
int queue_buffering_max_kbytes;
double buffering_max_ms_dbl; /**< This is the configured value */
rd_ts_t buffering_max_us; /**< This is the value used in the code */
int queue_backpressure_thres;
int max_retries;
int retry_backoff_ms;
int batch_num_messages;
int batch_size;
rd_kafka_compression_t compression_codec;
int dr_err_only;
int sticky_partition_linger_ms;
/* Message delivery report callback.
* Called once for each produced message, either on
* successful and acknowledged delivery to the broker in which
* case 'err' is 0, or if the message could not be delivered
* in which case 'err' is non-zero (use rd_kafka_err2str()
* to obtain a human-readable error reason).
*
* If the message was produced with neither RD_KAFKA_MSG_F_FREE
* or RD_KAFKA_MSG_F_COPY set then 'payload' is the original
* pointer provided to rd_kafka_produce().
* rdkafka will not perform any further actions on 'payload'
* at this point and the application may rd_free the payload data
* at this point.
*
* 'opaque' is 'conf.opaque', while 'msg_opaque' is
* the opaque pointer provided in the rd_kafka_produce() call.
*/
void (*dr_cb) (rd_kafka_t *rk,
void *payload, size_t len,
rd_kafka_resp_err_t err,
void *opaque, void *msg_opaque);
void (*dr_msg_cb) (rd_kafka_t *rk, const rd_kafka_message_t *rkmessage,
void *opaque);
/* Consume callback */
void (*consume_cb) (rd_kafka_message_t *rkmessage, void *opaque);
/* Log callback */
void (*log_cb) (const rd_kafka_t *rk, int level,
const char *fac, const char *buf);
int log_level;
int log_queue;
int log_thread_name;
int log_connection_close;
/* PRNG seeding */
int enable_random_seed;
/* Error callback */
void (*error_cb) (rd_kafka_t *rk, int err,
const char *reason, void *opaque);
/* Throttle callback */
void (*throttle_cb) (rd_kafka_t *rk, const char *broker_name,
int32_t broker_id, int throttle_time_ms,
void *opaque);
/* Stats callback */
int (*stats_cb) (rd_kafka_t *rk,
char *json,
size_t json_len,
void *opaque);
/* Socket creation callback */
int (*socket_cb) (int domain, int type, int protocol, void *opaque);
/* Connect callback */
int (*connect_cb) (int sockfd,
const struct sockaddr *addr,
int addrlen,
const char *id,
void *opaque);
/* Close socket callback */
int (*closesocket_cb) (int sockfd, void *opaque);
/* File open callback */
int (*open_cb) (const char *pathname, int flags, mode_t mode,
void *opaque);
/* Background queue event callback */
void (*background_event_cb) (rd_kafka_t *rk, rd_kafka_event_t *rkev,
void *opaque);
/* Opaque passed to callbacks. */
void *opaque;
/* For use with value-less properties. */
int dummy;
/* Admin client defaults */
struct {
int request_timeout_ms; /* AdminOptions.request_timeout */
} admin;
/*
* Test mocks
*/
struct {
int broker_cnt; /**< Number of mock brokers */
} mock;
/*
* Unit test pluggable interfaces
*/
struct {
/**< Inject errors in ProduceResponse handler */
rd_kafka_resp_err_t (*handle_ProduceResponse) (
rd_kafka_t *rk,
int32_t brokerid,
uint64_t msgid,
rd_kafka_resp_err_t err);
} ut;
char *sw_name; /**< Software/client name */
char *sw_version; /**< Software/client version */
struct {
/** Properties on (implicit pass-thru) default_topic_conf were
* overwritten by passing an explicit default_topic_conf. */
rd_bool_t default_topic_conf_overwritten;
} warn;
};
int rd_kafka_socket_cb_linux (int domain, int type, int protocol, void *opaque);
int rd_kafka_socket_cb_generic (int domain, int type, int protocol,
void *opaque);
#ifndef _WIN32
int rd_kafka_open_cb_linux (const char *pathname, int flags, mode_t mode,
void *opaque);
#endif
int rd_kafka_open_cb_generic (const char *pathname, int flags, mode_t mode,
void *opaque);
struct rd_kafka_topic_conf_s {
struct rd_kafka_anyconf_hdr hdr; /**< Must be first field */
int required_acks;
int32_t request_timeout_ms;
int message_timeout_ms;
int32_t (*partitioner) (const rd_kafka_topic_t *rkt,
const void *keydata, size_t keylen,
int32_t partition_cnt,
void *rkt_opaque,
void *msg_opaque);
char *partitioner_str;
rd_bool_t random_partitioner; /**< rd_true - random
* rd_false - sticky */
int queuing_strategy; /* RD_KAFKA_QUEUE_FIFO|LIFO */
int (*msg_order_cmp) (const void *a, const void *b);
rd_kafka_compression_t compression_codec;
rd_kafka_complevel_t compression_level;
int produce_offset_report;
int consume_callback_max_msgs;
int auto_commit;
int auto_commit_interval_ms;
int auto_offset_reset;
char *offset_store_path;
int offset_store_sync_interval_ms;
rd_kafka_offset_method_t offset_store_method;
/* Application provided opaque pointer (this is rkt_opaque) */
void *opaque;
};
void rd_kafka_anyconf_destroy (int scope, void *conf);
rd_bool_t rd_kafka_conf_is_modified (const rd_kafka_conf_t *conf,
const char *name);
void rd_kafka_desensitize_str (char *str);
void rd_kafka_conf_desensitize (rd_kafka_conf_t *conf);
void rd_kafka_topic_conf_desensitize (rd_kafka_topic_conf_t *tconf);
const char *rd_kafka_conf_finalize (rd_kafka_type_t cltype,
rd_kafka_conf_t *conf);
const char *rd_kafka_topic_conf_finalize (rd_kafka_type_t cltype,
const rd_kafka_conf_t *conf,
rd_kafka_topic_conf_t *tconf);
int rd_kafka_conf_warn (rd_kafka_t *rk);
void rd_kafka_anyconf_dump_dbg (rd_kafka_t *rk, int scope, const void *conf,
const char *description);
#include "rdkafka_confval.h"
int unittest_conf (void);
#endif /* _RDKAFKA_CONF_H_ */
|
el-hoshino/CooldownProgressView
|
CooldownProgressView/CooldownProgressView/CooldownProgressView.h
|
//
// CooldownProgressView.h
// CooldownProgressView
//
// Created by <NAME> on 2017/02/27.
// Copyright © 2017年 Crazism. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for CooldownProgressView.
FOUNDATION_EXPORT double CooldownProgressViewVersionNumber;
//! Project version string for CooldownProgressView.
FOUNDATION_EXPORT const unsigned char CooldownProgressViewVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <CooldownProgressView/PublicHeader.h>
|
khval/amosExtention2Ascii
|
startup.h
|
<gh_stars>1-10
BOOL open_lib( const char *name, int ver , const char *iname, int iver, struct Library **base, struct Interface **interface);
char *get_filename(int args,char **arg);
char *asl();
|
josnelihurt/algorithms
|
cpp-src/src/data-structures/tree/bst/bst.h
|
namespace bst{
struct Node{
int data;
Node *left;
Node *right;
};
Node* newNode(int data);
Node *insert(Node *root, int data);
Node *lca(Node *root, int v1,int v2);
int height(Node *root);
void deleteNode(Node *root);
void inOrder(Node *root);
void levelOrder(Node *root);
void postOrder(Node *root);
void preOrder(Node *root);
}
|
josnelihurt/algorithms
|
cpp-src/src/algorithms/hacker-rank/implementation/the_birthday_bar.h
|
#include <bits/stdc++.h>
#include <vector>
namespace the_birthday_bar{
int birthday(std::vector<int> s, int d, int m);
}
|
josnelihurt/algorithms
|
cpp-src/template/name.h
|
<filename>cpp-src/template/name.h
namespace name{
//Function definition goes here
}
|
josnelihurt/algorithms
|
cpp-src/src/algorithms/hacker-rank/implementation/between_two_sets.h
|
<filename>cpp-src/src/algorithms/hacker-rank/implementation/between_two_sets.h
#include <vector>
namespace between_two_sets{
int getTotalX(std::vector<int> a, std::vector<int> b);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.