hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4385e9cc0a790929e94f7311f688a76a2b12c7ac | 29,471 | c | C | src/gtk/iupgtk_common.c | airways/IupAndroid | a2ac756802f826a5db3a736f1731561dbbeb78fa | [
"MIT"
] | 64 | 2016-02-19T18:58:38.000Z | 2022-03-16T17:51:09.000Z | src/gtk/iupgtk_common.c | airways/IupAndroid | a2ac756802f826a5db3a736f1731561dbbeb78fa | [
"MIT"
] | 34 | 2017-04-14T01:12:21.000Z | 2018-10-26T05:30:24.000Z | src/gtk/iupgtk_common.c | airways/IupAndroid | a2ac756802f826a5db3a736f1731561dbbeb78fa | [
"MIT"
] | 8 | 2016-01-25T00:24:01.000Z | 2021-03-10T20:20:51.000Z | /** \file
* \brief GTK Base Functions
*
* See Copyright Notice in "iup.h"
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <gtk/gtk.h>
#include "iup.h"
#include "iupcbs.h"
#include "iupkey.h"
#include "iup_object.h"
#include "iup_childtree.h"
#include "iup_key.h"
#include "iup_str.h"
#include "iup_class.h"
#include "iup_attrib.h"
#include "iup_focus.h"
#include "iup_key.h"
#include "iup_image.h"
#include "iup_drv.h"
#include "iup_assert.h"
#include "iupgtk_drv.h"
#if GTK_CHECK_VERSION(3, 0, 0)
typedef struct _iupGtkFixed
{
GtkFixed fixed;
} iupGtkFixed;
typedef struct _iupGtkFixedClass
{
GtkFixedClass parent_class;
} iupGtkFixedClass;
static GType iup_gtk_fixed_get_type (void) G_GNUC_CONST;
static void iup_gtk_fixed_class_init (iupGtkFixedClass *_class);
static void iup_gtk_fixed_init (iupGtkFixed *fixed);
static void iup_gtk_fixed_get_preferred_size (GtkWidget *widget, gint *minimum, gint *natural);
G_DEFINE_TYPE (iupGtkFixed, iup_gtk_fixed, GTK_TYPE_FIXED)
static void iup_gtk_fixed_class_init (iupGtkFixedClass *_class)
{
GtkWidgetClass *widget_class = (GtkWidgetClass*) _class;
widget_class->get_preferred_width = iup_gtk_fixed_get_preferred_size;
widget_class->get_preferred_height = iup_gtk_fixed_get_preferred_size;
}
static int iupGtkFixedWindow = 0;
static void iup_gtk_fixed_init (iupGtkFixed *fixed)
{
if (iupGtkFixedWindow)
gtk_widget_set_has_window(GTK_WIDGET(fixed), TRUE);
}
static void iup_gtk_fixed_get_preferred_size (GtkWidget *widget, gint *minimum, gint *natural)
{
(void)widget;
/* all this is just to replace this method, so it will behave like GtkLayout. */
*minimum = 0;
*natural = 0;
}
static GtkWidget* iup_gtk_fixed_new(void)
{
return g_object_new (iup_gtk_fixed_get_type(), NULL);
}
#endif
/* WARNING: in GTK there are many controls that are not native windows,
so theirs GdkWindow will NOT return a native window exclusive of that control,
in fact it can return a base native window shared by many controls.
IupCanvas is a special case that uses an exclusive native window. */
GtkWidget* iupgtkNativeContainerNew(int has_window)
{
GtkWidget* widget;
#if GTK_CHECK_VERSION(3, 0, 0)
iupGtkFixedWindow = has_window;
widget = iup_gtk_fixed_new();
iupGtkFixedWindow = 0;
#else
widget = gtk_fixed_new();
#endif
#if GTK_CHECK_VERSION(2, 18, 0)
gtk_widget_set_has_window(widget, has_window);
#else
gtk_fixed_set_has_window(GTK_FIXED(widget), has_window);
#endif
return widget;
}
void iupgtkNativeContainerAdd(GtkWidget* container, GtkWidget* widget)
{
gtk_fixed_put(GTK_FIXED(container), widget, 0, 0);
}
void iupgtkNativeContainerMove(GtkWidget* container, GtkWidget* widget, int x, int y)
{
gtk_fixed_move(GTK_FIXED(container), widget, x, y);
}
/* GTK only has absolute positioning using a native container,
so all elements returned by iupChildTreeGetNativeParentHandle should be a native container.
If not looks in the native parent. */
static GtkWidget* gtkGetNativeParent(Ihandle* ih)
{
GtkWidget* widget = iupChildTreeGetNativeParentHandle(ih);
while (widget && !GTK_IS_FIXED(widget))
widget = gtk_widget_get_parent(widget);
return widget;
}
const char* iupgtkGetWidgetClassName(GtkWidget* widget)
{
/* Used for debugging */
return g_type_name(G_TYPE_FROM_CLASS(GTK_WIDGET_GET_CLASS(widget)));
}
void iupgtkUpdateMnemonic(Ihandle* ih)
{
GtkLabel* label = (GtkLabel*)iupAttribGet(ih, "_IUPGTK_LABELMNEMONIC");
if (label) gtk_label_set_mnemonic_widget(label, ih->handle);
}
void iupdrvActivate(Ihandle* ih)
{
gtk_widget_activate(ih->handle);
}
void iupdrvReparent(Ihandle* ih)
{
GtkWidget* old_parent;
GtkWidget* new_parent = gtkGetNativeParent(ih);
GtkWidget* widget = (GtkWidget*)iupAttribGet(ih, "_IUP_EXTRAPARENT"); /* here is used as the native child because is the outermost component of the element */
if (!widget) widget = ih->handle;
old_parent = gtk_widget_get_parent(widget);
if (old_parent != new_parent)
{
gtk_widget_reparent(widget, new_parent);
gtk_widget_realize(widget);
}
}
void iupgtkAddToParent(Ihandle* ih)
{
GtkWidget* parent = gtkGetNativeParent(ih);
GtkWidget* widget = (GtkWidget*)iupAttribGet(ih, "_IUP_EXTRAPARENT"); /* here is used as the native child because is the outermost component of the element */
if (!widget) widget = ih->handle;
iupgtkNativeContainerAdd(parent, widget);
}
void iupgtkSetPosSize(GtkContainer* parent, GtkWidget* widget, int x, int y, int width, int height)
{
iupgtkNativeContainerMove((GtkWidget*)parent, widget, x, y);
if (width > 0 && height > 0)
gtk_widget_set_size_request(widget, width, height);
}
void iupdrvBaseLayoutUpdateMethod(Ihandle *ih)
{
GtkWidget* parent = gtkGetNativeParent(ih);
GtkWidget* widget = (GtkWidget*)iupAttribGet(ih, "_IUP_EXTRAPARENT");
if (!widget) widget = ih->handle;
iupgtkSetPosSize(GTK_CONTAINER(parent), widget, ih->x, ih->y, ih->currentwidth, ih->currentheight);
}
void iupdrvBaseUnMapMethod(Ihandle* ih)
{
GtkWidget* widget = (GtkWidget*)iupAttribGet(ih, "_IUP_EXTRAPARENT");
if (!widget) widget = ih->handle;
gtk_widget_hide(widget);
gtk_widget_unrealize(widget);
gtk_widget_destroy(widget); /* To match the call to gtk_*****_new */
}
void iupdrvPostRedraw(Ihandle *ih)
{
GdkWindow* window = iupgtkGetWindow(ih->handle);
if (window)
gdk_window_invalidate_rect(window, NULL, TRUE);
/* Post a REDRAW */
gtk_widget_queue_draw(ih->handle);
}
void iupdrvRedrawNow(Ihandle *ih)
{
GdkWindow* window = iupgtkGetWindow(ih->handle);
if (window)
gdk_window_invalidate_rect(window, NULL, TRUE);
/* Post a REDRAW */
gtk_widget_queue_draw(ih->handle);
/* Force a REDRAW */
if (window)
gdk_window_process_updates(window, TRUE);
}
static GtkWidget* gtkGetWindowedParent(GtkWidget* widget)
{
#if GTK_CHECK_VERSION(2, 18, 0)
while (widget && !gtk_widget_get_has_window(widget))
#else
while (widget && GTK_WIDGET_NO_WINDOW(widget))
#endif
widget = gtk_widget_get_parent(widget);
return widget;
}
void iupdrvScreenToClient(Ihandle* ih, int *x, int *y)
{
gint win_x = 0, win_y = 0;
gint dx = 0, dy = 0;
GtkWidget* wparent = gtkGetWindowedParent(ih->handle);
if (ih->handle != wparent)
gtk_widget_translate_coordinates(ih->handle, wparent, 0, 0, &dx, &dy); /* widget origin relative to GDK window */
gdk_window_get_origin(iupgtkGetWindow(wparent), &win_x, &win_y); /* GDK window origin relative to screen */
*x -= win_x + dx;
*y -= win_y + dy;
}
void iupdrvClientToScreen(Ihandle* ih, int *x, int *y)
{
gint win_x = 0, win_y = 0;
gint dx = 0, dy = 0;
GtkWidget* wparent = gtkGetWindowedParent(ih->handle);
if (ih->handle != wparent)
gtk_widget_translate_coordinates(ih->handle, wparent, 0, 0, &dx, &dy); /* widget relative to GDK window */
gdk_window_get_origin(iupgtkGetWindow(wparent), &win_x, &win_y); /* GDK window relative to screen */
*x += win_x + dx;
*y += win_y + dy;
}
gboolean iupgtkShowHelp(GtkWidget *widget, GtkWidgetHelpType *arg1, Ihandle *ih)
{
Icallback cb;
(void)widget;
(void)arg1;
cb = IupGetCallback(ih, "HELP_CB");
if (cb && cb(ih) == IUP_CLOSE)
IupExitLoop();
return FALSE;
}
gboolean iupgtkEnterLeaveEvent(GtkWidget *widget, GdkEventCrossing *evt, Ihandle *ih)
{
Icallback cb = NULL;
(void)widget;
if (evt->type == GDK_ENTER_NOTIFY)
cb = IupGetCallback(ih, "ENTERWINDOW_CB");
else if (evt->type == GDK_LEAVE_NOTIFY)
cb = IupGetCallback(ih, "LEAVEWINDOW_CB");
if (cb)
cb(ih);
return FALSE;
}
int iupgtkSetMnemonicTitle(Ihandle* ih, GtkLabel* label, const char* value)
{
char c = '_';
char* str;
if (!value)
value = "";
str = iupStrProcessMnemonic(value, &c, 1); /* replace & by c, the returned value of c is ignored in GTK */
if (str != value)
{
gtk_label_set_text_with_mnemonic(label, iupgtkStrConvertToSystem(str));
free(str);
return 1;
}
else
{
if (iupAttribGetBoolean(ih, "MARKUP"))
gtk_label_set_markup(label, iupgtkStrConvertToSystem(str));
else
gtk_label_set_text(label, iupgtkStrConvertToSystem(str));
}
return 0;
}
int iupdrvBaseSetZorderAttrib(Ihandle* ih, const char* value)
{
if (iupdrvIsVisible(ih))
{
GdkWindow* window = iupgtkGetWindow(ih->handle);
if (iupStrEqualNoCase(value, "TOP"))
gdk_window_raise(window);
else
gdk_window_lower(window);
}
return 0;
}
void iupdrvSetVisible(Ihandle* ih, int visible)
{
GtkWidget* container = (GtkWidget*)iupAttribGet(ih, "_IUP_EXTRAPARENT");
if (visible)
{
if (container) gtk_widget_show(container);
gtk_widget_show(ih->handle);
}
else
{
if (container) gtk_widget_hide(container);
gtk_widget_hide(ih->handle);
}
}
int iupgtkIsVisible(GtkWidget* widget)
{
#if GTK_CHECK_VERSION(2, 18, 0)
return gtk_widget_get_visible(widget);
#else
return GTK_WIDGET_VISIBLE(widget);
#endif
}
int iupdrvIsVisible(Ihandle* ih)
{
if (iupgtkIsVisible(ih->handle))
{
/* if marked as visible, since we use gtk_widget_hide and NOT gtk_widget_hide_all
must check its parents. */
Ihandle* parent = ih->parent;
while (parent)
{
if (parent->iclass->nativetype != IUP_TYPEVOID)
{
if (!iupgtkIsVisible(parent->handle))
return 0;
}
parent = parent->parent;
}
return 1;
}
else
return 0;
}
int iupdrvIsActive(Ihandle *ih)
{
#if GTK_CHECK_VERSION(2, 18, 0)
return gtk_widget_is_sensitive(ih->handle);
#else
return GTK_WIDGET_IS_SENSITIVE(ih->handle);
#endif
}
void iupdrvSetActive(Ihandle* ih, int enable)
{
GtkWidget* container = (GtkWidget*)iupAttribGet(ih, "_IUP_EXTRAPARENT");
if (container) gtk_widget_set_sensitive(container, enable);
gtk_widget_set_sensitive(ih->handle, enable);
}
#if GTK_CHECK_VERSION(3, 0, 0)
static void iupgdkRGBASet(GdkRGBA* rgba, unsigned char r, unsigned char g, unsigned char b)
{
rgba->red = iupgtkColorToDouble(r);
rgba->green = iupgtkColorToDouble(g);
rgba->blue = iupgtkColorToDouble(b);
rgba->alpha = 1.0;
}
static GdkRGBA gtkDarkerRGBA(GdkRGBA *rgba)
{
GdkRGBA dark_rgba = {0,0,0,1.0};
dark_rgba.red = (rgba->red*9)/10;
dark_rgba.green = (rgba->green*9)/10;
dark_rgba.blue = (rgba->blue*9)/10;
return dark_rgba;
}
static gdouble gtkCROPDouble(gdouble x)
{
if (x > 1.0) return 1.0;
return x;
}
static GdkRGBA gtkLighterRGBA(GdkRGBA *rgba)
{
GdkRGBA light_rgba = {0,0,0,1.0};
light_rgba.red = gtkCROPDouble((rgba->red*11)/10);
light_rgba.green = gtkCROPDouble((rgba->green*11)/10);
light_rgba.blue = gtkCROPDouble((rgba->blue*11)/10);
return light_rgba;
}
#else
static GdkColor gtkDarkerColor(GdkColor *color)
{
GdkColor dark_color = {0L,0,0,0};
dark_color.red = (color->red*9)/10;
dark_color.green = (color->green*9)/10;
dark_color.blue = (color->blue*9)/10;
return dark_color;
}
static guint16 gtkCROP16(int x)
{
if (x > 65535) return 65535;
return (guint16)x;
}
static GdkColor gtkLighterColor(GdkColor *color)
{
GdkColor light_color = {0L,0,0,0};
light_color.red = gtkCROP16(((int)color->red*11)/10);
light_color.green = gtkCROP16(((int)color->green*11)/10);
light_color.blue = gtkCROP16(((int)color->blue*11)/10);
return light_color;
}
#endif
#if GTK_CHECK_VERSION(3, 16, 0)
static char* gtkGetSelectedColor(void)
{
GdkRGBA rgba;
unsigned char r, g, b;
iupStrToRGB(IupGetGlobal("TXTHLCOLOR"), &r, &g, &b);
iupgdkRGBASet(&rgba, r, g, b);
return gdk_rgba_to_string(&rgba);
}
#endif
void iupgtkSetBgColor(InativeHandle* handle, unsigned char r, unsigned char g, unsigned char b)
{
#if GTK_CHECK_VERSION(3, 0, 0)
GdkRGBA rgba, light_rgba, dark_rgba;
int is_txt = 0;
if (GTK_IS_TREE_VIEW(handle) ||
GTK_IS_TEXT_VIEW(handle) ||
GTK_IS_ENTRY(handle) ||
GTK_IS_COMBO_BOX(handle))
is_txt = 1;
iupgdkRGBASet(&rgba, r, g, b);
dark_rgba = gtkDarkerRGBA(&rgba);
light_rgba = gtkLighterRGBA(&rgba);
#if GTK_CHECK_VERSION(3, 16, 0)
{
char *bg, *bg_light, *bg_dark;
char *css;
GtkCssProvider *provider;
bg = gdk_rgba_to_string(&rgba);
bg_light = gdk_rgba_to_string(&light_rgba);
bg_dark = gdk_rgba_to_string(&dark_rgba);
/* style background color using CSS */
provider = gtk_css_provider_new();
if (is_txt)
{
char* selected = gtkGetSelectedColor();
css = g_strdup_printf("* { background-color: %s; }"
"*:hover { background-color: %s; }"
"*:active { background-color: %s; }"
"*:selected { background-color: %s; }"
"*:disabled { background-color: %s; }",
bg, bg_light, bg_dark, selected, bg_light);
g_free(selected);
}
else
{
css = g_strdup_printf("* { background-color: %s; }"
"*:hover { background-color: %s; }"
"*:active { background-color: %s; }"
"*:disabled { background-color: %s; }",
bg, bg_light, bg_dark, bg);
}
gtk_style_context_add_provider(gtk_widget_get_style_context(handle), GTK_STYLE_PROVIDER(provider), GTK_STYLE_PROVIDER_PRIORITY_USER);
gtk_css_provider_load_from_data(provider, css, -1, NULL);
g_free(bg); g_free(bg_light); g_free(bg_dark);
g_free(css);
g_object_unref(provider);
}
#else
gtk_widget_override_background_color(handle, GTK_STATE_FLAG_NORMAL, &rgba);
gtk_widget_override_background_color(handle, GTK_STATE_FLAG_ACTIVE, &dark_rgba); /* active */
gtk_widget_override_background_color(handle, GTK_STATE_FLAG_PRELIGHT, &light_rgba); /* hover */
if (is_txt)
gtk_widget_override_background_color(handle, GTK_STATE_FLAG_INSENSITIVE, &light_rgba); /* disabled */
else
gtk_widget_override_background_color(handle, GTK_STATE_FLAG_INSENSITIVE, &rgba); /* disabled */
#endif
#else
GtkRcStyle *rc_style;
GdkColor color;
iupgdkColorSetRGB(&color, r, g, b);
rc_style = gtk_widget_get_modifier_style(handle);
rc_style->base[GTK_STATE_NORMAL] = rc_style->bg[GTK_STATE_NORMAL] = rc_style->bg[GTK_STATE_INSENSITIVE] = color;
rc_style->base[GTK_STATE_ACTIVE] = rc_style->bg[GTK_STATE_ACTIVE] = gtkDarkerColor(&color);
rc_style->base[GTK_STATE_PRELIGHT] = rc_style->bg[GTK_STATE_PRELIGHT] = rc_style->base[GTK_STATE_INSENSITIVE] = gtkLighterColor(&color);
rc_style->color_flags[GTK_STATE_NORMAL] |= GTK_RC_BASE | GTK_RC_BG;
rc_style->color_flags[GTK_STATE_ACTIVE] |= GTK_RC_BASE | GTK_RC_BG; /* active */
rc_style->color_flags[GTK_STATE_PRELIGHT] |= GTK_RC_BASE | GTK_RC_BG; /* hover */
rc_style->color_flags[GTK_STATE_INSENSITIVE] |= GTK_RC_BASE | GTK_RC_BG; /* disabled */
gtk_widget_modify_style(handle, rc_style);
#endif
}
void iupgtkSetFgColor(InativeHandle* handle, unsigned char r, unsigned char g, unsigned char b)
{
#if GTK_CHECK_VERSION(3, 0, 0)
GdkRGBA rgba;
iupgdkRGBASet(&rgba, r, g, b);
gtk_widget_override_color(handle, GTK_STATE_FLAG_NORMAL, &rgba);
gtk_widget_override_color(handle, GTK_STATE_FLAG_ACTIVE, &rgba);
gtk_widget_override_color(handle, GTK_STATE_FLAG_PRELIGHT, &rgba);
#else
GtkRcStyle *rc_style;
GdkColor color;
iupgdkColorSetRGB(&color, r, g, b);
rc_style = gtk_widget_get_modifier_style(handle);
rc_style->fg[GTK_STATE_ACTIVE] = rc_style->fg[GTK_STATE_NORMAL] = rc_style->fg[GTK_STATE_PRELIGHT] = color;
rc_style->text[GTK_STATE_ACTIVE] = rc_style->text[GTK_STATE_NORMAL] = rc_style->text[GTK_STATE_PRELIGHT] = color;
rc_style->color_flags[GTK_STATE_NORMAL] |= GTK_RC_TEXT | GTK_RC_FG;
rc_style->color_flags[GTK_STATE_ACTIVE] |= GTK_RC_TEXT | GTK_RC_FG;
rc_style->color_flags[GTK_STATE_PRELIGHT] |= GTK_RC_TEXT | GTK_RC_FG;
/* do not set at CHILD_CONTAINER */
gtk_widget_modify_style(handle, rc_style);
#endif
}
int iupdrvBaseSetBgColorAttrib(Ihandle* ih, const char* value)
{
unsigned char r, g, b;
if (!iupStrToRGB(value, &r, &g, &b))
return 0;
iupgtkSetBgColor(ih->handle, r, g, b);
/* DO NOT NEED TO UPDATE GTK IMAGES SINCE THEY DO NOT DEPEND ON BGCOLOR */
return 1;
}
int iupdrvBaseSetFgColorAttrib(Ihandle* ih, const char* value)
{
unsigned char r, g, b;
if (!iupStrToRGB(value, &r, &g, &b))
return 0;
iupgtkSetFgColor(ih->handle, r, g, b);
return 1;
}
static GdkCursor* gtkEmptyCursor(Ihandle* ih)
{
#if GTK_CHECK_VERSION(2, 16, 0)
(void)ih;
return gdk_cursor_new(GDK_BLANK_CURSOR);
#else
/* creates an empty cursor */
GdkColor cursor_color = {0L,0,0,0};
char bitsnull[1] = {0x00};
GdkWindow* window = iupgtkGetWindow(ih->handle);
GdkPixmap* pixmapnull = gdk_bitmap_create_from_data(
(GdkDrawable*)window,
bitsnull,
1,1);
GdkCursor* cur = gdk_cursor_new_from_pixmap(
pixmapnull,
pixmapnull,
&cursor_color,
&cursor_color,
0,0);
g_object_unref(pixmapnull);
return cur;
#endif
}
static GdkCursor* gtkGetCursor(Ihandle* ih, const char* name)
{
static struct {
const char* iupname;
int sysname;
} table[] = {
{ "NONE", 0},
{ "NULL", 0},
{ "ARROW", GDK_LEFT_PTR},
{ "BUSY", GDK_WATCH},
{ "CROSS", GDK_CROSSHAIR},
{ "HAND", GDK_HAND2},
{ "HELP", GDK_QUESTION_ARROW},
{ "IUP", GDK_QUESTION_ARROW},
{ "MOVE", GDK_FLEUR},
{ "PEN", GDK_PENCIL},
{ "RESIZE_N", GDK_TOP_SIDE},
{ "RESIZE_S", GDK_BOTTOM_SIDE},
{ "RESIZE_NS", GDK_SB_V_DOUBLE_ARROW},
{ "SPLITTER_HORIZ", GDK_SB_V_DOUBLE_ARROW},
{ "RESIZE_W", GDK_LEFT_SIDE},
{ "RESIZE_E", GDK_RIGHT_SIDE},
{ "RESIZE_WE", GDK_SB_H_DOUBLE_ARROW},
{ "SPLITTER_VERT", GDK_SB_H_DOUBLE_ARROW},
{ "RESIZE_NE", GDK_TOP_RIGHT_CORNER},
{ "RESIZE_SE", GDK_BOTTOM_RIGHT_CORNER},
{ "RESIZE_NW", GDK_TOP_LEFT_CORNER},
{ "RESIZE_SW", GDK_BOTTOM_LEFT_CORNER},
{ "TEXT", GDK_XTERM},
{ "UPARROW", GDK_CENTER_PTR}
};
GdkCursor* cur;
char str[200];
int i, count = sizeof(table)/sizeof(table[0]);
/* check the cursor cache first (per control)*/
sprintf(str, "_IUPGTK_CURSOR_%s", name);
cur = (GdkCursor*)iupAttribGet(ih, str);
if (cur)
return cur;
/* check the pre-defined IUP names first */
for (i = 0; i < count; i++)
{
if (iupStrEqualNoCase(name, table[i].iupname))
{
if (table[i].sysname)
cur = gdk_cursor_new(table[i].sysname);
else
cur = gtkEmptyCursor(ih);
break;
}
}
if (i == count)
{
/* check for a name defined cursor */
cur = iupImageGetCursor(name);
}
/* save the cursor in cache */
iupAttribSet(ih, str, (char*)cur);
return cur;
}
int iupdrvBaseSetCursorAttrib(Ihandle* ih, const char* value)
{
GdkCursor* cur = gtkGetCursor(ih, value);
if (cur)
{
GdkWindow* window = iupgtkGetWindow(ih->handle);
if (window)
{
gdk_window_set_cursor(window, cur);
gdk_display_flush(gdk_display_get_default());
}
return 1;
}
return 0;
}
void iupgdkColorSetRGB(GdkColor* color, unsigned char r, unsigned char g, unsigned char b)
{
color->red = iupCOLOR8TO16(r);
color->green = iupCOLOR8TO16(g);
color->blue = iupCOLOR8TO16(b);
color->pixel = 0;
}
int iupdrvGetScrollbarSize(void)
{
static int size = 0;
if (iupStrBoolean(IupGetGlobal("OVERLAYSCROLLBAR")))
return 1;
if (size == 0)
{
gint slider_width, trough_border;
#if GTK_CHECK_VERSION(3, 0, 0)
GtkWidget* sb = gtk_scrollbar_new(GTK_ORIENTATION_VERTICAL, NULL);
#else
GtkWidget* sb = gtk_vscrollbar_new(NULL);
#endif
gtk_widget_style_get(sb, "slider-width", &slider_width,
"trough-border", &trough_border,
NULL);
size = trough_border * 2 + slider_width;
gtk_widget_destroy(sb);
}
return size;
}
void iupdrvPaintFocusRect(Ihandle* ih, void* _gc, int x, int y, int w, int h)
{
#if GTK_CHECK_VERSION(3, 0, 0)
cairo_t* cr = (cairo_t*)_gc;
GtkStyleContext* context = gtk_widget_get_style_context(ih->handle);
gtk_render_focus(context, cr, x, y, w, h);
#else
GdkWindow* window = iupgtkGetWindow(ih->handle);
GtkStyle *style = gtk_widget_get_style(ih->handle);
#if GTK_CHECK_VERSION(2, 18, 0)
GtkStateType state = gtk_widget_get_state(ih->handle);
#else
GtkStateType state = GTK_WIDGET_STATE(ih->handle);
#endif
gtk_paint_focus(style, window, state, NULL, ih->handle, NULL, x, y, w, h);
#endif
(void)_gc;
}
void iupdrvBaseRegisterCommonAttrib(Iclass* ic)
{
iupClassRegisterAttribute(ic, iupgtkGetNativeFontIdName(), iupgtkGetFontIdAttrib, NULL, NULL, NULL, IUPAF_NOT_MAPPED | IUPAF_NO_INHERIT | IUPAF_NO_STRING);
iupClassRegisterAttribute(ic, "PANGOFONTDESC", iupgtkGetPangoFontDescAttrib, NULL, NULL, NULL, IUPAF_NOT_MAPPED|IUPAF_NO_INHERIT|IUPAF_NO_STRING);
iupClassRegisterAttribute(ic, "PANGOLAYOUT", iupgtkGetPangoLayoutAttrib, NULL, NULL, NULL, IUPAF_NOT_MAPPED|IUPAF_NO_INHERIT|IUPAF_NO_STRING);
}
void iupdrvBaseRegisterVisualAttrib(Iclass* ic)
{
iupClassRegisterAttribute(ic, "TIPMARKUP", NULL, NULL, IUPAF_SAMEASSYSTEM, NULL, IUPAF_NOT_MAPPED);
iupClassRegisterAttribute(ic, "TIPICON", NULL, NULL, IUPAF_SAMEASSYSTEM, NULL, IUPAF_NOT_MAPPED);
}
gboolean iupgtkMotionNotifyEvent(GtkWidget *widget, GdkEventMotion *evt, Ihandle *ih)
{
IFniis cb;
if (evt->is_hint)
{
int x, y;
iupgtkWindowGetPointer(iupgtkGetWindow(widget), &x, &y, NULL);
evt->x = x;
evt->y = y;
}
cb = (IFniis)IupGetCallback(ih,"MOTION_CB");
if (cb)
{
char status[IUPKEY_STATUS_SIZE] = IUPKEY_STATUS_INIT;
iupgtkButtonKeySetStatus(evt->state, 0, status, 0);
cb(ih, (int)evt->x, (int)evt->y, status);
}
return FALSE;
}
gboolean iupgtkButtonEvent(GtkWidget *widget, GdkEventButton *evt, Ihandle *ih)
{
IFniiiis cb = (IFniiiis)IupGetCallback(ih,"BUTTON_CB");
if (cb)
{
int doubleclick = 0, ret, press = 1;
int b = IUP_BUTTON1+(evt->button-1);
char status[IUPKEY_STATUS_SIZE] = IUPKEY_STATUS_INIT;
if (evt->type == GDK_BUTTON_RELEASE)
press = 0;
if (evt->type == GDK_2BUTTON_PRESS)
doubleclick = 1;
iupgtkButtonKeySetStatus(evt->state, evt->button, status, doubleclick);
if (doubleclick)
{
/* Must compensate the fact that in GTK there is an extra button press event
when occurs a double click, we compensate that completing the event
with a button release before the double click. */
status[5] = ' '; /* clear double click */
ret = cb(ih, b, 0, (int)evt->x, (int)evt->y, status); /* release */
if (ret==IUP_CLOSE)
IupExitLoop();
else if (ret==IUP_IGNORE)
return TRUE;
status[5] = 'D'; /* restore double click */
}
ret = cb(ih, b, press, (int)evt->x, (int)evt->y, status);
if (ret==IUP_CLOSE)
IupExitLoop();
else if (ret==IUP_IGNORE)
return TRUE;
}
(void)widget;
return FALSE;
}
void iupdrvSendKey(int key, int press)
{
Ihandle* focus;
gint nkeys = 0;
GdkKeymapKey *keys;
GdkEventKey evt;
memset(&evt, 0, sizeof(GdkEventKey));
evt.send_event = TRUE;
focus = IupGetFocus();
if (!focus)
return;
evt.window = iupgtkGetWindow(focus->handle);
iupdrvKeyEncode(key, &evt.keyval, &evt.state);
if (!evt.keyval)
return;
if (!gdk_keymap_get_entries_for_keyval(gdk_keymap_get_default(), evt.keyval, &keys, &nkeys))
return;
evt.hardware_keycode = (guint16)keys[0].keycode;
evt.group = (guint8)keys[0].group;
if (press & 0x01)
{
evt.type = GDK_KEY_PRESS;
gdk_event_put((GdkEvent*)&evt);
}
if (press & 0x02)
{
evt.type = GDK_KEY_RELEASE;
gdk_event_put((GdkEvent*)&evt);
}
}
void iupdrvWarpPointer(int x, int y)
{
/* VirtualBox does not reproduce the mouse move visually, but it is working. */
#if GTK_CHECK_VERSION(3, 0, 0)
GdkDeviceManager* device_manager = gdk_display_get_device_manager(gdk_display_get_default());
GdkDevice* device = gdk_device_manager_get_client_pointer(device_manager);
gdk_device_warp(device, gdk_screen_get_default(), x, y);
#elif GTK_CHECK_VERSION(2, 8, 0)
gdk_display_warp_pointer(gdk_display_get_default(), gdk_screen_get_default(), x, y);
#endif
}
void iupdrvSendMouse(int x, int y, int bt, int status)
{
/* always update cursor */
/* must be before sending the message because the cursor position will be used */
/* this will also send an extra motion event */
iupdrvWarpPointer(x, y);
if (status != -1)
{
GtkWidget* grab_widget;
gint origin_x, origin_y;
#if GTK_CHECK_VERSION(3, 0, 0)
GdkDeviceManager* device_manager = gdk_display_get_device_manager(gdk_display_get_default());
GdkDevice* device = gdk_device_manager_get_client_pointer(device_manager);
#endif
GdkEventButton evt;
memset(&evt, 0, sizeof(GdkEventButton));
evt.send_event = TRUE;
evt.x_root = x;
evt.y_root = y;
evt.type = (status==0)? GDK_BUTTON_RELEASE: ((status==2)? GDK_2BUTTON_PRESS: GDK_BUTTON_PRESS);
#if GTK_CHECK_VERSION(3, 0, 0)
evt.device = device;
#else
evt.device = gdk_device_get_core_pointer();
#endif
grab_widget = gtk_grab_get_current();
if (grab_widget)
evt.window = iupgtkGetWindow(grab_widget);
else
{
#if GTK_CHECK_VERSION(3, 0, 0)
evt.window = gdk_device_get_window_at_position(device, NULL, NULL);
#else
evt.window = gdk_window_at_pointer(NULL, NULL);
#endif
}
switch(bt)
{
case IUP_BUTTON1:
evt.state = GDK_BUTTON1_MASK;
evt.button = 1;
break;
case IUP_BUTTON2:
evt.state = GDK_BUTTON2_MASK;
evt.button = 2;
break;
case IUP_BUTTON3:
evt.state = GDK_BUTTON3_MASK;
evt.button = 3;
break;
case IUP_BUTTON4:
evt.state = GDK_BUTTON4_MASK;
evt.button = 4;
break;
case IUP_BUTTON5:
evt.state = GDK_BUTTON5_MASK;
evt.button = 5;
break;
default:
return;
}
gdk_window_get_origin(evt.window, &origin_x, &origin_y);
evt.x = x - origin_x;
evt.y = y - origin_y;
gdk_event_put((GdkEvent*)&evt);
}
#if 0 /* kept for future reference */
else
{
GtkWidget* grab_widget;
gint origin_x, origin_y;
GdkEventMotion evt;
memset(&evt, 0, sizeof(GdkEventMotion));
evt.send_event = TRUE;
evt.x_root = x;
evt.y_root = y;
evt.type = GDK_MOTION_NOTIFY;
evt.device = gdk_device_get_core_pointer();
grab_widget = gtk_grab_get_current();
if (grab_widget)
evt.window = iupgtkGetWindow(grab_widget);
else
evt.window = gdk_window_at_pointer(NULL, NULL);
switch(bt)
{
case IUP_BUTTON1:
evt.state = GDK_BUTTON1_MASK;
break;
case IUP_BUTTON2:
evt.state = GDK_BUTTON2_MASK;
break;
case IUP_BUTTON3:
evt.state = GDK_BUTTON3_MASK;
break;
case IUP_BUTTON4:
evt.state = GDK_BUTTON4_MASK;
break;
case IUP_BUTTON5:
evt.state = GDK_BUTTON5_MASK;
break;
default:
return;
}
gdk_window_get_origin(evt.window, &origin_x, &origin_y);
evt.x = x - origin_x;
evt.y = y - origin_y;
gdk_event_put((GdkEvent*)&evt);
}
#endif
}
void iupdrvSleep(int time)
{
g_usleep(time*1000); /* mili to micro */
}
GdkWindow* iupgtkGetWindow(GtkWidget *widget)
{
#if GTK_CHECK_VERSION(2, 14, 0)
return gtk_widget_get_window(widget);
#else
return widget->window;
#endif
}
void iupgtkWindowGetPointer(GdkWindow *window, int *x, int *y, GdkModifierType *mask)
{
#if GTK_CHECK_VERSION(3, 0, 0)
GdkDisplay *display = gdk_window_get_display(window);
GdkDeviceManager* device_manager = gdk_display_get_device_manager(display);
GdkDevice* device = gdk_device_manager_get_client_pointer(device_manager);
gdk_window_get_device_position(window, device, x, y, mask);
#else
gdk_window_get_pointer(window, x, y, mask);
#endif
}
void iupgtkSetMargin(GtkWidget* widget, int horiz_padding, int vert_padding, int mandatory_gtk3)
{
#if GTK_CHECK_VERSION(3, 12, 0)
if (mandatory_gtk3)
{
gtk_widget_set_margin_top(widget, vert_padding);
gtk_widget_set_margin_bottom(widget, vert_padding);
gtk_widget_set_margin_start(widget, horiz_padding);
gtk_widget_set_margin_end(widget, horiz_padding);
}
#elif GTK_CHECK_VERSION(3, 4, 0)
gtk_widget_set_margin_top(widget, vert_padding);
gtk_widget_set_margin_bottom(widget, vert_padding);
gtk_widget_set_margin_left(widget, horiz_padding);
gtk_widget_set_margin_right(widget, horiz_padding);
#endif
(void)widget;
(void)horiz_padding;
(void)vert_padding;
(void)mandatory_gtk3;
}
void iupgtkClearSizeStyleCSS(GtkWidget* widget)
{
#if GTK_CHECK_VERSION(3, 0, 0)
GtkStyleContext *context = gtk_widget_get_style_context(widget);
const char* str = "*{ padding-bottom: 0px ; padding-top: 0px; padding-left: 2px; padding-right: 2px; "
"margin-bottom: 0px; margin-top: 0px; margin-left: 0px; margin-right: 0px; }";
GtkCssProvider *provider = gtk_css_provider_new();
gtk_css_provider_load_from_data(GTK_CSS_PROVIDER(provider), str, -1, NULL);
gtk_style_context_add_provider(context, GTK_STYLE_PROVIDER(provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
g_object_unref(provider);
#endif
}
/* Deprecated but still used for GTK2:
gdk_bitmap_create_from_data (since 2.22)
gdk_font_id
gdk_font_from_description
*/
| 27.112236 | 161 | 0.692138 |
b7c8b1c7e91d87340658520c95c89806e27ebdf1 | 59 | h | C | c_quizz/src/pretraitement_tri.h | jeanphilippeD/school | 4dd6634f882446a0699ea1a8256d8f916fd0c4c2 | [
"MIT"
] | null | null | null | c_quizz/src/pretraitement_tri.h | jeanphilippeD/school | 4dd6634f882446a0699ea1a8256d8f916fd0c4c2 | [
"MIT"
] | null | null | null | c_quizz/src/pretraitement_tri.h | jeanphilippeD/school | 4dd6634f882446a0699ea1a8256d8f916fd0c4c2 | [
"MIT"
] | null | null | null | extern void tri_par_fitness_croissant(int,char**,double*);
| 29.5 | 58 | 0.813559 |
314e105a74704436ec6c98aea9cc89682446d9f6 | 276 | h | C | Pods/Headers/Public/YPProtocolMediator/YPDefaultModule.h | fmouer/YPProtocolMediatorDemo | 935a85815e05d252fdc45bed801b1ad995b48cec | [
"MIT"
] | 3 | 2019-07-22T06:24:50.000Z | 2020-04-24T08:25:46.000Z | Pods/Headers/Public/YPProtocolMediator/YPDefaultModule.h | fmouer/YPProtocolMediatorDemo | 935a85815e05d252fdc45bed801b1ad995b48cec | [
"MIT"
] | null | null | null | Pods/Headers/Public/YPProtocolMediator/YPDefaultModule.h | fmouer/YPProtocolMediatorDemo | 935a85815e05d252fdc45bed801b1ad995b48cec | [
"MIT"
] | null | null | null | //
// YPDefaultModule.h
// YPProtocolMediatorDemo
//
// Created by huangzhimou on 2019/4/27.
// Copyright © 2019 fmouer All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface YPDefaultModule : NSObject
@end
NS_ASSUME_NONNULL_END
| 15.333333 | 48 | 0.757246 |
2ebfdf9d4b6d1590e1399c3e7ef50c3c24529157 | 925 | h | C | System/Library/PrivateFrameworks/GraphicsServices.framework/_UIFontExtraData.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | 4 | 2019-08-27T18:03:47.000Z | 2021-09-18T06:29:00.000Z | System/Library/PrivateFrameworks/GraphicsServices.framework/_UIFontExtraData.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/GraphicsServices.framework/_UIFontExtraData.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.0
* on Saturday, August 24, 2019 at 9:41:50 PM Mountain Standard Time
* Operating System: Version 12.4 (Build 16M568)
* Image Source: /System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <GraphicsServices/GraphicsServices-Structs.h>
@class NSCharacterSet, NSString;
@interface _UIFontExtraData : NSObject {
NSCharacterSet* _coveredCharacterSet;
double _ascender;
double _descender;
double _lineHeight;
double _lineGap;
struct {
unsigned _initialized : 1;
unsigned _isSystemFont : 1;
unsigned _hasKernPair : 1;
unsigned _unused : 1;
unsigned _isIBTextStyleFont : 1;
unsigned _isIBScaledFont : 1;
} _fFlags;
NSString* _textStyleForScaling;
double _pointSizeForScaling;
double _maximumPointSizeAfterScaling;
}
-(void)dealloc;
@end
| 25.694444 | 93 | 0.778378 |
c883e89a843a788f2fa58664ebebed68d9c779a2 | 892 | h | C | android_webview/common/aw_switches.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | android_webview/common/aw_switches.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | android_webview/common/aw_switches.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ANDROID_WEBVIEW_COMMON_AW_SWITCHES_H_
#define ANDROID_WEBVIEW_COMMON_AW_SWITCHES_H_
namespace switches {
extern const char kWebViewLogJsConsoleMessages[];
extern const char kWebViewSandboxedRenderer[];
extern const char kWebViewDisableSafebrowsingSupport[];
extern const char kWebViewEnableVulkan[];
extern const char kWebViewSafebrowsingBlockAllResources[];
extern const char kHighlightAllWebViews[];
extern const char kWebViewVerboseLogging[];
extern const char kFinchSeedExpirationAge[];
extern const char kFinchSeedIgnorePendingDownload[];
extern const char kFinchSeedMinDownloadPeriod[];
extern const char kFinchSeedMinUpdatePeriod[];
} // namespace switches
#endif // ANDROID_WEBVIEW_COMMON_AW_SWITCHES_H_
| 35.68 | 73 | 0.835202 |
aeaf9284d64a98a464eb8008c549f8ebb61e6d2d | 2,884 | h | C | include/sead/resource/seadResource.h | xiivler/smo-practice | 7df6dd21809e35e4af585a792c1fcdc3ee290132 | [
"MIT"
] | 14 | 2021-12-10T20:21:00.000Z | 2022-03-28T00:05:30.000Z | include/sead/resource/seadResource.h | xiivler/smo-practice | 7df6dd21809e35e4af585a792c1fcdc3ee290132 | [
"MIT"
] | 5 | 2021-12-14T16:02:41.000Z | 2022-03-23T22:05:46.000Z | include/sead/resource/seadResource.h | xiivler/smo-practice | 7df6dd21809e35e4af585a792c1fcdc3ee290132 | [
"MIT"
] | 10 | 2021-12-10T20:50:53.000Z | 2022-03-14T02:58:53.000Z | #ifndef SEAD_RESOURCE_H_
#define SEAD_RESOURCE_H_
#include <sead/basis/seadNew.h>
#include <sead/basis/seadTypes.h>
#include <sead/container/seadTList.h>
#include <sead/heap/seadDisposer.h>
#include <sead/heap/seadHeap.h>
#include <sead/prim/seadBitFlag.h>
#include <sead/resource/seadDecompressor.h>
#include <sead/resource/seadResourceMgr.h>
namespace sead
{
class Resource
{
public:
SEAD_RTTI_BASE(Resource)
Resource();
virtual ~Resource();
};
class DirectResource : public Resource
{
SEAD_RTTI_OVERRIDE(DirectResource, Resource)
public:
DirectResource();
~DirectResource() override;
virtual s32 getLoadDataAlignment() const;
virtual void doCreate_(u8* buffer, u32 bufferSize, Heap* heap);
void create(u8* buffer, u32 bufferSize, u32 allocSize, bool allocated, Heap* heap);
u8* getRawData() const { return mRawData; }
u32 getRawSize() const { return mRawSize; }
u32 getBufferSize() const { return mBufferSize; }
static constexpr size_t cLoadDataAlignment = 4;
protected:
u8* mRawData = 0;
u32 mRawSize = 0;
u32 mBufferSize = 0;
BitFlag32 mSettingFlag;
};
class ResourceFactory : public TListNode<ResourceFactory*>, public IDisposer
{
SEAD_RTTI_BASE(ResourceFactory)
public:
ResourceFactory() : TListNode<ResourceFactory*>(this), IDisposer(), mExt() {}
virtual ~ResourceFactory();
virtual Resource* tryCreate(const ResourceMgr::LoadArg& loadArg) = 0;
virtual Resource* tryCreateWithDecomp(const ResourceMgr::LoadArg& loadArg,
Decompressor* decompressor) = 0;
virtual Resource* create(const ResourceMgr::CreateArg& createArg) = 0;
const SafeString& getExt() const { return mExt; }
void setExt(const SafeString& ext) { mExt = ext; }
protected:
FixedSafeString<32> mExt;
};
class DirectResourceFactoryBase : public ResourceFactory
{
SEAD_RTTI_OVERRIDE(DirectResourceFactoryBase, ResourceFactory)
public:
DirectResourceFactoryBase() : ResourceFactory() {}
~DirectResourceFactoryBase() override {}
Resource* create(const ResourceMgr::CreateArg& createArg) override;
Resource* tryCreate(const ResourceMgr::LoadArg& loadArg) override;
Resource* tryCreateWithDecomp(const ResourceMgr::LoadArg& loadArg,
Decompressor* decompressor) override;
virtual DirectResource* newResource_(Heap* heap, s32 alignment) = 0;
};
template <typename T>
class DirectResourceFactory : public DirectResourceFactoryBase
{
SEAD_RTTI_OVERRIDE(DirectResourceFactory<T>, DirectResourceFactoryBase)
public:
DirectResourceFactory() : DirectResourceFactoryBase() {}
~DirectResourceFactory() override {}
DirectResource* newResource_(Heap* heap, s32 alignment) override
{
return new (heap, alignment) T;
}
};
} // namespace sead
#endif // SEAD_RESOURCE_H_
| 28 | 87 | 0.719487 |
834bd52797215a5132027b4296700c8e99e60ccc | 8,317 | c | C | pr4/01_dlist.c | Bearjonok/TimP_Lab3_728_1 | 868394434868236f16687e338cf38aa1f9654f6c | [
"BSD-3-Clause"
] | null | null | null | pr4/01_dlist.c | Bearjonok/TimP_Lab3_728_1 | 868394434868236f16687e338cf38aa1f9654f6c | [
"BSD-3-Clause"
] | null | null | null | pr4/01_dlist.c | Bearjonok/TimP_Lab3_728_1 | 868394434868236f16687e338cf38aa1f9654f6c | [
"BSD-3-Clause"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
typedef struct node {
int value; // значение, которое хранит узел
struct node *next; // ссылка на следующий элемент списка
struct node *prev; // ссылка на предыдущий элемент списка
} node;
typedef struct list {
struct node *head; // начало списка
struct node *tail; // конец списка
} list;
// инициализация пустого списка
void init(list *l);
// удалить все элементы из списка
void clean(list *l);
// проверка на пустоту списка
bool is_empty(list *l);
// поиск элемента по значению. вернуть NULL если элемент не найден
node *find(list *l, int value);
// вставка значения в конец списка, вернуть 0 если успешно
int push_back(list *l, int value);
// вставка значения в начало списка, вернуть 0 если успешно
int push_front(list *l, int value);
// вставка значения после указанного узла, вернуть 0 если успешно
int insert_after(list *l, node *n, int value);
// вставка значения перед указанным узлом, вернуть 0 если успешно
int insert_before(list *l, node *n, int value);
// удалить первый элемент из списка с указанным значением,
// вернуть 0 если успешно
int remove_first(list *l, int value);
// удалить последний элемент из списка с указанным значением,
// вернуть 0 если успешно
int remove_last(list *l, int value);
// вывести все значения из списка в прямом порядке через пробел,
// после окончания вывода перейти на новую строку
void print(list *l);
// вывести все значения из списка в обратном порядке через пробел,
// после окончания вывода перейти на новую строку
void print_invers(list *l);
// Проверка наличия элемента
void find_id(list *l, int value);
int main() {
int n, x, elem;
int i = 1;
list l = {0};
int check = scanf("%d", &n);
assert(check == 1);
while (i <= n) {
check = scanf("%d", &x);
assert(check == 1);
push_back(&l, x);
i++;
}
print(&l);
printf("\n");
i = 1; //Нахождение элементов в списке
while (i <= 3) {
check = scanf("%d", &x);
assert(check == 1);
find_id(&l, x);
i++;
}
printf("\n");
check = scanf("%d", &x); //Добавление в конец
assert(check == 1);
push_back(&l, x);
print_invers(&l);
printf("\n");
check = scanf("%d", &x); //Добавлние в начало
assert(check == 1);
push_front(&l, x);
print(&l);
printf("\n");
check = scanf("%d", &x); //Добавление после указанного элемента
assert(check == 1);
check = scanf("%d", &elem);
assert(check == 1);
node *c_node = l.head; //Поиск номера элемента
int numb = 1;
while ((c_node != NULL)&&(numb!= x)) {
c_node = c_node->next;
numb++;
}
node *insert_head = c_node;
insert_after(&l, insert_head, elem);
print_invers(&l);
printf("\n");
check = scanf("%d", &x); //Добавление перед указанным элементом
assert(check == 1);
check = scanf("%d", &elem);
assert(check == 1);
node *c_node1 = l.head;
int numb1 = 1;
while ((c_node1 != NULL)&&(numb1!= x)) {
c_node1 = c_node1->next;
numb1++;
}
node *insert_tail = c_node1;
insert_before(&l, insert_tail, elem);
print(&l);
printf("\n");
check = scanf("%d", &x); //Удалить первый элемент равный введенному
assert(check == 1);
remove_first(&l, x);
print_invers(&l);
printf("\n");
check = scanf("%d", &x); //Удалить последний элемент равный введенному
assert(check == 1);
remove_last(&l, x);
print(&l);
printf("\n");
clean(&l); //Очистить список
return 0;
}
// инициализация пустого списка
void init(list *l) {
l->head = NULL;
l->tail = NULL;
}
// удалить все элементы из списка
void clean(list *l) {
node *c_node = l->head;
node *n_node = c_node->next;
while(n_node != NULL) {
free(c_node);
c_node = n_node;
n_node = c_node->next;
}
l->head = NULL;
l->tail = NULL;
}
// проверка на пустоту списка
bool is_empty(list *l) {
if(l->head == NULL && l->tail == NULL) {
return true;
}
return false;
}
// поиск элемента по значению. вернуть NULL если элемент не найден
node *find(list *l, int value) {
node *c_node = l->head;
while(c_node != NULL) {
if(c_node->value == value) {
return c_node;
}
c_node = c_node->next;
}
return NULL;
}
// вставка значения в конец списка, вернуть 0 если успешно
int push_back(list *l, int value) {
node *push;
push = malloc(sizeof(node));
push->value = value;
push->next = NULL;
push->prev = l->tail; // Если в спикске один элемент то prev и next = NULL
if(l->head == NULL) {
l->head = push;
l->tail = push;
} else {
l->tail->next = push;
l->tail = push;
}
return 0;
}
// вставка значения в начало списка, вернуть 0 если успешно
int push_front(list *l, int value) {
node *push;
push = malloc(sizeof(node));
push->value = value;
push->next = l->head;
push->prev = NULL;
if(l->head == NULL) {
l->head = push;
l->tail = push;
} else {
l->head->prev = push;
l->head = push;
}
return 0;
}
// вставка значения после указанного узла, вернуть 0 если успешно
int insert_after(list *l, node *n, int value) {
node *insert;
insert = malloc(sizeof(node));
insert->value = value;
insert->next = n->next;
insert->prev = n;
n->next->prev = insert;
n->next = insert;
if(insert->next == NULL) {
l->head = insert;
}
return 0;
}
// вставка значения перед указанным узлом, вернуть 0 если успешно
int insert_before(list *l, node *n, int value) {
node *insert;
insert = malloc(sizeof(node));
insert->value = value;
insert->next = n;
insert->prev = n->prev;
n->prev->next = insert;
n->prev = insert;
if(insert->prev == NULL) {
l->head = insert;
}
return 0;
}
// удалить первый элемент из списка с указанным значением,
// вернуть 0 если успешно
int remove_first(list *l, int value) {
if(l->head == NULL) {
return -1;
}
node *c_node = l->head;
while (c_node->next) {
if (c_node->value == value) {
if (c_node->prev == NULL) {
l->head = c_node->next;
c_node -> next -> prev = NULL;
free(c_node);
return 0;
}
if (c_node->next == NULL) {
l->tail = c_node->prev;
c_node->prev->next = NULL;
free(c_node);
return 0;
}
c_node->prev->next = c_node->next;
c_node->next->prev = c_node->prev;
free(c_node);
return 0;
}
c_node = c_node->next;
}
return -1;
}
// удалить последний элемент из списка с указанным значением,
// вернуть 0 если успешно
int remove_last(list *l, int value) {
if(l->tail == NULL) {
return -1;
}
node *c_node = l->tail;
while (c_node->prev) {
if (c_node->value == value) {
if (c_node->next == NULL) {
l->tail = c_node->prev;
c_node->prev->next = NULL;
free(c_node);
return 0;
}
if (c_node->prev == NULL) {
l->head = c_node->next;
c_node -> next -> prev = NULL;
free(c_node);
return 0;
}
c_node->prev->next = c_node->next;
c_node->next->prev = c_node->prev;
free(c_node);
return 0;
}
c_node = c_node->prev;
}
return -1;
}
// вывести все значения из списка в прямом порядке через пробел,
// после окончания вывода перейти на новую строку
void print(list *l) {
node *c_node = l->head;
while (c_node != NULL) {
printf ("%d ", c_node -> value);
c_node = c_node->next;
}
printf (" ");
}
// вывести все значения из списка в обратном порядке через пробел,
// после окончания вывода перейти на новую строку
void print_invers(list *l) {
node *c_node = l->tail;
do {
printf ("%d ", c_node -> value);
c_node = c_node->prev;
} while (c_node != NULL);
printf (" ");
}
// Проверка наличия элемента
void find_id(list *l, int value) {
if (find(l, value) != NULL) {
printf("1 ");
} else {
printf("0 ");
}
}
| 24.606509 | 78 | 0.57124 |
2656a751f8e88463378c93368bf6383ed6eeaeba | 7,636 | c | C | src/ebml_writer.c | arkanis/smeb | 2d581fdd332eb6ecd8c0d180072ea90c3ecb6dcb | [
"MIT"
] | null | null | null | src/ebml_writer.c | arkanis/smeb | 2d581fdd332eb6ecd8c0d180072ea90c3ecb6dcb | [
"MIT"
] | null | null | null | src/ebml_writer.c | arkanis/smeb | 2d581fdd332eb6ecd8c0d180072ea90c3ecb6dcb | [
"MIT"
] | null | null | null | #include <string.h>
#include "ebml_writer.h"
//
// Functions to start and end elements that should contain other elements
//
/**
* Writes the element ID and a 4 byte zero data size to reserve space for the proper data
* size. The offset to this 4 byte space is returned.
*/
long ebml_element_start(FILE* file, uint32_t element_id) {
ebml_write_element_id(file, element_id);
long length_offset = ftell(file);
ebml_write_data_size(file, 0, 4);
return length_offset;
}
/**
* Ends an element that was started with `ebml_element_start()`. For this it calculates
* the number of bytes written since the elment has been started and writes them to the
* 4 byte space reserved for the element size.
*/
void ebml_element_end(FILE* file, long offset) {
long current_offset = ftell(file);
fseek(file, offset, SEEK_SET);
ebml_write_data_size(file, current_offset - offset - 4, 4);
fseek(file, current_offset, SEEK_SET);
}
/**
* Starts an element with unknown data size. Useful for streaming.
*/
void ebml_element_start_unkown_data_size(FILE* file, uint32_t element_id) {
ebml_write_element_id(file, element_id);
ebml_write_unkown_data_size(file);
}
//
// Scalar element functions
//
void ebml_element_uint(FILE* file, uint32_t element_id, uint64_t value) {
size_t required_data_bytes = ebml_unencoded_uint_required_bytes(value);
ebml_write_element_id(file, element_id);
ebml_write_data_size(file, required_data_bytes, 0);
value = __builtin_bswap64(value);
uint8_t* value_ptr = (uint8_t*)&value;
fwrite(value_ptr + sizeof(value) - required_data_bytes, required_data_bytes, 1, file);
}
void ebml_element_int(FILE* file, uint32_t element_id, int64_t value) {
size_t required_data_bytes = ebml_unencoded_int_required_bytes(value);
ebml_write_element_id(file, element_id);
ebml_write_data_size(file, required_data_bytes, 0);
value = __builtin_bswap64(value);
uint8_t* value_ptr = (uint8_t*)&value;
fwrite(value_ptr + sizeof(value) - required_data_bytes, required_data_bytes, 1, file);
}
void ebml_element_string(FILE* file, uint32_t element_id, const char* value) {
size_t required_data_bytes = strlen(value);
ebml_write_element_id(file, element_id);
ebml_write_data_size(file, required_data_bytes, 0);
fwrite(value, required_data_bytes, 1, file);
}
void ebml_element_float(FILE* file, uint32_t element_id, float value) {
size_t required_data_bytes = sizeof(value);
ebml_write_element_id(file, element_id);
ebml_write_data_size(file, required_data_bytes, 0);
uint32_t* float_ptr = (uint32_t*)&value;
*float_ptr = __builtin_bswap32(*float_ptr);
fwrite(&value, required_data_bytes, 1, file);
}
void ebml_element_double(FILE* file, uint32_t element_id, double value) {
size_t required_data_bytes = sizeof(value);
ebml_write_element_id(file, element_id);
ebml_write_data_size(file, required_data_bytes, 0);
uint64_t* double_ptr = (uint64_t*)&value;
*double_ptr = __builtin_bswap64(*double_ptr);
fwrite(&value, required_data_bytes, 1, file);
}
//
// Low level functions to write encoded values
//
/**
* Writes an EBML ID with the appropiate number of bytes.
*
* EBML IDs are already encoded variable length uints with up to 4 byte. When writing an ID we
* just need to figure out many bytes we're supposed to write. However we always use uint32_t
* (4 byte uints) in the API. Therefore we don't need to interprete the length descriptor but
* can just skip all leading zero _bytes_ of the 32bit ID.
*
* Like all EBML values the ID is written in big endian byte order.
*/
size_t ebml_write_element_id(FILE* file, uint32_t element_id) {
int leading_zero_bits = __builtin_clz(element_id);
int length_in_bytes = 4 - leading_zero_bits / 8;
uint32_t big_endian_id = __builtin_bswap32(element_id);
uint8_t* big_endian_id_ptr = (uint8_t*)&big_endian_id;
return fwrite(big_endian_id_ptr + sizeof(uint32_t) - length_in_bytes, length_in_bytes, 1, file);
}
/**
* Writes an EBML data size. Takes into account that bit patterns of all ones are
* reserved for an unknown size. In this case the next larger representation is
* used.
*
* The number of bytes written can be specified in the `bytes` argument. When set
* to `0` as few bytes as possible are written.
*/
size_t ebml_write_data_size(FILE* file, uint64_t value, size_t bytes) {
if (bytes == 0)
bytes = ebml_encoded_uint_required_bytes(value);
// Length to large to be encoded
if (bytes == 0)
return 0;
// We can store 7 bits per byte. If they are all 1s we have a reserved length
// and need the next larger prepresentation.
size_t one_count = __builtin_popcountll(value);
if (one_count >= bytes * 7)
bytes++;
// Create the length descriptor (a 1 bit after sufficient 0 bits, all at the
// right byte in the 64 bit value). Combine it with the value and store the
// result in big endian byte order.
uint64_t prefix = 1LL << (8 - bytes + 8 * (bytes - 1));
value = __builtin_bswap64(value | prefix);
// Finally write the required amount of bytes
uint8_t* value_ptr = (uint8_t*)&value;
return fwrite(value_ptr + 8 - bytes, bytes, 1, file);
}
/**
* Writes an unknown data size. This is a data size field with all bits set to 1.
*/
size_t ebml_write_unkown_data_size(FILE* file) {
uint8_t length = 0xff;
return fwrite(&length, 1, sizeof(length), file);
}
//
// Utility functions
//
/**
* Returns the number of bytes required to encode the uint value in EBML.
* Returns 0 if the value is to large to be encoded.
*
* Basic idea is to get the index of the first set bit (using the GCC __builtin_clz())
* and caculate how many bytes we need to represent that number.
*
* leading zeros: 64 -7 -7 -7 -7 -7 -7 -7 -7
* 64 57 50 43 36 29 22 15 8
* required bytes: 1 2 3 4 5 6 7 8
*
* This calculates does the trick: 8 - (leading zeros - 8) / 7
*
* 1. Move bits to origin: leading zeros - 8
* 2. Scale down to index of 7 bit group the first bit is in: ... / 7
* 3. Calculate the number of bytes needed: 8 - ...
* If the byte is in group 0 we need 8 bytes, if it's in
* group 7 we need 1 byte.
*/
size_t ebml_encoded_uint_required_bytes(uint64_t value) {
// Use 1 byte to encode zero
if (value == 0)
return 1;
int leading_zeros = __builtin_clzll(value);
if (leading_zeros < 8) {
fprintf(stderr, "EBML: Value 0x%016lx to large to encode as uint!\n", value);
return 0;
}
return 8 - (leading_zeros - 8) / 7;
}
/**
* Returns the number of bytes required to encode the int value in EBML.
* Returns 0 if the value is out of the encodable range.
*
* Same logic as ebml_encoded_uint_required_bytes(). We take negative
* numbers into account by counting the leading sign bits instead of zeros.
*/
size_t ebml_encoded_int_required_bytes(int64_t value) {
//int leading_sign_bits = __builtin_clrsbll(value);
int leading_sign_bits = __builtin_clzll( (value >= 0) ? value : ~value ) - 1;
if (leading_sign_bits < 8) {
fprintf(stderr, "EBML: Value %ld out of encodable int range!\n", value);
return 0;
}
return 8 - (leading_sign_bits - 8) / 7;
}
size_t ebml_unencoded_uint_required_bytes(uint64_t value) {
int leading_zeros = __builtin_clzll(value);
int value_bits = 64 - leading_zeros;
int value_bytes = (value_bits - 1) / 8 + 1;
return value_bytes;
}
size_t ebml_unencoded_int_required_bytes(int64_t value) {
//int leading_sign_bits = __builtin_clrsbll(value);
int leading_sign_bits = __builtin_clzll( (value >= 0) ? value : ~value ) - 1;
int value_bits = 64 - leading_sign_bits;
int value_bytes = (value_bits - 1) / 8 + 1;
return value_bytes;
} | 32.632479 | 97 | 0.726427 |
64adece3672a178e0ead01a934f144c5a4776246 | 2,965 | h | C | Dev/Cpp/EffekseerRendererMetal/EffekseerRenderer/ShaderHeader/sprite_lit_vs.h | riccardobl/Effekseer | 40dea55d7d2fafa365e4365adfe58a1059a5a980 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Dev/Cpp/EffekseerRendererMetal/EffekseerRenderer/ShaderHeader/sprite_lit_vs.h | riccardobl/Effekseer | 40dea55d7d2fafa365e4365adfe58a1059a5a980 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Dev/Cpp/EffekseerRendererMetal/EffekseerRenderer/ShaderHeader/sprite_lit_vs.h | riccardobl/Effekseer | 40dea55d7d2fafa365e4365adfe58a1059a5a980 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | static const char metal_sprite_lit_vs[] = R"(mtlcode
#pragma clang diagnostic ignored "-Wmissing-prototypes"
#include <metal_stdlib>
#include <simd/simd.h>
using namespace metal;
struct VS_Input
{
float3 Pos;
float4 Color;
float4 Normal;
float4 Tangent;
float2 UV1;
float2 UV2;
};
struct VS_Output
{
float4 PosVS;
float4 Color;
float2 UV;
float3 WorldN;
float3 WorldB;
float3 WorldT;
float4 PosP;
};
struct VS_ConstantBuffer
{
float4x4 mCamera;
float4x4 mProj;
float4 mUVInversed;
float4 mflipbookParameter;
};
struct main0_out
{
float4 _entryPointOutput_Color [[user(locn0)]];
float2 _entryPointOutput_UV [[user(locn1)]];
float3 _entryPointOutput_WorldN [[user(locn2)]];
float3 _entryPointOutput_WorldB [[user(locn3)]];
float3 _entryPointOutput_WorldT [[user(locn4)]];
float4 _entryPointOutput_PosP [[user(locn5)]];
float4 gl_Position [[position]];
};
struct main0_in
{
float3 Input_Pos [[attribute(0)]];
float4 Input_Color [[attribute(1)]];
float4 Input_Normal [[attribute(2)]];
float4 Input_Tangent [[attribute(3)]];
float2 Input_UV1 [[attribute(4)]];
float2 Input_UV2 [[attribute(5)]];
};
static inline __attribute__((always_inline))
VS_Output _main(VS_Input Input, constant VS_ConstantBuffer& v_21)
{
float4x4 mCameraProj = transpose(v_21.mProj * v_21.mCamera);
VS_Output Output = VS_Output{ float4(0.0), float4(0.0), float2(0.0), float3(0.0), float3(0.0), float3(0.0), float4(0.0) };
float4 worldNormal = float4((Input.Normal.xyz - float3(0.5)) * 2.0, 0.0);
float4 worldTangent = float4((Input.Tangent.xyz - float3(0.5)) * 2.0, 0.0);
float4 worldBinormal = float4(cross(worldNormal.xyz, worldTangent.xyz), 0.0);
float4 worldPos = float4(Input.Pos.x, Input.Pos.y, Input.Pos.z, 1.0);
Output.PosVS = worldPos * mCameraProj;
Output.Color = Input.Color;
float2 uv1 = Input.UV1;
uv1.y = v_21.mUVInversed.x + (v_21.mUVInversed.y * uv1.y);
Output.UV = uv1;
Output.WorldN = worldNormal.xyz;
Output.WorldB = worldBinormal.xyz;
Output.WorldT = worldTangent.xyz;
Output.PosP = Output.PosVS;
return Output;
}
vertex main0_out main0(main0_in in [[stage_in]], constant VS_ConstantBuffer& v_21 [[buffer(0)]])
{
main0_out out = {};
VS_Input Input;
Input.Pos = in.Input_Pos;
Input.Color = in.Input_Color;
Input.Normal = in.Input_Normal;
Input.Tangent = in.Input_Tangent;
Input.UV1 = in.Input_UV1;
Input.UV2 = in.Input_UV2;
VS_Output flattenTemp = _main(Input, v_21);
out.gl_Position = flattenTemp.PosVS;
out._entryPointOutput_Color = flattenTemp.Color;
out._entryPointOutput_UV = flattenTemp.UV;
out._entryPointOutput_WorldN = flattenTemp.WorldN;
out._entryPointOutput_WorldB = flattenTemp.WorldB;
out._entryPointOutput_WorldT = flattenTemp.WorldT;
out._entryPointOutput_PosP = flattenTemp.PosP;
return out;
}
)";
| 28.786408 | 126 | 0.69511 |
d3bcf352a43785125c4811fb5d99d366296a7020 | 12,243 | h | C | src/ROCALL/KiServiceTable.h | tkreuzer/ROCALL | c64faa8d05d718464d93c2cb1b7e84f4b16caed4 | [
"MIT"
] | 2 | 2018-12-20T20:10:26.000Z | 2020-01-07T23:41:31.000Z | src/ROCALL/KiServiceTable.h | tkreuzer/ROCALL | c64faa8d05d718464d93c2cb1b7e84f4b16caed4 | [
"MIT"
] | null | null | null | src/ROCALL/KiServiceTable.h | tkreuzer/ROCALL | c64faa8d05d718464d93c2cb1b7e84f4b16caed4 | [
"MIT"
] | null | null | null | /*
* ReactOS system call definitions
* Source: ReactOS source code
* Author: Timo Kreuzer <timo.kreuzer@reactos.org>
* License: MIT (see LICENSE file in the root of this repository)
*/
ServiceMacro("AcceptConnectPort", 6)
ServiceMacro("AccessCheck", 8)
ServiceMacro("AccessCheckAndAuditAlarm", 11)
ServiceMacro("AccessCheckByType", 11)
ServiceMacro("AccessCheckByTypeAndAuditAlarm", 16)
ServiceMacro("AccessCheckByTypeResultList", 11)
ServiceMacro("AccessCheckByTypeResultListAndAuditAlarm", 16)
ServiceMacro("AccessCheckByTypeResultListAndAuditAlarmByHandle", 17)
ServiceMacro("AddAtom", 3)
ServiceMacro("AddBootEntry", 2)
ServiceMacro("AddDriverEntry", 2)
ServiceMacro("AdjustGroupsToken", 6)
ServiceMacro("AdjustPrivilegesToken", 6)
ServiceMacro("AlertResumeThread", 2)
ServiceMacro("AlertThread", 1)
ServiceMacro("AllocateLocallyUniqueId", 1)
ServiceMacro("AllocateUserPhysicalPages", 3)
ServiceMacro("AllocateUuids", 4)
ServiceMacro("AllocateVirtualMemory", 6)
ServiceMacro("ApphelpCacheControl", 2)
ServiceMacro("AreMappedFilesTheSame", 2)
ServiceMacro("AssignProcessToJobObject", 2)
ServiceMacro("CallbackReturn", 3)
ServiceMacro("CancelDeviceWakeupRequest", 1)
ServiceMacro("CancelIoFile", 2)
ServiceMacro("CancelTimer", 2)
ServiceMacro("ClearEvent", 1)
ServiceMacro("Close", 1)
ServiceMacro("CloseObjectAuditAlarm", 3)
ServiceMacro("CompactKeys", 2)
ServiceMacro("CompareTokens", 3)
ServiceMacro("CompleteConnectPort", 1)
ServiceMacro("CompressKey", 1)
ServiceMacro("ConnectPort", 8)
ServiceMacro("Continue", 2)
ServiceMacro("CreateDebugObject", 4)
ServiceMacro("CreateDirectoryObject", 3)
ServiceMacro("CreateEvent", 5)
ServiceMacro("CreateEventPair", 3)
ServiceMacro("CreateFile", 11)
ServiceMacro("CreateIoCompletion", 4)
ServiceMacro("CreateJobObject", 3)
ServiceMacro("CreateJobSet", 3)
ServiceMacro("CreateKey", 7)
ServiceMacro("CreateMailslotFile", 8)
ServiceMacro("CreateMutant", 4)
ServiceMacro("CreateNamedPipeFile", 14)
ServiceMacro("CreatePagingFile", 4)
ServiceMacro("CreatePort", 5)
ServiceMacro("CreateProcess", 8)
ServiceMacro("CreateProcessEx", 9)
ServiceMacro("CreateProfile", 9)
ServiceMacro("CreateSection", 7)
ServiceMacro("CreateSemaphore", 5)
ServiceMacro("CreateSymbolicLinkObject", 4)
ServiceMacro("CreateThread", 8)
ServiceMacro("CreateTimer", 4)
ServiceMacro("CreateToken", 13)
ServiceMacro("CreateWaitablePort", 5)
ServiceMacro("DebugActiveProcess", 2)
ServiceMacro("DebugContinue", 3)
ServiceMacro("DelayExecution", 2)
ServiceMacro("DeleteAtom", 1)
ServiceMacro("DeleteBootEntry", 1)
ServiceMacro("DeleteDriverEntry", 1)
ServiceMacro("DeleteFile", 1)
ServiceMacro("DeleteKey", 1)
ServiceMacro("DeleteObjectAuditAlarm", 3)
ServiceMacro("DeleteValueKey", 2)
ServiceMacro("DeviceIoControlFile", 10)
ServiceMacro("DisplayString", 1)
ServiceMacro("DuplicateObject", 7)
ServiceMacro("DuplicateToken", 6)
ServiceMacro("EnumerateBootEntries", 2)
ServiceMacro("EnumerateDriverEntries", 2)
ServiceMacro("EnumerateKey", 6)
ServiceMacro("EnumerateSystemEnvironmentValuesEx", 3)
ServiceMacro("EnumerateValueKey", 6)
ServiceMacro("ExtendSection", 2)
ServiceMacro("FilterToken", 6)
ServiceMacro("FindAtom", 3)
ServiceMacro("FlushBuffersFile", 2)
ServiceMacro("FlushInstructionCache", 3)
ServiceMacro("FlushKey", 1)
ServiceMacro("FlushVirtualMemory", 4)
ServiceMacro("FlushWriteBuffer", 0)
ServiceMacro("FreeUserPhysicalPages", 3)
ServiceMacro("FreeVirtualMemory", 4)
ServiceMacro("FsControlFile", 10)
ServiceMacro("GetContextThread", 2)
ServiceMacro("GetDevicePowerState", 2)
ServiceMacro("GetPlugPlayEvent", 4)
ServiceMacro("GetWriteWatch", 7)
ServiceMacro("ImpersonateAnonymousToken", 1)
ServiceMacro("ImpersonateClientOfPort", 2)
ServiceMacro("ImpersonateThread", 3)
ServiceMacro("InitializeRegistry", 1)
ServiceMacro("InitiatePowerAction", 4)
ServiceMacro("IsProcessInJob", 2)
ServiceMacro("IsSystemResumeAutomatic", 0)
ServiceMacro("ListenPort", 2)
ServiceMacro("LoadDriver", 1)
ServiceMacro("LoadKey", 2)
ServiceMacro("LoadKey2", 3)
ServiceMacro("LoadKeyEx", 4)
ServiceMacro("LockFile", 10)
ServiceMacro("LockProductActivationKeys", 2)
ServiceMacro("LockRegistryKey", 1)
ServiceMacro("LockVirtualMemory", 4)
ServiceMacro("MakePermanentObject", 1)
ServiceMacro("MakeTemporaryObject", 1)
ServiceMacro("MapUserPhysicalPages", 3)
ServiceMacro("MapUserPhysicalPagesScatter", 3)
ServiceMacro("MapViewOfSection", 10)
ServiceMacro("ModifyBootEntry", 1)
ServiceMacro("ModifyDriverEntry", 1)
ServiceMacro("NotifyChangeDirectoryFile", 9)
ServiceMacro("NotifyChangeKey", 10)
ServiceMacro("NotifyChangeMultipleKeys", 12)
ServiceMacro("OpenDirectoryObject", 3)
ServiceMacro("OpenEvent", 3)
ServiceMacro("OpenEventPair", 3)
ServiceMacro("OpenFile", 6)
ServiceMacro("OpenIoCompletion", 3)
ServiceMacro("OpenJobObject", 3)
ServiceMacro("OpenKey", 3)
ServiceMacro("OpenMutant", 3)
ServiceMacro("OpenObjectAuditAlarm", 12)
ServiceMacro("OpenProcess", 4)
ServiceMacro("OpenProcessToken", 3)
ServiceMacro("OpenProcessTokenEx", 4)
ServiceMacro("OpenSection", 3)
ServiceMacro("OpenSemaphore", 3)
ServiceMacro("OpenSymbolicLinkObject", 3)
ServiceMacro("OpenThread", 4)
ServiceMacro("OpenThreadToken", 4)
ServiceMacro("OpenThreadTokenEx", 5)
ServiceMacro("OpenTimer", 3)
ServiceMacro("PlugPlayControl", 3)
ServiceMacro("PowerInformation", 5)
ServiceMacro("PrivilegeCheck", 3)
ServiceMacro("PrivilegeObjectAuditAlarm", 6)
ServiceMacro("PrivilegedServiceAuditAlarm", 5)
ServiceMacro("ProtectVirtualMemory", 5)
ServiceMacro("PulseEvent", 2)
ServiceMacro("QueryAttributesFile", 2)
ServiceMacro("QueryBootEntryOrder", 2)
ServiceMacro("QueryBootOptions", 2)
ServiceMacro("QueryDebugFilterState", 2)
ServiceMacro("QueryDefaultLocale", 2)
ServiceMacro("QueryDefaultUILanguage", 1)
ServiceMacro("QueryDirectoryFile", 11)
ServiceMacro("QueryDirectoryObject", 7)
ServiceMacro("QueryDriverEntryOrder", 2)
ServiceMacro("QueryEaFile", 9)
ServiceMacro("QueryEvent", 5)
ServiceMacro("QueryFullAttributesFile", 2)
ServiceMacro("QueryInformationAtom", 5)
ServiceMacro("QueryInformationFile", 5)
ServiceMacro("QueryInformationJobObject", 5)
ServiceMacro("QueryInformationPort", 5)
ServiceMacro("QueryInformationProcess", 5)
ServiceMacro("QueryInformationThread", 5)
ServiceMacro("QueryInformationToken", 5)
ServiceMacro("QueryInstallUILanguage", 1)
ServiceMacro("QueryIntervalProfile", 2)
ServiceMacro("QueryIoCompletion", 5)
ServiceMacro("QueryKey", 5)
ServiceMacro("QueryMultipleValueKey", 6)
ServiceMacro("QueryMutant", 5)
ServiceMacro("QueryObject", 5)
ServiceMacro("QueryOpenSubKeys", 2)
ServiceMacro("QueryOpenSubKeysEx", 4)
ServiceMacro("QueryPerformanceCounter", 2)
ServiceMacro("QueryQuotaInformationFile", 9)
ServiceMacro("QuerySection", 5)
ServiceMacro("QuerySecurityObject", 5)
ServiceMacro("QuerySemaphore", 5)
ServiceMacro("QuerySymbolicLinkObject", 3)
ServiceMacro("QuerySystemEnvironmentValue", 4)
ServiceMacro("QuerySystemEnvironmentValueEx", 5)
ServiceMacro("QuerySystemInformation", 4)
ServiceMacro("QuerySystemTime", 1)
ServiceMacro("QueryTimer", 5)
ServiceMacro("QueryTimerResolution", 3)
ServiceMacro("QueryValueKey", 6)
ServiceMacro("QueryVirtualMemory", 6)
ServiceMacro("QueryVolumeInformationFile", 5)
ServiceMacro("QueueApcThread", 5)
ServiceMacro("RaiseException", 3)
ServiceMacro("RaiseHardError", 6)
ServiceMacro("ReadFile", 9)
ServiceMacro("ReadFileScatter", 9)
ServiceMacro("ReadRequestData", 6)
ServiceMacro("ReadVirtualMemory", 5)
ServiceMacro("RegisterThreadTerminatePort", 1)
ServiceMacro("ReleaseMutant", 2)
ServiceMacro("ReleaseSemaphore", 3)
ServiceMacro("RemoveIoCompletion", 5)
ServiceMacro("RemoveProcessDebug", 2)
ServiceMacro("RenameKey", 2)
ServiceMacro("ReplaceKey", 3)
ServiceMacro("ReplyPort", 2)
ServiceMacro("ReplyWaitReceivePort", 4)
ServiceMacro("ReplyWaitReceivePortEx", 5)
ServiceMacro("ReplyWaitReplyPort", 2)
ServiceMacro("RequestDeviceWakeup", 1)
ServiceMacro("RequestPort", 2)
ServiceMacro("RequestWaitReplyPort", 3)
ServiceMacro("RequestWakeupLatency", 1)
ServiceMacro("ResetEvent", 2)
ServiceMacro("ResetWriteWatch", 3)
ServiceMacro("RestoreKey", 3)
ServiceMacro("ResumeProcess", 1)
ServiceMacro("ResumeThread", 2)
ServiceMacro("SaveKey", 2)
ServiceMacro("SaveKeyEx", 3)
ServiceMacro("SaveMergedKeys", 3)
ServiceMacro("SecureConnectPort", 9)
ServiceMacro("SetBootEntryOrder", 2)
ServiceMacro("SetBootOptions", 2)
ServiceMacro("SetContextThread", 2)
ServiceMacro("SetDebugFilterState", 3)
ServiceMacro("SetDefaultHardErrorPort", 1)
ServiceMacro("SetDefaultLocale", 2)
ServiceMacro("SetDefaultUILanguage", 1)
ServiceMacro("SetDriverEntryOrder", 2)
ServiceMacro("SetEaFile", 4)
ServiceMacro("SetEvent", 2)
ServiceMacro("SetEventBoostPriority", 1)
ServiceMacro("SetHighEventPair", 1)
ServiceMacro("SetHighWaitLowEventPair", 1)
ServiceMacro("SetInformationDebugObject", 5)
ServiceMacro("SetInformationFile", 5)
ServiceMacro("SetInformationJobObject", 4)
ServiceMacro("SetInformationKey", 4)
ServiceMacro("SetInformationObject", 4)
ServiceMacro("SetInformationProcess", 4)
ServiceMacro("SetInformationThread", 4)
ServiceMacro("SetInformationToken", 4)
ServiceMacro("SetIntervalProfile", 2)
ServiceMacro("SetIoCompletion", 5)
ServiceMacro("SetLdtEntries", 6)
ServiceMacro("SetLowEventPair", 1)
ServiceMacro("SetLowWaitHighEventPair", 1)
ServiceMacro("SetQuotaInformationFile", 4)
ServiceMacro("SetSecurityObject", 3)
ServiceMacro("SetSystemEnvironmentValue", 2)
ServiceMacro("SetSystemEnvironmentValueEx", 5)
ServiceMacro("SetSystemInformation", 3)
ServiceMacro("SetSystemPowerState", 3)
ServiceMacro("SetSystemTime", 2)
ServiceMacro("SetThreadExecutionState", 2)
ServiceMacro("SetTimer", 7)
ServiceMacro("SetTimerResolution", 3)
ServiceMacro("SetUuidSeed", 1)
ServiceMacro("SetValueKey", 6)
ServiceMacro("SetVolumeInformationFile", 5)
ServiceMacro("ShutdownSystem", 1)
ServiceMacro("SignalAndWaitForSingleObject", 4)
ServiceMacro("StartProfile", 1)
ServiceMacro("StopProfile", 1)
ServiceMacro("SuspendProcess", 1)
ServiceMacro("SuspendThread", 2)
ServiceMacro("SystemDebugControl", 6)
ServiceMacro("TerminateJobObject", 2)
ServiceMacro("TerminateProcess", 2)
ServiceMacro("TerminateThread", 2)
ServiceMacro("TestAlert", 0)
ServiceMacro("TraceEvent", 4)
ServiceMacro("TranslateFilePath", 4)
ServiceMacro("UnloadDriver", 1)
ServiceMacro("UnloadKey", 1)
ServiceMacro("UnloadKey2", 2)
ServiceMacro("UnloadKeyEx", 2)
ServiceMacro("UnlockFile", 5)
ServiceMacro("UnlockVirtualMemory", 4)
ServiceMacro("UnmapViewOfSection", 2)
ServiceMacro("VdmControl", 2)
ServiceMacro("WaitForDebugEvent", 4)
ServiceMacro("WaitForMultipleObjects", 5)
ServiceMacro("WaitForSingleObject", 3)
ServiceMacro("WaitHighEventPair", 1)
ServiceMacro("WaitLowEventPair", 1)
ServiceMacro("WriteFile", 9)
ServiceMacro("WriteFileGather", 9)
ServiceMacro("WriteRequestData", 6)
ServiceMacro("WriteVirtualMemory", 5)
ServiceMacro("YieldExecution", 0)
ServiceMacro("CreateKeyedEvent", 4)
ServiceMacro("OpenKeyedEvent", 3)
ServiceMacro("ReleaseKeyedEvent", 4)
ServiceMacro("WaitForKeyedEvent", 4)
ServiceMacro("QueryPortInformationProcess", 0)
ServiceMacro("GetCurrentProcessorNumber", 0)
ServiceMacro("WaitForMultipleObjects32", 5)
| 40.405941 | 72 | 0.727844 |
23c1659097a1b67042a5b68d5d26296fd6304b60 | 6,032 | c | C | hv6/user/fs/fs.c | ekiwi/hyperkernel | d66adb5684ed82b7ed783315835b2f96de87793e | [
"Apache-2.0"
] | 132 | 2017-11-30T19:42:45.000Z | 2019-09-10T10:25:55.000Z | hv6/user/fs/fs.c | ekiwi/hyperkernel | d66adb5684ed82b7ed783315835b2f96de87793e | [
"Apache-2.0"
] | 8 | 2017-11-30T20:05:19.000Z | 2019-05-02T01:33:17.000Z | hv6/user/fs/fs.c | ekiwi/hyperkernel | d66adb5684ed82b7ed783315835b2f96de87793e | [
"Apache-2.0"
] | 19 | 2017-12-03T08:52:58.000Z | 2019-08-04T13:37:15.000Z | #include <uapi/machine/io.h>
#include <uapi/console.h>
#include "fs.h"
typedef int (*handler_t)(pid_t);
static int do_open(pid_t);
static int do_pread(pid_t);
static int do_mknod(pid_t);
static int do_fstat(pid_t);
static int do_pwrite(pid_t);
static int do_mkdir(pid_t);
static int do_unlink(pid_t);
static int do_pipe(pid_t);
static int do_membuf(pid_t);
static handler_t handlers[] = {
[FSIPC_OPEN] = do_open, [FSIPC_PREAD] = do_pread, [FSIPC_MKNOD] = do_mknod,
[FSIPC_MKDIR] = do_mkdir, [FSIPC_FSTAT] = do_fstat, [FSIPC_PWRITE] = do_pwrite,
[FSIPC_UNLINK] = do_unlink, [FSIPC_PIPE] = do_pipe, [FSIPC_MEMBUF] = do_membuf,
};
struct devsw devsw[NDEV];
extern char _binary_fs_img_start[], _binary_fs_img_end[];
static uint8_t ping_buf[PAGE_SIZE] __aligned(PAGE_SIZE);
static uint8_t pong_buf[PAGE_SIZE] __aligned(PAGE_SIZE);
static struct fsipc_ping *ping = (void *)ping_buf;
static struct fsipc_pong *pong = (void *)pong_buf;
static void consoleinit(void);
static void gc(void);
static struct file *fd_lookup(pid_t pid, int fd);
noreturn void fs_main(void)
{
struct superblock sb;
int r;
set_proc_name("fs");
unix_init();
consoleinit();
binit();
initlog();
readsb(ROOTDEV, &sb);
cprintf("fs: size %d nblocks %d ninodes %d nlog %d\n", sb.size, sb.nblocks, sb.ninodes,
sb.nlog);
r = sys_recv(INITPID, virt_to_pn(ping), -1);
while (1) {
if (r == 0) {
size_t op = ucurrent->ipc_val;
if (op < countof(handlers)) {
handler_t handler;
handler = handlers[op];
if (handler) {
gc();
r = handler(ucurrent->ipc_from);
continue;
}
}
}
r = sys_recv(INITPID, virt_to_pn(ping), -1);
}
exit();
}
static int do_open(pid_t pid)
{
struct file *cwd;
int fd, r;
cwd = fd_lookup(ucurrent->ipc_from, ping->open.dirfd);
fd = fileopen(cwd, ping->open.path, ping->open.omode);
r = (fd < 0) ? fd : 0;
return sys_reply_wait(pid, r, virt_to_pn(pong), 0, fd, virt_to_pn(ping));
}
static int do_pread(pid_t pid)
{
struct file *f;
size_t count;
ssize_t r;
f = fd_lookup(ucurrent->ipc_from, ping->pread.fd);
count = min(ping->pread.count, PAGE_SIZE);
r = filepread(f, (void *)pong, count, ping->pread.offset);
return sys_reply_wait(pid, r, virt_to_pn(pong), (r > 0) ? r : 0, -1, virt_to_pn(ping));
}
static int do_mknod(pid_t pid)
{
struct file *cwd;
int r;
cwd = fd_lookup(ucurrent->ipc_from, ping->mknod.dirfd);
r = filemknod(cwd, ping->mknod.path, ping->mknod.major, ping->mknod.minor);
return sys_reply_wait(pid, r, virt_to_pn(pong), 0, -1, virt_to_pn(ping));
}
static int do_mkdir(pid_t pid)
{
struct file *cwd;
int r;
cwd = fd_lookup(ucurrent->ipc_from, ping->mkdir.dirfd);
r = filemkdir(cwd, ping->mkdir.path);
return sys_reply_wait(pid, r, virt_to_pn(pong), 0, -1, virt_to_pn(ping));
}
static int do_fstat(pid_t pid)
{
struct file *f;
ssize_t r;
f = fd_lookup(ucurrent->ipc_from, ping->fstat.fd);
r = filestat(f, (struct stat *)pong);
return sys_reply_wait(pid, r, virt_to_pn(pong), (r == 0) ? sizeof(struct stat) : 0, -1,
virt_to_pn(ping));
}
static int do_pwrite(pid_t pid)
{
struct file *f;
size_t count;
ssize_t r;
f = fd_lookup(ucurrent->ipc_from, ping->pread.fd);
count = min(ping->pwrite.count, sizeof(ping->pwrite.buf));
r = filepwrite(f, ping->pwrite.buf, count, ping->pread.offset);
return sys_reply_wait(pid, r, virt_to_pn(pong), 0, -1, virt_to_pn(ping));
}
static int do_unlink(pid_t pid)
{
struct file *cwd;
int r;
cwd = fd_lookup(ucurrent->ipc_from, ping->unlink.dirfd);
r = fileunlink(cwd, ping->unlink.path);
return sys_reply_wait(pid, r, virt_to_pn(pong), 0, -1, virt_to_pn(ping));
}
static int do_pipe(pid_t pid)
{
int fds[2], r;
r = pipealloc(fds);
assert(r == 0, "pipealloc");
/* send two file descriptors */
r = sys_send(pid, r, virt_to_pn(pong), 0, fds[0]);
assert(r == 0, "sys_send");
while (uprocs[pid].state != PROC_SLEEPING)
yield();
return sys_reply_wait(pid, r, virt_to_pn(pong), 0, fds[1], virt_to_pn(ping));
}
static int do_membuf(pid_t pid)
{
int r;
r = membuf_get(pong);
return sys_reply_wait(pid, r, virt_to_pn(pong), 80 * 25, -1, virt_to_pn(ping));
}
static struct file *fd_lookup(pid_t pid, int fd)
{
fn_t fn;
if (!is_fd_valid(fd))
return 0;
fn = uprocs[pid].ofile[fd];
if (!is_fn_valid(fn))
return 0;
/* TODO: check own ofile for fd */
return &ufiles[fn];
}
int unix_time(void)
{
return 0;
}
static int consoleread(struct inode *ip, char *buf, size_t count, size_t offset)
{
int r;
r = console_getc();
if (r == 0)
return -EAGAIN;
buf[0] = r;
return 1;
}
static int enable_cga = ENABLED(CONFIG_CGA);
static int consolewrite(struct inode *ip, char *buf, size_t count)
{
if (enable_cga)
debug_print_screen(buf, count);
console_write(buf, count);
return count;
}
static void consoleinit(void)
{
/* enable I/O ports */
alloc_ports(PORT_COM1, 6);
alloc_port(PORT_KBD_DATA);
alloc_port(PORT_KBD_STATUS);
alloc_ports(PORT_CRT, 2);
/* initialize user console */
uart8250_init();
kbd_init();
membuf_init();
devsw[DEV_CONSOLE].write = consolewrite;
devsw[DEV_CONSOLE].read = consoleread;
if (is_kvm())
enable_cga = 0;
}
/* reclaim fds */
static void gc(void)
{
int fd;
fn_t fn;
struct file *f;
for (fd = 0; fd < NOFILE; ++fd) {
fn = ucurrent->ofile[fd];
if (!is_fn_valid(fn))
continue;
f = &ufiles[fn];
if (f->refcnt != 1)
continue;
if (f->type == FD_PIPE)
pipeclose(file_pipe(f), file_writable(f));
close(fd);
}
}
| 24.128 | 91 | 0.613395 |
c12d66c5bc730808a97b1025deb8aa31331615d0 | 72 | h | C | platforms/ios/plus/Pods/Headers/Public/WeexSDK/WXMultiColumnLayout.h | qq476743842/weex-saoa | 27d2347e865cf35e7c9bfb6180ba7b5106875296 | [
"MIT"
] | 13 | 2018-04-14T09:38:13.000Z | 2021-09-03T17:07:04.000Z | platforms/ios/plus/Pods/Headers/Public/WeexSDK/WXMultiColumnLayout.h | qq476743842/weex-oa | 27d2347e865cf35e7c9bfb6180ba7b5106875296 | [
"MIT"
] | 1 | 2019-09-05T02:17:42.000Z | 2019-09-05T02:17:42.000Z | platforms/ios/plus/Pods/Headers/Public/WeexSDK/WXMultiColumnLayout.h | qq476743842/weex-oa | 27d2347e865cf35e7c9bfb6180ba7b5106875296 | [
"MIT"
] | 5 | 2019-08-13T08:36:46.000Z | 2021-09-03T05:20:21.000Z | ../../../../sdk/WeexSDK/Sources/Component/Recycler/WXMultiColumnLayout.h | 72 | 72 | 0.75 |
c15849bcbd6e7bbbc88c32248ee4072fb197194d | 766 | c | C | Chapter-1/1-19.c | agrawal-shivani/The-C-Programming-Language | d0a08036df04ca1dcb1c3b33b1776803a0036102 | [
"MIT"
] | 5 | 2020-08-02T08:43:56.000Z | 2021-04-02T19:41:45.000Z | Chapter-1/1-19.c | Vipul97/The-C-Programming-Language | eec0fa5c09582cd72af2081e87e1612ec17900dc | [
"MIT"
] | null | null | null | Chapter-1/1-19.c | Vipul97/The-C-Programming-Language | eec0fa5c09582cd72af2081e87e1612ec17900dc | [
"MIT"
] | 1 | 2020-10-01T11:54:24.000Z | 2020-10-01T11:54:24.000Z | #include <stdio.h>
#define MAXLINE 1000
int getline(char line[], int maxline);
void reverse(char s[]);
main()
{
int len;
char line[MAXLINE];
while ((len = getline(line, MAXLINE)) > 0) {
reverse(line);
printf("%s", line);
}
return 0;
}
int getline(char s[], int lim)
{
int c, i;
for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
void reverse(char s[])
{
int i, j, c;
for (j = 0; s[j] != '\n'; ++j)
;
if (j > 1)
for (i = 0; i < j; ++i, --j) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
| 16.297872 | 63 | 0.365535 |
cab56b3d7f37b092616d226faee79fc81ed19d62 | 3,110 | h | C | src/common/mutex.h | qingnia/Pebbble | 8f8ea5f24565f3e6c5e488597131eba9bdbf7d31 | [
"BSD-2-Clause"
] | 841 | 2016-11-11T21:44:15.000Z | 2022-03-13T09:00:56.000Z | src/common/mutex.h | qingnia/Pebbble | 8f8ea5f24565f3e6c5e488597131eba9bdbf7d31 | [
"BSD-2-Clause"
] | 21 | 2016-11-17T04:24:06.000Z | 2019-04-11T09:36:52.000Z | src/common/mutex.h | qingnia/Pebbble | 8f8ea5f24565f3e6c5e488597131eba9bdbf7d31 | [
"BSD-2-Clause"
] | 343 | 2016-11-11T11:06:19.000Z | 2022-03-21T09:07:45.000Z | /*
* Tencent is pleased to support the open source community by making Pebble available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 _PEBBLE_COMMON_MUTEX_H_
#define _PEBBLE_COMMON_MUTEX_H_
#include <pthread.h>
namespace pebble {
class Mutex
{
public:
Mutex()
{
pthread_mutex_init(&m_mutex, NULL);
}
~Mutex()
{
pthread_mutex_destroy(&m_mutex);
}
void Lock()
{
pthread_mutex_lock(&m_mutex);
}
void UnLock()
{
pthread_mutex_unlock(&m_mutex);
}
pthread_mutex_t* GetMutex() {
return &m_mutex;
}
private:
pthread_mutex_t m_mutex;
};
class AutoLocker
{
public:
explicit AutoLocker(Mutex* mutex)
{
m_mutex = mutex;
m_mutex->Lock();
}
~AutoLocker()
{
m_mutex->UnLock();
}
private:
Mutex* m_mutex;
};
class ReadWriteLock
{
public:
ReadWriteLock()
{
pthread_rwlock_init(&m_lock, NULL);
}
~ReadWriteLock()
{
pthread_rwlock_destroy(&m_lock);
}
void ReadLock()
{
pthread_rwlock_rdlock(&m_lock);
}
void WriteLock()
{
pthread_rwlock_wrlock(&m_lock);
}
void UnLock()
{
pthread_rwlock_unlock(&m_lock);
}
private:
pthread_rwlock_t m_lock;
};
class ReadAutoLocker
{
public:
explicit ReadAutoLocker(ReadWriteLock* lock)
{
m_lock = lock;
m_lock->ReadLock();
}
~ReadAutoLocker()
{
m_lock->UnLock();
}
private:
ReadWriteLock* m_lock;
};
class WriteAutoLocker
{
public:
explicit WriteAutoLocker(ReadWriteLock* lock)
{
m_lock = lock;
m_lock->WriteLock();
}
~WriteAutoLocker()
{
m_lock->UnLock();
}
private:
ReadWriteLock* m_lock;
};
class SpinLock
{
public:
SpinLock()
{
pthread_spin_init(&_lock, 0);
}
~SpinLock()
{
pthread_spin_destroy(&_lock);
}
void Lock()
{
pthread_spin_lock(&_lock);
}
void Unlock()
{
pthread_spin_unlock(&_lock);
}
private:
pthread_spinlock_t _lock;
};
class AutoSpinLock
{
public:
explicit AutoSpinLock(SpinLock* spin_lock)
: _spin_lock(spin_lock)
{
if (NULL != _spin_lock)
{
_spin_lock->Lock();
}
}
~AutoSpinLock()
{
if (NULL != _spin_lock)
{
_spin_lock->Unlock();
}
}
private:
SpinLock* _spin_lock;
};
} // namespace pebble
#endif // _PEBBLE_COMMON_MUTEX_H_ | 16.72043 | 100 | 0.605145 |
1b1930ef9d8ee514ab7a18c42f62d315e480c195 | 6,823 | c | C | lib/libkvm/kvm_sparc.c | cooljeanius/DragonFlyBSD | 4c4e823ecc4019d4536be9493e38fef118f9a8cf | [
"BSD-3-Clause"
] | 2 | 2020-06-26T21:37:45.000Z | 2020-09-30T17:08:12.000Z | lib/libkvm/kvm_sparc.c | cooljeanius/DragonFlyBSD | 4c4e823ecc4019d4536be9493e38fef118f9a8cf | [
"BSD-3-Clause"
] | null | null | null | lib/libkvm/kvm_sparc.c | cooljeanius/DragonFlyBSD | 4c4e823ecc4019d4536be9493e38fef118f9a8cf | [
"BSD-3-Clause"
] | null | null | null | /*-
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software developed by the Computer Systems
* Engineering group at Lawrence Berkeley Laboratory under DARPA contract
* BG 91-66 and contributed to Berkeley.
*
* 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
*
* @(#)kvm_sparc.c 8.1 (Berkeley) 6/4/93
* $FreeBSD: src/lib/libkvm/kvm_sparc.c,v 1.3 1999/12/27 07:14:58 peter Exp $
*/
/*
* Sparc machine dependent routines for kvm. Hopefully, the forthcoming
* vm code will one day obsolete this module.
*/
#include <sys/user.h> /* MUST BE FIRST */
#include <sys/param.h>
#include <sys/proc.h>
#include <sys/stat.h>
#include <unistd.h>
#include <nlist.h>
#include <kvm.h>
#include <vm/vm.h>
#include <vm/vm_param.h>
#include <limits.h>
#include "kvm_private.h"
#define NPMEG 128
/* XXX from sparc/pmap.c */
#define MAXMEM (128 * 1024 * 1024) /* no more than 128 MB phys mem */
#define NPGBANK 16 /* 2^4 pages per bank (64K / bank) */
#define BSHIFT 4 /* log2(NPGBANK) */
#define BOFFSET (NPGBANK - 1)
#define BTSIZE (MAXMEM / NBPG / NPGBANK)
#define HWTOSW(pmap_stod, pg) (pmap_stod[(pg) >> BSHIFT] | ((pg) & BOFFSET))
struct vmstate {
pmeg_t segmap[NKSEG];
int pmeg[NPMEG][NPTESG];
int pmap_stod[BTSIZE]; /* dense to sparse */
};
void
_kvm_freevtop(kvm_t *kd)
{
if (kd->vmst != 0)
free(kd->vmst);
}
int
_kvm_initvtop(kvm_t *kd)
{
int i;
int off;
struct vmstate *vm;
struct stat st;
struct nlist nlist[2];
vm = (struct vmstate *)_kvm_malloc(kd, sizeof(*vm));
if (vm == NULL)
return (-1);
kd->vmst = vm;
if (fstat(kd->pmfd, &st) < 0)
return (-1);
/*
* Read segment table.
*/
off = st.st_size - ctob(btoc(sizeof(vm->segmap)));
errno = 0;
if (lseek(kd->pmfd, (off_t)off, 0) == -1 && errno != 0 ||
read(kd->pmfd, (char *)vm->segmap, sizeof(vm->segmap)) < 0) {
_kvm_err(kd, kd->program, "cannot read segment map");
return (-1);
}
/*
* Read PMEGs.
*/
off = st.st_size - ctob(btoc(sizeof(vm->pmeg)) +
btoc(sizeof(vm->segmap)));
errno = 0;
if (lseek(kd->pmfd, (off_t)off, 0) == -1 && errno != 0 ||
read(kd->pmfd, (char *)vm->pmeg, sizeof(vm->pmeg)) < 0) {
_kvm_err(kd, kd->program, "cannot read PMEG table");
return (-1);
}
/*
* Make pmap_stod be an identity map so we can bootstrap it in.
* We assume it's in the first contiguous chunk of physical memory.
*/
for (i = 0; i < BTSIZE; ++i)
vm->pmap_stod[i] = i << 4;
/*
* It's okay to do this nlist separately from the one kvm_getprocs()
* does, since the only time we could gain anything by combining
* them is if we do a kvm_getprocs() on a dead kernel, which is
* not too common.
*/
nlist[0].n_name = "_pmap_stod";
nlist[1].n_name = 0;
if (kvm_nlist(kd, nlist) != 0) {
_kvm_err(kd, kd->program, "pmap_stod: no such symbol");
return (-1);
}
if (kvm_read(kd, (u_long)nlist[0].n_value,
(char *)vm->pmap_stod, sizeof(vm->pmap_stod))
!= sizeof(vm->pmap_stod)) {
_kvm_err(kd, kd->program, "cannot read pmap_stod");
return (-1);
}
return (0);
}
#define VA_OFF(va) (va & (NBPG - 1))
/*
* Translate a user virtual address to a physical address.
*/
int
_kvm_uvatop(kvm_t *kd, const struct proc *p, u_long va, u_long *pa)
{
int kva, pte;
int off, frame;
struct vmspace *vms = p->p_vmspace;
if ((u_long)vms < KERNBASE) {
_kvm_err(kd, kd->program, "_kvm_uvatop: corrupt proc");
return (0);
}
if (va >= KERNBASE)
return (0);
/*
* Get the PTE. This takes two steps. We read the
* base address of the table, then we index it.
* Note that the index pte table is indexed by
* virtual segment rather than physical segment.
*/
kva = (u_long)&vms->vm_pmap.pm_rpte[VA_VSEG(va)];
if (kvm_read(kd, kva, (char *)&kva, 4) != 4 || kva == 0)
goto invalid;
kva += sizeof(vms->vm_pmap.pm_rpte[0]) * VA_VPG(va);
if (kvm_read(kd, kva, (char *)&pte, 4) == 4 && (pte & PG_V)) {
off = VA_OFF(va);
/*
* /dev/mem adheres to the hardware model of physical memory
* (with holes in the address space), while crashdumps
* adhere to the contiguous software model.
*/
if (kvm_ishost(kd))
frame = pte & PG_PFNUM;
else
frame = HWTOSW(kd->vmst->pmap_stod, pte & PG_PFNUM);
*pa = (frame << PGSHIFT) | off;
return (NBPG - off);
}
invalid:
_kvm_err(kd, 0, "invalid address (%x)", va);
return (0);
}
/*
* Translate a kernel virtual address to a physical address using the
* mapping information in kd->vm. Returns the result in pa, and returns
* the number of bytes that are contiguously available from this
* physical address. This routine is used only for crashdumps.
*/
int
_kvm_kvatop(kvm_t *kd, u_long va, u_long *pa)
{
struct vmstate *vm;
int s;
int pte;
int off;
if (va >= KERNBASE) {
vm = kd->vmst;
s = vm->segmap[VA_VSEG(va) - NUSEG];
pte = vm->pmeg[s][VA_VPG(va)];
if ((pte & PG_V) != 0) {
off = VA_OFF(va);
*pa = (HWTOSW(vm->pmap_stod, pte & PG_PFNUM)
<< PGSHIFT) | off;
return (NBPG - off);
}
}
_kvm_err(kd, 0, "invalid address (%x)", va);
return (0);
}
| 30.190265 | 77 | 0.66481 |
1459b0a66214a369650a12a719932a5c4afe445b | 6,607 | c | C | countops.c | cxd4/rsplog | ec1076e0cccb2fa5ca7b6dc02ce99c2462adba7b | [
"CC0-1.0"
] | 2 | 2016-02-29T02:40:35.000Z | 2016-05-01T02:59:47.000Z | countops.c | cxd4/rsplog | ec1076e0cccb2fa5ca7b6dc02ce99c2462adba7b | [
"CC0-1.0"
] | null | null | null | countops.c | cxd4/rsplog | ec1076e0cccb2fa5ca7b6dc02ce99c2462adba7b | [
"CC0-1.0"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include "mnemonics.h"
#include "rcp.h"
typedef long int capacity; /* Signed types help diagnose overflow. */
capacity count_primary[077 + 1];
capacity count_SPECIAL[077 + 1];
capacity count_REGIMM [037 + 1];
capacity count_COP0 [037 + 1];
capacity count_COP2 [037 + 1];
capacity count_LWC2 [037 + 1];
capacity count_SWC2 [037 + 1];
capacity count_C2 [077 + 1];
u8 * DRAM;
extern void RSP_count(FILE * stream, size_t max_PC, u8 * IMEM);
extern long file_size(FILE * stream);
int main(int argc, char* argv[])
{
FILE * stream;
size_t bytes, elements_read;
long file_size_in_bytes;
if (argc < 2)
{
fputs("Command syntax missing domain.\n", stderr);
getchar();
return 1;
}
stream = fopen(argv[1], "rb");
if (stream == NULL)
{
fputs("Specified file was unreadable.\n", stderr);
return 1;
}
file_size_in_bytes = file_size(stream);
if (file_size_in_bytes < 0)
{
fputs("The file size is immeasurable.\n", stderr);
return 1;
}
bytes = (size_t)file_size_in_bytes;
printf("Attempting to import %li-byte file...\n", file_size_in_bytes);
rewind(stream);
DRAM = malloc(bytes * sizeof(u8));
if (DRAM == NULL)
{
fputs("Too much data to allocate RAM.\n", stderr);
return 1;
}
elements_read = fread(DRAM, sizeof(u8) * bytes, 1, stream);
while (fclose(stream) != 0)
;
if (elements_read != 1)
{
fputs("DRAM file data import failure.\n", stderr);
return 1;
}
stream = fopen("out.txt", "w");
if (stream == NULL)
{
fputs("File write permission failure.\n", stderr);
return 1;
}
RSP_count(stream, bytes, DRAM);
while (fclose(stream) != 0)
;
return 0;
}
void RSP_count(FILE * stream, size_t max_PC, u8 * IMEM)
{
register size_t PC;
register int i;
if (max_PC & 3)
fputs("Warning: Truncating unaligned cache size.\n", stderr);
#if 0
max_PC &= 0x03FFFFFCul;
#endif
max_PC &= ~0x00000003ul;
printf("Enumerating RSP operations...\n");
for (PC = 0x04001000 & 0x000; PC < max_PC; PC += 0x004)
{
const u32 inst = 0x00000000u
| (IMEM[PC + 0] << 24)
| (IMEM[PC + 1] << 16)
| (IMEM[PC + 2] << 8)
| (IMEM[PC + 3] << 0)
;
const unsigned int op = (inst >> 26) % 64;
const unsigned int rs = (inst >> 21) % 32;
const unsigned int rt = (inst >> 16) % 32;
const unsigned short immediate = (unsigned short)(inst & 0x0000FFFFul);
const unsigned int rd = (immediate >> 11) % 32;
const unsigned int func = (immediate >> 0) % 64;
++count_primary[op];
switch (op)
{ /* oooooo ----- ----- ----- ----- ------ */
case 000: /* SPECIAL */
++count_SPECIAL[func];
continue; /* 000000 ----- ----- ----- ----- ffffff */
case 001: /* REGIMM */
++count_REGIMM[rt];
continue; /* 000001 ----- ttttt ----- ----- ------ */
case 020: /* COP0 */
++count_COP0[rs];
continue; /* 010000 sssss ----- ----- ----- ------ */
case 022: /* COP2 */
++count_COP2[(rs >= 16) ? 16 : rs];
count_C2[inst % 64] += !!(inst & 0x02000000ul);
continue; /* 010010 Veeee ----- ----- ----- ffffff */
case 062: /* LWC2 */
++count_LWC2[rd];
continue;
case 072: /* SWC2 */
++count_SWC2[rd];
continue;
default:
continue;
}
}
printf("Checking through the results...");
fprintf(stream, "RSP Iterations Log: %s\n", "primary R4000 op-codes");
fputs("--------------------------------------------\n", stream);
for (i = 0; i < 64; i++)
if (count_primary[i] != 0)
fprintf(stream, "%s %i\n", mnemonics_primary[i], count_primary[i]);
fputc('\n', stream);
fprintf(stream, "RSP Iterations Log: %s\n", "SPECIAL operation codes");
fputs("--------------------------------------------\n", stream);
for (i = 0; i < 64; i++)
if (count_SPECIAL[i] != 0)
fprintf(stream, "%s %i\n", mnemonics_SPECIAL[i], count_SPECIAL[i]);
fputc('\n', stream);
fprintf(stream, "RSP Iterations Log: %s\n", "REGIMM operation codes");
fputs("--------------------------------------------\n", stream);
for (i = 0; i < 32; i++)
if (count_REGIMM[i] != 0)
fprintf(stream, "%s %i\n", mnemonics_REGIMM[i], count_REGIMM[i]);
fputc('\n', stream);
fprintf(stream, "RSP Iterations Log: %s\n", "COP0 operation codes");
fputs("--------------------------------------------\n", stream);
for (i = 0; i < 32; i++)
if (count_COP0[i] != 0)
fprintf(stream, "%s %i\n", mnemonics_COP0[i], count_COP0[i]);
fputc('\n', stream);
fprintf(stream, "RSP Iterations Log: %s\n", "COP2 operation codes");
fputs("--------------------------------------------\n", stream);
for (i = 0; i < 32; i++)
if (count_COP2[i] != 0)
fprintf(stream, "%s %i\n", mnemonics_COP2[i], count_COP2[i]);
fputc('\n', stream);
fprintf(stream, "RSP Iterations Log: %s\n", "LWC2 operation codes");
fputs("--------------------------------------------\n", stream);
for (i = 0; i < 32; i++)
if (count_LWC2[i] != 0)
fprintf(stream, "%s %i\n", mnemonics_LWC2[i], count_LWC2[i]);
fputc('\n', stream);
fprintf(stream, "RSP Iterations Log: %s\n", "SWC2 operation codes");
fputs("--------------------------------------------\n", stream);
for (i = 0; i < 32; i++)
if (count_SWC2[i] != 0)
fprintf(stream, "%s %i\n", mnemonics_SWC2[i], count_SWC2[i]);
fputc('\n', stream);
fprintf(stream, "RSP Iterations Log: %s\n", "vector operation codes");
fputs("--------------------------------------------\n", stream);
for (i = 0; i < 64; i++)
if (count_C2[i] != 0)
fprintf(stream, "%s %i\n", mnemonics_vector[i], count_C2[i]);
printf("Results written.\n");
return;
}
long file_size(FILE * stream)
{
int failure;
#ifdef POSIX_REGULATIONS_ASSUMED
failure = fseek(stream, SEEK_END, 0);
if (failure)
return -1L;
#else
failure = fseek(stream, SEEK_SET, 0);
if (failure)
return -1L;
while (fgetc(stream) >= 0)
;
#endif
return ftell(stream);
}
| 30.730233 | 79 | 0.497654 |
9f13be18ff2614f6ad7d7ac34583bca03fadf764 | 624 | h | C | ECAPI/DiscussionResponse.h | PearsonEducation/mobile2-ios-api | e2bcc3c72a76ee3ff146e39d61aaffb2a594b0fd | [
"Apache-2.0"
] | null | null | null | ECAPI/DiscussionResponse.h | PearsonEducation/mobile2-ios-api | e2bcc3c72a76ee3ff146e39d61aaffb2a594b0fd | [
"Apache-2.0"
] | null | null | null | ECAPI/DiscussionResponse.h | PearsonEducation/mobile2-ios-api | e2bcc3c72a76ee3ff146e39d61aaffb2a594b0fd | [
"Apache-2.0"
] | null | null | null | //
// DiscussionResponse.h
// ECAPI
//
// Created by Brad Umbaugh on 3/15/11.
// Copyright 2011 EffectiveUI. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "User.h"
@interface DiscussionResponse : NSObject {
NSNumber* discussionResponseId;
NSString* title;
NSString* description;
User* author;
NSDate* postedDate;
}
@property (nonatomic, retain) NSNumber* discussionResponseId;
@property (nonatomic, retain) NSString* title;
@property (nonatomic, retain) NSString* description;
@property (nonatomic, retain) User* author;
@property (nonatomic, retain) NSDate* postedDate;
@end
| 23.111111 | 61 | 0.729167 |
9f19c9f2b43cd4b9c515175cf695258a6a2762f0 | 44,075 | c | C | tcod_sys/libtcod/src/libtcod/console_printing.c | alexschrod/tcod-rs | 03a35b3977744069759a6e5c8521ebe471fe5f70 | [
"WTFPL"
] | null | null | null | tcod_sys/libtcod/src/libtcod/console_printing.c | alexschrod/tcod-rs | 03a35b3977744069759a6e5c8521ebe471fe5f70 | [
"WTFPL"
] | null | null | null | tcod_sys/libtcod/src/libtcod/console_printing.c | alexschrod/tcod-rs | 03a35b3977744069759a6e5c8521ebe471fe5f70 | [
"WTFPL"
] | null | null | null | /* BSD 3-Clause License
*
* Copyright © 2008-2020, Jice and the libtcod contributors.
* 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.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* 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 HOLDER 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.
*/
#include "console_printing.h"
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#ifndef NO_UNICODE
#include <wchar.h>
#include <wctype.h>
#endif
#include "console_drawing.h"
#include "console.h"
#include "libtcod_int.h"
#include "utility.h"
#include "../vendor/utf8proc/utf8proc.h"
static TCOD_color_t color_control_fore[TCOD_COLCTRL_NUMBER] = {
{255, 255, 255}, {255, 255, 255}, {255, 255, 255}, {255, 255, 255},
{255, 255, 255}};
static TCOD_color_t color_control_back[TCOD_COLCTRL_NUMBER];
/**
* Assign a foreground and background color to a color control index.
*
* \param con Index to change, e.g. `TCOD_COLCTRL_1`
* \param fore Foreground color to assign to this index.
* \param back Background color to assign to this index.
*/
void TCOD_console_set_color_control(
TCOD_colctrl_t con, TCOD_color_t fore, TCOD_color_t back)
{
TCOD_IFNOT(con >= TCOD_COLCTRL_1 && con <= TCOD_COLCTRL_NUMBER) return;
color_control_fore[con - 1] = fore;
color_control_back[con - 1] = back;
}
char *TCOD_console_vsprint(const char *fmt, va_list ap)
{
#define NB_BUFFERS 10
#define INITIAL_SIZE 512
/* several static buffers in case the function is used more than once in a single function call */
static char *msg[NB_BUFFERS] = {NULL};
static int buflen[NB_BUFFERS] = {0};
static int curbuf = 0;
char *ret;
bool ok = false;
if (!msg[0]) {
int i;
for (i = 0; i < NB_BUFFERS; i++) {
buflen[i] = INITIAL_SIZE;
msg[i] = calloc(sizeof(char), INITIAL_SIZE);
}
}
do {
/* warning ! depending on the compiler, vsnprintf return -1 or
the expected string length if the buffer is not big enough */
va_list ap_clone;
va_copy(ap_clone, ap);
int len = vsnprintf(msg[curbuf], buflen[curbuf], fmt, ap_clone);
va_end(ap_clone);
ok=true;
if (len < 0 || len >= buflen[curbuf]) {
/* buffer too small. */
if (len > 0) {
while (buflen[curbuf] < len + 1) { buflen[curbuf] *= 2; }
} else {
buflen[curbuf] *= 2;
}
free(msg[curbuf]);
msg[curbuf] = calloc(sizeof(char), buflen[curbuf]);
ok = false;
}
} while (!ok);
ret = msg[curbuf];
curbuf = (curbuf + 1) % NB_BUFFERS;
return ret;
}
/**
* Print a titled, framed region on a console, using default colors and
* alignment.
*
* \param con A console pointer.
* \param x The starting X coordinate, the left-most position being 0.
* \param y The starting Y coordinate, the top-most position being 0.
* \param w The width of the frame.
* \param h The height of the frame.
* \param empty If true the characters inside of the frame will be cleared
* with spaces.
* \param flag The blending flag.
* \param fmt A format string as if passed to printf.
* \param ... Variadic arguments as if passed to printf.
*
* This function makes assumptions about the fonts character encoding.
* It will fail if the font encoding is not `cp437`.
*/
void TCOD_console_print_frame(
TCOD_Console* con,int x, int y, int w, int h,
bool empty, TCOD_bkgnd_flag_t flag, const char* fmt, ...)
{
con = TCOD_console_validate_(con);
if (!con) { return; }
TCOD_console_put_char(con, x, y, TCOD_CHAR_NW, flag);
TCOD_console_put_char(con, x + w - 1, y, TCOD_CHAR_NE, flag);
TCOD_console_put_char(con, x, y + h - 1 , TCOD_CHAR_SW, flag);
TCOD_console_put_char(con, x + w - 1, y + h - 1, TCOD_CHAR_SE, flag);
TCOD_console_hline(con, x + 1, y, w - 2, flag);
TCOD_console_hline(con, x + 1, y + h - 1, w - 2, flag);
if (h > 2) {
TCOD_console_vline(con, x,y + 1, h - 2, flag);
TCOD_console_vline(con, x + w - 1, y + 1, h - 2, flag);
if (empty) {
TCOD_console_rect(con, x + 1, y + 1, w - 2, h - 2, true, flag);
}
}
if (fmt) {
va_list ap;
int xs;
char *title;
va_start(ap, fmt);
title = TCOD_console_vsprint(fmt, ap);
va_end(ap);
title[w - 3] = 0; /* truncate if needed */
xs = x + (w - (int)(strlen(title)) - 2) / 2;
TCOD_color_t tmp;
tmp = con->fore;
con->fore = con->back;
con->back = tmp;
TCOD_console_print_ex(con, xs, y, TCOD_BKGND_SET, TCOD_LEFT,
" %s ", title);
tmp = con->fore;
con->fore = con->back;
con->back = tmp;
}
}
/**
* Print a string on a console, using default colors and alignment.
*
* \param con A console pointer.
* \param x The starting X coordinate, the left-most position being 0.
* \param y The starting Y coordinate, the top-most position being 0.
* \param fmt A format string as if passed to printf.
* \param ... Variadic arguments as if passed to printf.
*/
void TCOD_console_print(TCOD_Console* con, int x, int y, const char* fmt, ...)
{
va_list ap;
con = TCOD_console_validate_(con);
if (!con) { return; }
va_start(ap, fmt);
TCOD_console_print_internal(con, x, y, 0, 0, con->bkgnd_flag,
con->alignment, TCOD_console_vsprint(fmt, ap), false, false);
va_end(ap);
}
/**
* Print a string on a console, using default colors.
*
* \param con A console pointer.
* \param x The starting X coordinate, the left-most position being 0.
* \param y The starting Y coordinate, the top-most position being 0.
* \param flag The blending flag.
* \param alignment The font alignment to use.
* \param fmt A format string as if passed to printf.
* \param ... Variadic arguments as if passed to printf.
*/
void TCOD_console_print_ex(TCOD_Console* con,int x, int y,
TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
TCOD_console_print_internal(con, x, y, 0, 0, flag, alignment,
TCOD_console_vsprint(fmt, ap), false, false);
va_end(ap);
}
/**
* Print a string on a console constrained to a rectangle, using default
* colors and alignment.
*
* \param con A console pointer.
* \param x The starting X coordinate, the left-most position being 0.
* \param y The starting Y coordinate, the top-most position being 0.
* \param w The width of the region.
* If 0 then the maximum width will be used.
* \param h The height of the region.
* If 0 then the maximum height will be used.
* \param fmt A format string as if passed to printf.
* \param ... Variadic arguments as if passed to printf.
* \return The number of lines actually printed.
*/
int TCOD_console_print_rect(TCOD_Console* con, int x, int y, int w, int h,
const char *fmt, ...)
{
int ret;
va_list ap;
con = TCOD_console_validate_(con);
if (!con) { return 0; }
va_start(ap, fmt);
ret = TCOD_console_print_internal(con, x, y, w, h, con->bkgnd_flag,
con->alignment, TCOD_console_vsprint(fmt, ap), true, false);
va_end(ap);
return ret;
}
/**
* Print a string on a console constrained to a rectangle, using default
* colors.
*
* \param con A console pointer.
* \param x The starting X coordinate, the left-most position being 0.
* \param y The starting Y coordinate, the top-most position being 0.
* \param w The width of the region.
* If 0 then the maximum width will be used.
* \param h The height of the region.
* If 0 then the maximum height will be used.
* \param flag The blending flag.
* \param alignment The font alignment to use.
* \param fmt A format string as if passed to printf.
* \param ... Variadic arguments as if passed to printf.
* \return The number of lines actually printed.
*/
int TCOD_console_print_rect_ex(TCOD_Console* con, int x, int y, int w, int h,
TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...)
{
int ret;
va_list ap;
va_start(ap, fmt);
ret = TCOD_console_print_internal(con, x, y, w, h, flag, alignment,
TCOD_console_vsprint(fmt, ap), true, false);
va_end(ap);
return ret;
}
/**
* Return the number of lines that would be printed by the
*
* \param con A console pointer.
* \param x The starting X coordinate, the left-most position being 0.
* \param y The starting Y coordinate, the top-most position being 0.
* \param w The width of the region.
* If 0 then the maximum width will be used.
* \param h The height of the region.
* If 0 then the maximum height will be used.
* \param fmt A format string as if passed to printf.
* \param ... Variadic arguments as if passed to printf.
* \return The number of lines that would have been printed.
*/
int TCOD_console_get_height_rect(TCOD_Console* con,
int x, int y, int w, int h, const char *fmt, ...)
{
int ret;
va_list ap;
va_start(ap, fmt);
ret = TCOD_console_print_internal(con, x, y, w, h, TCOD_BKGND_NONE,
TCOD_LEFT, TCOD_console_vsprint(fmt, ap), true, true);
va_end(ap);
return ret;
}
/* non public methods */
int TCOD_console_stringLength(const unsigned char *s)
{
int l = 0;
while (*s) {
if (*s == TCOD_COLCTRL_FORE_RGB || *s == TCOD_COLCTRL_BACK_RGB) {
s += 3;
} else if (*s > TCOD_COLCTRL_STOP) {
l++;
}
s++;
}
return l;
}
unsigned char * TCOD_console_forward(unsigned char *s,int l)
{
while (*s && l > 0) {
if (*s == TCOD_COLCTRL_FORE_RGB || *s == TCOD_COLCTRL_BACK_RGB) {
s += 3;
} else if (*s > TCOD_COLCTRL_STOP) {
l--;
}
s++;
}
return s;
}
unsigned char *TCOD_console_strchr(unsigned char *s, unsigned char c)
{
while (*s && *s != c) {
if (*s == TCOD_COLCTRL_FORE_RGB || *s == TCOD_COLCTRL_BACK_RGB) {
s += 3;
}
s++;
}
return (*s ? s : NULL);
}
int TCOD_console_print_internal(
TCOD_Console* con, int x,int y, int rw, int rh, TCOD_bkgnd_flag_t flag,
TCOD_alignment_t align, char *msg, bool can_split, bool count_only)
{
unsigned char *c = (unsigned char*)msg;
int cx = 0;
int cy = y;
int minx, maxx, miny, maxy;
TCOD_color_t oldFore;
TCOD_color_t oldBack;
con = TCOD_console_validate_(con);
if (!con) { return 0; }
TCOD_IFNOT(TCOD_console_is_index_valid_(con, x, y)) { return 0; }
TCOD_IFNOT(msg != NULL) { return 0; }
if (rh == 0) { rh = con->h - y; }
if (rw == 0) {
switch(align) {
case TCOD_LEFT: rw = con->w - x; break;
case TCOD_RIGHT: rw = x + 1; break;
case TCOD_CENTER: default: rw = con->w; break;
}
}
oldFore = con->fore;
oldBack = con->back;
miny = y;
maxy = con->h - 1;
if (rh > 0) { maxy = MIN(maxy, y + rh - 1); }
switch (align) {
case TCOD_LEFT:
minx = MAX(0,x);
maxx = MIN(con->w - 1, x + rw - 1);
break;
case TCOD_RIGHT:
minx = MAX(0, x - rw + 1);
maxx = MIN(con->w - 1, x);
break;
case TCOD_CENTER: default:
minx = MAX(0, x - rw / 2);
maxx = MIN(con->w - 1, x + rw / 2);
break;
}
do {
/* get \n delimited sub-message */
unsigned char *end = TCOD_console_strchr(c, '\n');
char bak = 0;
int cl;
unsigned char *split = NULL;
if (end) { *end=0; }
cl = TCOD_console_stringLength(c);
/* find starting x */
switch (align) {
case TCOD_LEFT : cx = x; break;
case TCOD_RIGHT : cx = x - cl + 1; break;
case TCOD_CENTER : cx = x - cl / 2; break;
}
/* check if the string is completely out of the minx,miny,maxx,maxy frame */
if (cy >= miny && cy <= maxy && cx <= maxx && cx + cl -1 >= minx) {
if (can_split && cy <= maxy) {
/* if partially out of screen, try to split the sub-message */
if (cx < minx) {
split = TCOD_console_forward(c, (align == TCOD_CENTER
? cl - 2 * (minx - cx)
: cl - (minx - cx)));
} else if (align == TCOD_CENTER) {
if (cx + cl / 2 > maxx + 1) {
split = TCOD_console_forward(c, maxx + 1 - cx);
}
} else {
if (cx + cl > maxx + 1) {
split = TCOD_console_forward(c, maxx + 1 - cx);
}
}
}
if (split) {
unsigned char *oldsplit = split;
while (!isspace(*split) && split > c) { split--; }
if (end) { *end = '\n'; }
if (!isspace(*split)) {
split = oldsplit;
}
end = split;
bak = *split;
*split = 0;
cl = TCOD_console_stringLength(c);
switch (align) {
case TCOD_LEFT : cx = x; break;
case TCOD_RIGHT : cx = x - cl + 1; break;
case TCOD_CENTER : cx = x - cl / 2; break;
}
}
if (cx < minx) {
/* truncate left part */
c += minx-cx;
cl -= minx-cx;
cx = minx;
}
if (cx + cl > maxx + 1) {
/* truncate right part */
split = TCOD_console_forward(c, maxx + 1 - cx);
*split = 0;
}
/* render the sub-message */
if (cy >= 0 && cy < con->h) {
while (*c) {
if (*c >= TCOD_COLCTRL_1 && *c <= TCOD_COLCTRL_NUMBER) {
con->fore = color_control_fore[*c - 1];
con->back = color_control_back[*c - 1];
} else if (*c == TCOD_COLCTRL_FORE_RGB) {
c++;
con->fore.r = *c++;
con->fore.g = *c++;
con->fore.b = *c;
} else if (*c == TCOD_COLCTRL_BACK_RGB) {
c++;
con->back.r = *c++;
con->back.g = *c++;
con->back.b = *c;
} else if (*c == TCOD_COLCTRL_STOP) {
con->fore = oldFore;
con->back = oldBack;
} else {
if (!count_only) {
TCOD_console_put_char(con, cx, cy, *c, flag);
}
cx++;
}
c++;
}
}
}
if (end) {
/* next line */
if (split && ! isspace(bak)) {
*end = bak;
c = end;
} else {
c = end + 1;
}
cy++;
} else {
c = NULL;
}
} while (c && cy < con->h && (rh == 0 || cy < y + rh));
return cy - y + 1;
}
#ifndef NO_UNICODE
wchar_t *TCOD_console_strchr_utf(wchar_t *s, char c)
{
while (*s && *s != c) {
if (*s == TCOD_COLCTRL_FORE_RGB || *s == TCOD_COLCTRL_BACK_RGB) {
s += 3;
}
s++;
}
return (*s ? s : NULL);
}
wchar_t *TCOD_console_vsprint_utf(const wchar_t *fmt, va_list ap)
{
#define NB_BUFFERS 10
#define INITIAL_SIZE 512
/* several static buffers in case the function is used more than once in a single function call */
static wchar_t *msg[NB_BUFFERS] = {NULL};
static int buflen[NB_BUFFERS] = {0};
static int curbuf = 0;
wchar_t *ret;
bool ok = false;
if (!msg[0]) {
int i;
for (i = 0; i < NB_BUFFERS; i++) {
buflen[i] = INITIAL_SIZE;
msg[i] = calloc(sizeof(wchar_t), INITIAL_SIZE);
}
}
do {
/* warning ! depending on the compiler, vsnprintf return -1 or
the expected string length if the buffer is not big enough */
int len = vswprintf(msg[curbuf], buflen[curbuf], fmt, ap);
ok = true;
if (len < 0 || len >= buflen[curbuf]) {
/* buffer too small. */
if (len > 0) {
while (buflen[curbuf] < len + 1) { buflen[curbuf] *= 2; }
} else {
buflen[curbuf] *= 2;
}
free(msg[curbuf]);
msg[curbuf] = calloc(sizeof(wchar_t), buflen[curbuf]);
ok = false;
}
} while (!ok);
ret = msg[curbuf];
curbuf = (curbuf + 1) % NB_BUFFERS;
return ret;
}
int TCOD_console_stringLength_utf(const wchar_t *s)
{
int l = 0;
while (*s) {
if (*s == TCOD_COLCTRL_FORE_RGB || *s == TCOD_COLCTRL_BACK_RGB) {
s += 3;
} else if (*s > TCOD_COLCTRL_STOP) {
l++;
}
s++;
}
return l;
}
wchar_t * TCOD_console_forward_utf(wchar_t *s,int l)
{
while (*s && l > 0) {
if (*s == TCOD_COLCTRL_FORE_RGB || *s == TCOD_COLCTRL_BACK_RGB) {
s+=3;
} else if (*s > TCOD_COLCTRL_STOP) {
l--;
}
s++;
}
return s;
}
int TCOD_console_print_internal_utf(
TCOD_Console* con,int x,int y, int rw, int rh, TCOD_bkgnd_flag_t flag,
TCOD_alignment_t align, wchar_t *msg, bool can_split, bool count_only)
{
wchar_t *c = msg;
int cx = 0;
int cy = y;
int minx, maxx, miny, maxy;
TCOD_color_t oldFore;
TCOD_color_t oldBack;
con = TCOD_console_validate_(con);
if (!con) { return 0; }
if (!TCOD_console_is_index_valid_(con, x, y)) { return 0; }
TCOD_IFNOT(msg != NULL) { return 0; }
if (rh == 0) { rh = con->h - y; }
if (rw == 0) {
switch(align) {
case TCOD_LEFT: rw = con->w - x; break;
case TCOD_RIGHT: rw = x + 1; break;
case TCOD_CENTER: default: rw = con->w; break;
}
}
oldFore = con->fore;
oldBack = con->back;
miny = y;
maxy = con->h - 1;
if (rh > 0) maxy = MIN(maxy, y + rh - 1);
switch (align) {
case TCOD_LEFT:
minx = MAX(0,x);
maxx = MIN(con->w-1,x+rw-1);
break;
case TCOD_RIGHT:
minx = MAX(0, x - rw + 1);
maxx = MIN(con->w - 1, x);
break;
case TCOD_CENTER: default:
minx = MAX(0, x - rw / 2);
maxx = MIN(con->w - 1, x + rw / 2);
break;
}
do {
/* get \n delimited sub-message */
wchar_t *end = TCOD_console_strchr_utf(c, '\n');
wchar_t bak = 0;
int cl;
wchar_t *split = NULL;
if (end) { *end = 0; }
cl = TCOD_console_stringLength_utf(c);
/* find starting x */
switch (align) {
case TCOD_LEFT: cx = x; break;
case TCOD_RIGHT: cx = x - cl + 1; break;
case TCOD_CENTER: cx = x - cl / 2; break;
}
/* check if the string is completely out of the minx,miny,maxx,maxy frame */
if (cy >= miny && cy <= maxy && cx <= maxx && cx + cl - 1 >= minx) {
if (can_split && cy < maxy) {
/* if partially out of screen, try to split the sub-message */
if (cx < minx) {
split = TCOD_console_forward_utf(c, (align == TCOD_CENTER
? cl - 2 * (minx - cx)
: cl - (minx - cx)));
} else if (align == TCOD_CENTER) {
if (cx + cl / 2 > maxx + 1) {
split = TCOD_console_forward_utf(c, maxx + 1 - cx);
}
} else {
if (cx + cl > maxx + 1) {
split = TCOD_console_forward_utf(c, maxx + 1 - cx);
}
}
}
if (split) {
wchar_t *oldsplit = split;
while (!iswspace(*split) && split > c) { split--; }
if (end) { *end='\n'; }
if (!iswspace(*split)) {
split = oldsplit;
}
end = split;
bak = *split;
*split = 0;
cl = TCOD_console_stringLength_utf(c);
switch (align) {
case TCOD_LEFT: cx = x; break;
case TCOD_RIGHT: cx = x - cl + 1; break;
case TCOD_CENTER: cx = x - cl / 2; break;
}
}
if (cx < minx) {
/* truncate left part */
c += minx - cx;
cl -= minx - cx;
cx = minx;
}
if (cx + cl > maxx + 1) {
/* truncate right part */
split = TCOD_console_forward_utf(c, maxx + 1 - cx);
*split = 0;
}
/* render the sub-message */
if (cy >= 0 && cy < con->h)
while (*c) {
if (*c >= TCOD_COLCTRL_1 && *c <= TCOD_COLCTRL_NUMBER) {
con->fore = color_control_fore[(int)(*c) - 1];
con->back = color_control_back[(int)(*c) - 1];
} else if (*c == TCOD_COLCTRL_FORE_RGB) {
c++;
con->fore.r = (uint8_t)(*c++);
con->fore.g = (uint8_t)(*c++);
con->fore.b = (uint8_t)(*c);
} else if (*c == TCOD_COLCTRL_BACK_RGB) {
c++;
con->back.r = (uint8_t)(*c++);
con->back.g = (uint8_t)(*c++);
con->back.b = (uint8_t)(*c);
} else if (*c == TCOD_COLCTRL_STOP) {
con->fore = oldFore;
con->back = oldBack;
} else {
if (!count_only) {
TCOD_console_put_char(con, cx, cy, (int)*c, flag);
}
cx++;
}
c++;
}
}
if (end) {
/* next line */
if (split && !iswspace(bak)) {
*end = bak;
c = end;
} else {
c = end + 1;
}
cy++;
} else {
c = NULL;
}
} while (c && cy < con->h && (rh == 0 || cy < y + rh));
return cy - y + 1;
}
/**
* \rst
* .. deprecated:: 1.8
* Use :any:`TCOD_console_printf` instead.
* \endrst
*/
void TCOD_console_print_utf(TCOD_Console* con, int x, int y,
const wchar_t *fmt, ...)
{
va_list ap;
con = TCOD_console_validate_(con);
if (!con) { return; }
va_start(ap, fmt);
TCOD_console_print_internal_utf(con, x, y, 0, 0, con->bkgnd_flag,
con->alignment, TCOD_console_vsprint_utf(fmt, ap), false, false);
va_end(ap);
}
/**
* \rst
* .. deprecated:: 1.8
* Use :any:`TCOD_console_printf_ex` instead.
* \endrst
*/
void TCOD_console_print_ex_utf(
TCOD_Console* con, int x, int y, TCOD_bkgnd_flag_t flag,
TCOD_alignment_t alignment, const wchar_t *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
TCOD_console_print_internal_utf(
con, x, y, 0, 0, flag, alignment, TCOD_console_vsprint_utf(fmt, ap),
false, false);
va_end(ap);
}
int TCOD_console_print_rect_utf(TCOD_Console* con, int x, int y, int w, int h,
const wchar_t *fmt, ...)
{
con = TCOD_console_validate_(con);
if (!con) { return 0; }
va_list ap;
va_start(ap, fmt);
int ret = TCOD_console_print_internal_utf(
con, x, y, w, h, con->bkgnd_flag, con->alignment,
TCOD_console_vsprint_utf(fmt, ap), true, false);
va_end(ap);
return ret;
}
/**
* \rst
* .. deprecated:: 1.8
* Use :any:`TCOD_console_printf_rect_ex` instead.
* \endrst
*/
int TCOD_console_print_rect_ex_utf(
TCOD_Console* con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag,
TCOD_alignment_t alignment, const wchar_t *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
int ret = TCOD_console_print_internal_utf(
con, x, y, w, h, flag, alignment,
TCOD_console_vsprint_utf(fmt, ap), true, false);
va_end(ap);
return ret;
}
/**
* \rst
* .. deprecated:: 1.8
* \endrst
*/
int TCOD_console_get_height_rect_utf(
TCOD_Console* con,int x, int y, int w, int h, const wchar_t *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
int ret = TCOD_console_print_internal_utf(
con, x, y, w, h, TCOD_BKGND_NONE, TCOD_LEFT,
TCOD_console_vsprint_utf(fmt, ap), true, true);
va_end(ap);
return ret;
}
#endif /* NO_UNICODE */
// ----------------------------------------------------------------------------
// New UTF-8 parser.
/**
* Allocates the formatted string to `out` and returns the size.
*
* Returns a negative number on error.
*/
static int vsprint_(char** out, const char *fmt, va_list ap)
{
if (!fmt) { return -1; }
va_list ap_clone;
va_copy(ap_clone, ap);
int size = vsnprintf(NULL, 0, fmt, ap_clone);
va_end(ap_clone);
if (size < 0) { return size; }
*out = malloc(size + 1);
if (!*out) { return -1; }
vsprintf(*out, fmt, ap);
return size;
}
struct FormattedPrinter {
const unsigned char* string;
const unsigned char* end;
struct TCOD_ColorRGBA fg;
struct TCOD_ColorRGBA bg;
const struct TCOD_ColorRGBA default_fg;
const struct TCOD_ColorRGBA default_bg;
};
static TCOD_Error utf8_report_error(int err) {
switch (err) {
case UTF8PROC_ERROR_NOMEM:
TCOD_set_errorv("Out of memory while parsing a UTF-8 string.");
return TCOD_E_OUT_OF_MEMORY;
case UTF8PROC_ERROR_INVALIDUTF8:
TCOD_set_errorv("UTF-8 string is malformed.");
return TCOD_E_ERROR;
default:
if (err < 0) {
TCOD_set_errorvf("Unexpected error while processing UTF-8 string: %d", err);
return TCOD_E_ERROR;
}
return TCOD_E_OK;
}
}
/**
Return the next codepoint without advancing the string pointer.
*/
static int fp_peak_raw(const struct FormattedPrinter* printer)
{
int codepoint;
int err = utf8proc_iterate(printer->string, printer->end - printer->string, &codepoint);
if (err < 0) { return utf8_report_error(err); }
return codepoint;
}
/**
Return the next codepoint and advance the string pointer.
*/
static int fp_next_raw(struct FormattedPrinter* printer)
{
int codepoint;
int len = utf8proc_iterate(printer->string, printer->end - printer->string, &codepoint);
if (len < 0) { return utf8_report_error(len); }
printer->string += len;
return codepoint;
}
/**
Return the next 3 codepoints as a TCOD_ColorRGBA struct and advance.
*/
static struct TCOD_ColorRGBA fp_next_rgba(struct FormattedPrinter* printer)
{
struct TCOD_ColorRGBA rgb = {
fp_next_raw(printer),
fp_next_raw(printer),
fp_next_raw(printer),
255,
};
return rgb;
}
/**
Apply and special formatting codes to this printer and advance.
Special codes are the libtcod color formatting codes, these change the state
if the FormattedPrinter struct.
*/
static void fp_handle_special_codes(struct FormattedPrinter* printer)
{
while(printer->string < printer->end) {
int codepoint = fp_peak_raw(printer);
switch (codepoint) {
case TCOD_COLCTRL_STOP:
fp_next_raw(printer);
printer->fg = printer->default_fg;
printer->bg = printer->default_bg;
break;
case TCOD_COLCTRL_FORE_RGB:
fp_next_raw(printer);
printer->fg = fp_next_rgba(printer);
break;
case TCOD_COLCTRL_BACK_RGB:
fp_next_raw(printer);
printer->bg = fp_next_rgba(printer);
break;
default:
if (codepoint < 0) { return; }
if (TCOD_COLCTRL_1 <= codepoint && codepoint <= TCOD_COLCTRL_NUMBER) {
fp_next_raw(printer);
int color_index = codepoint - TCOD_COLCTRL_1;
*(TCOD_ColorRGB*)&printer->fg = color_control_fore[color_index];
printer->fg.a = 255;
*(TCOD_ColorRGB*)&printer->bg = color_control_back[color_index];
printer->bg.a = 255;
} else {
return;
}
break;
}
}
}
/**
Return the next non-special codepoint and apply any states up to that point.
*/
static int fp_next(struct FormattedPrinter* printer)
{
fp_handle_special_codes(printer);
return fp_next_raw(printer);
}
/**
Return the next non-special codepoint without advancing the string pointer.
*/
static int fp_peak(const struct FormattedPrinter* printer)
{
struct FormattedPrinter temp = *printer;
return fp_next(&temp);
}
/*
* Check if the specified character is any line-break character
*/
static bool is_newline(int codepoint)
{
const utf8proc_property_t* property = utf8proc_get_property(codepoint);
switch (property->category) {
case UTF8PROC_CATEGORY_ZL: /* Separator, line */
case UTF8PROC_CATEGORY_ZP: /* Separator, paragraph */
return true;
case UTF8PROC_CATEGORY_CC: /* Other, control */
switch(property->boundclass) {
case UTF8PROC_BOUNDCLASS_CR: // carriage return - \r
case UTF8PROC_BOUNDCLASS_LF: // line feed - \n
return true;
default: break;
}
break;
default: break;
}
return false;
}
/**
A variable that toggles double wide character handing in print functions.
In theory this option could be made public.
*/
static const bool TCOD_double_width_print_mode = 0;
/**
Return the tile-width for this character.
The result for normally double-width characters will depend on
`TCOD_double_width_print_mode`.
*/
static int get_character_width(int codepoint)
{
const utf8proc_property_t* property = utf8proc_get_property(codepoint);
switch(property->charwidth) {
default:
return (int)property->charwidth;
case 2:
return TCOD_double_width_print_mode ? 2 : 1;
}
}
/**
* Get the next line-break or null terminator, or break the string before
* `max_width`.
*
* `break_point` is the pointer to the line end position.
*
* `break_width` is the width of the line.
*
* Returns true if this function is breaking a line, or false where the line
* doesn't break or breaks on its own (line a new-line.)
*/
static bool next_split_(
const struct FormattedPrinter* printer,
int max_width,
int can_split,
const unsigned char** break_point,
int* break_width)
{
struct FormattedPrinter it = *printer;
// The break point and width of the line.
*break_point = it.end;
*break_width = 0;
// The current line width.
int char_width = 0;
bool separating = false; // True if the last iteration was breakable.
while (it.string != it.end) {
int codepoint = fp_peak(&it);
if (codepoint < 0) { return 0; } // Break out of function on error.
const utf8proc_property_t* property = utf8proc_get_property(codepoint);
if (can_split && char_width > 0) {
switch (property->category) {
default:
if (char_width + get_character_width(codepoint) > max_width) {
// The next character would go over the max width, so return now.
if (*break_point != it.end) {
// Use latest line break if one exists.
return 1;
} else {
// Force a line break here.
*break_point = it.string;
*break_width = char_width;
return 1;
}
}
separating = false;
break;
case UTF8PROC_CATEGORY_PD: // Punctuation, dash
if (char_width + get_character_width(codepoint) > max_width) {
*break_point = it.string;
*break_width = char_width;
return 1;
} else {
char_width += get_character_width(codepoint);
fp_next(&it);
*break_point = it.string;
*break_width = char_width;
separating = true;
continue;
}
break;
case UTF8PROC_CATEGORY_ZS: // Separator, space
if (!separating) {
*break_point = it.string;
*break_width = char_width;
separating = true;
}
break;
}
}
if (is_newline(codepoint)) {
// Always break on newlines.
*break_point = it.string;
*break_width = char_width;
return 0;
}
char_width += get_character_width(codepoint);
fp_next(&it);
}
// Return end of iteration.
*break_point = it.string;
*break_width = char_width;
return 0;
}
static int print_internal_(
TCOD_Console* con,
int x,
int y,
int width,
int height,
int n,
const char* string,
const TCOD_color_t* fg_in,
const TCOD_color_t* bg_in,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t align,
int can_split,
int count_only)
{
static const TCOD_ColorRGBA color_default = {255, 255, 255, 0};
TCOD_ColorRGBA fg = color_default;
TCOD_ColorRGBA bg = color_default;
if (fg_in) {
fg.r = fg_in->r;
fg.g = fg_in->g;
fg.b = fg_in->b;
fg.a = 255;
}
if (bg_in) {
bg.r = bg_in->r;
bg.g = bg_in->g;
bg.b = bg_in->b;
bg.a = 255;
}
struct FormattedPrinter printer = {
.string = (const unsigned char*)string,
.end = (const unsigned char*)string + n,
.fg = fg,
.bg = bg,
.default_fg = fg,
.default_bg = bg,
};
if (!can_split && align == TCOD_RIGHT) {
// In general `can_split = false` is deprecated.
x -= con->w - 1;
width = con->w;
}
// Expand the width/height of 0 to the edge of the console.
if (!width) { width = con->w - x; }
if (!height) { height = con->h - y; }
// Print bounding box.
int left = x;
int right = x + width;
int top = y;
int bottom = y + height;
width = right - left;
height = bottom - top;
if (can_split && (width <= 0 || height <= 0)) {
return 0; // The bounding box is invalid.
}
while (printer.string != printer.end && top < bottom && top < con->h) {
int codepoint = fp_peak(&printer);
if (codepoint < 0) { return codepoint; } // Return error code.
const utf8proc_property_t* property = utf8proc_get_property(codepoint);
// Check for newlines.
if(is_newline(codepoint)) {
if(property->category == UTF8PROC_CATEGORY_ZP) {
top += 2;
} else {
top += 1;
}
fp_next(&printer);
continue;
}
// Get the next line of characters.
const unsigned char* line_break;
int line_width;
int split_status = next_split_(&printer, width, can_split, &line_break, &line_width);
// Set cursor_x from alignment.
int cursor_x = 0;
switch (align) {
default:
case TCOD_LEFT:
cursor_x = left;
break;
case TCOD_RIGHT:
cursor_x = right - line_width;
break;
case TCOD_CENTER:
if (can_split) {
cursor_x = left + (width - line_width) / 2;
} else {
cursor_x = left - (line_width / 2); // Deprecated.
}
break;
}
// True clipping area. Prevent drawing outside of these bounds.
int clip_left = left;
int clip_right = right;
if (!can_split) {
// Bounds are ignored if splitting is off.
clip_left = 0;
clip_right = con->w;
}
while (printer.string < line_break) {
// Iterate over a line of characters.
codepoint = fp_next(&printer);
if (codepoint < 0) { return codepoint; } // Return error code.
if(count_only) { continue; }
if (clip_left <= cursor_x && cursor_x < clip_right) {
// Actually render this line of characters.
TCOD_ColorRGB* fg_rgb = printer.fg.a ? (TCOD_ColorRGB*)&printer.fg : NULL;
TCOD_ColorRGB* bg_rgb = printer.bg.a ? (TCOD_ColorRGB*)&printer.bg : NULL;
TCOD_console_put_rgb(con, cursor_x, top, codepoint, fg_rgb, bg_rgb, flag);
}
cursor_x += get_character_width(codepoint);
}
// Ignore any extra spaces.
while (printer.string != printer.end) {
// Separator, space
if (utf8proc_get_property(fp_peak(&printer))->category != UTF8PROC_CATEGORY_ZS) {
break;
}
codepoint = fp_next(&printer);
if (codepoint < 0) { return codepoint; } // Return error code.
}
// If there was an automatic split earlier then the top is moved down.
if (split_status == 1) { top += 1; }
}
return MIN(top, bottom) - y + 1;
}
/**
* Normalize rectangle values using old libtcod rules where alignment can move
* the rectangle position.
*/
static void normalize_old_rect_(
TCOD_Console* console,
TCOD_alignment_t alignment,
int* x,
int* y,
int* width,
int* height)
{
// Set default width/height if either is zero.
if (*width == 0) { *width = console->w; }
if (*height == 0) { *height = console->h - *y; }
switch(alignment) {
default:
case TCOD_LEFT:
break;
case TCOD_RIGHT:
*x -= *width;
break;
case TCOD_CENTER:
*x -= *width / 2;
break;
}
return;
}
TCOD_Error TCOD_console_printn(
TCOD_Console* con,
int x,
int y,
int n,
const char* str,
const TCOD_color_t* fg,
const TCOD_color_t* bg,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t alignment)
{
con = TCOD_console_validate_(con);
if (!con) {
TCOD_set_errorv("Console pointer must not be NULL.");
return TCOD_E_INVALID_ARGUMENT;
}
int err = print_internal_(con, x, y, con->w, con->h, n, str,
fg, bg, flag, alignment, false, false);
if (err < 0) { return (TCOD_Error)err; }
return TCOD_E_OK;
}
int TCOD_console_printn_rect(
TCOD_Console *con,
int x,
int y,
int width,
int height,
int n,
const char* str,
const TCOD_color_t* fg,
const TCOD_color_t* bg,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t alignment)
{
con = TCOD_console_validate_(con);
if (!con) {
TCOD_set_errorv("Console pointer must not be NULL.");
return TCOD_E_INVALID_ARGUMENT;
}
return print_internal_(con, x, y, width, height, n, str, fg, bg, flag, alignment, true, false);
}
int TCOD_console_get_height_rect_n(
TCOD_Console *console,
int x,
int y,
int width,
int height,
int n,
const char* str)
{
console = TCOD_console_validate_(console);
if (!console) {
TCOD_set_errorv("Console pointer must not be NULL.");
return TCOD_E_INVALID_ARGUMENT;
}
return print_internal_(console, x, y, width, height, n, str, NULL, NULL,
TCOD_BKGND_NONE, TCOD_LEFT, true, true);
}
int TCOD_console_get_height_rect_wn(
int width,
int n,
const char* str)
{
TCOD_Console console = { .w = width, .h = INT_MAX };
return TCOD_console_get_height_rect_n(&console, 0, 0, width, INT_MAX, n, str);
}
TCOD_Error TCOD_console_printn_frame(
struct TCOD_Console *con,
int x,
int y,
int width,
int height,
int n,
const char* title,
const TCOD_color_t* fg,
const TCOD_color_t* bg,
TCOD_bkgnd_flag_t flag,
bool empty)
{
const int left = x;
const int right = x + width - 1;
const int top = y;
const int bottom = y + height - 1;
con = TCOD_console_validate_(con);
if (!con) {
TCOD_set_errorv("Console pointer must not be NULL.");
return TCOD_E_INVALID_ARGUMENT;
}
TCOD_console_put_rgb(con, left, top, 0x250C, fg, bg, flag); // ┌
TCOD_console_put_rgb(con, right, top, 0x2510, fg, bg, flag); // ┐
TCOD_console_put_rgb(con, left, bottom, 0x2514, fg, bg, flag); // └
TCOD_console_put_rgb(con, right, bottom, 0x2518, fg, bg, flag); // ┘
TCOD_console_draw_rect_rgb(
con, x + 1, y, width - 2, 1, 0x2500, fg, bg, flag); // ─
TCOD_console_draw_rect_rgb(
con, x + 1, y + height - 1, width - 2, 1, 0x2500, fg, bg, flag);
TCOD_console_draw_rect_rgb(
con, x, y + 1, 1, height - 2, 0x2502, fg, bg, flag); // │
TCOD_console_draw_rect_rgb(
con, x + width - 1, y + 1, 1, height - 2, 0x2502, fg, bg, flag);
if (empty) {
TCOD_console_draw_rect_rgb(
con, x + 1, y + 1, width - 2, height - 2, 0x20, fg, bg, flag);
}
if (n > 0 && title) {
char* tmp_string = malloc(n + 2);
if (!tmp_string) {
TCOD_set_errorv("Out of memory.");
return TCOD_E_OUT_OF_MEMORY;
}
memcpy(&tmp_string[1], title, n);
tmp_string[0] = ' ';
tmp_string[n + 1] = ' ';
int err = TCOD_console_printn_rect(
con, x, y, width, 1, n + 2, tmp_string, bg, fg, TCOD_BKGND_SET, TCOD_CENTER);
free(tmp_string);
if (err < 0) { return (TCOD_Error)err; }
}
return TCOD_E_OK;
}
TCOD_Error TCOD_console_printf_ex(
TCOD_Console* con,
int x,
int y,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t alignment,
const char *fmt, ...)
{
con = TCOD_console_validate_(con);
if (!con) {
TCOD_set_errorv("Console pointer must not be NULL.");
return TCOD_E_INVALID_ARGUMENT;
}
va_list ap;
va_start(ap, fmt);
char* str = NULL;
int len = vsprint_(&str, fmt, ap);
va_end(ap);
if (len < 0) {
TCOD_set_errorv("Error while resolving formatting string.");
return TCOD_E_ERROR;
}
TCOD_Error err =
TCOD_console_printn(con, x, y, len, str, &con->fore, &con->back, flag, alignment);
free(str);
return err;
}
TCOD_Error TCOD_console_printf(TCOD_Console* con, int x, int y, const char *fmt, ...)
{
con = TCOD_console_validate_(con);
if (!con) {
TCOD_set_errorv("Console pointer must not be NULL.");
return TCOD_E_INVALID_ARGUMENT;
}
va_list ap;
va_start(ap, fmt);
char* str = NULL;
int len = vsprint_(&str, fmt, ap);
va_end(ap);
if (len < 0) {
TCOD_set_errorv("Error while resolving formatting string.");
return TCOD_E_ERROR;
}
int err = TCOD_console_printn(con, x, y, len, str, &con->fore, &con->back, con->bkgnd_flag, con->alignment);
free(str);
return (TCOD_Error)err;
}
int TCOD_console_printf_rect_ex(
struct TCOD_Console* con,
int x, int y, int w, int h,
TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...)
{
con = TCOD_console_validate_(con);
if (!con) {
TCOD_set_errorv("Console pointer must not be NULL.");
return TCOD_E_INVALID_ARGUMENT;
}
normalize_old_rect_(con, alignment, &x, &y, &w, &h);
va_list ap;
va_start(ap, fmt);
char* str = NULL;
int len = vsprint_(&str, fmt, ap);
va_end(ap);
if (len < 0) {
TCOD_set_errorv("Error while resolving formatting string.");
return TCOD_E_ERROR;
}
int ret = TCOD_console_printn_rect(con, x, y, w, h, len, str, &con->fore, &con->back, flag, alignment);
free(str);
return ret;
}
int TCOD_console_printf_rect(
struct TCOD_Console* con, int x, int y, int w, int h, const char *fmt, ...)
{
con = TCOD_console_validate_(con);
if (!con) {
TCOD_set_errorv("Console pointer must not be NULL.");
return TCOD_E_INVALID_ARGUMENT;
}
normalize_old_rect_(con, con->alignment, &x, &y, &w, &h);
va_list ap;
va_start(ap, fmt);
char* str = NULL;
int len = vsprint_(&str, fmt, ap);
va_end(ap);
if (len < 0) {
TCOD_set_errorv("Error while resolving formatting string.");
return TCOD_E_ERROR;
}
int ret = TCOD_console_printn_rect( con, x, y, w, h, len, str, &con->fore, &con->back, con->bkgnd_flag, con->alignment);
free(str);
return ret;
}
int TCOD_console_get_height_rect_fmt(
struct TCOD_Console* con, int x, int y, int w, int h, const char *fmt, ...)
{
con = TCOD_console_validate_(con);
if (!con) {
TCOD_set_errorv("Console pointer must not be NULL.");
return TCOD_E_INVALID_ARGUMENT;
}
normalize_old_rect_(con, TCOD_LEFT, &x, &y, &w, &h);
va_list ap;
va_start(ap, fmt);
char* str = NULL;
int len = vsprint_(&str, fmt, ap);
va_end(ap);
if (len < 0) {
TCOD_set_errorv("Error while resolving formatting string.");
return TCOD_E_ERROR;
}
int ret = TCOD_console_get_height_rect_n(con, x, y, w, h, len, str);
free(str);
return ret;
}
TCOD_Error TCOD_console_printf_frame(struct TCOD_Console *con,
int x, int y, int width, int height, int empty,
TCOD_bkgnd_flag_t flag, const char *fmt, ...)
{
con = TCOD_console_validate_(con);
if (!con) {
TCOD_set_errorv("Console pointer must not be NULL.");
return TCOD_E_INVALID_ARGUMENT;
}
va_list ap;
va_start(ap, fmt);
char* str = NULL;
int len = vsprint_(&str, fmt, ap);
va_end(ap);
if (len < 0) {
TCOD_set_errorv("Error while resolving formatting string.");
return TCOD_E_ERROR;
}
int err = TCOD_console_printn_frame(con, x, y, width, height, len, str, &con->fore, &con->back, flag, empty);
free(str);
return (TCOD_Error)err;
}
| 30.480636 | 122 | 0.604969 |
15851e56c6ba95188971c049b60e7b8690df8389 | 111 | c | C | chill/examples/chill/testcases/echo11/rose_jacobi1.c | CompOpt4Apps/Artifact-DataDepSimplify | 4fa1bf2bda2902fec50a54ee79ae405a554fc9f4 | [
"MIT"
] | 5 | 2019-05-20T03:35:41.000Z | 2021-09-16T22:22:13.000Z | chill/examples/chill/testcases/echo11/rose_jacobi1.c | CompOpt4Apps/Artifact-DataDepSimplify | 4fa1bf2bda2902fec50a54ee79ae405a554fc9f4 | [
"MIT"
] | null | null | null | chill/examples/chill/testcases/echo11/rose_jacobi1.c | CompOpt4Apps/Artifact-DataDepSimplify | 4fa1bf2bda2902fec50a54ee79ae405a554fc9f4 | [
"MIT"
] | null | null | null |
// this source derived from CHILL AST originally from file 'jacobi1.c' as parsed by frontend compiler rose
| 18.5 | 106 | 0.765766 |
9b88adbc5eda9d1acc57a38724264f0904ecb751 | 366 | h | C | c/unused/m_airport.h | alexey-lukyanenko/jdrive | 70d0d5265b9edc731032c5e624449cbeb45e257c | [
"MIT"
] | null | null | null | c/unused/m_airport.h | alexey-lukyanenko/jdrive | 70d0d5265b9edc731032c5e624449cbeb45e257c | [
"MIT"
] | null | null | null | c/unused/m_airport.h | alexey-lukyanenko/jdrive | 70d0d5265b9edc731032c5e624449cbeb45e257c | [
"MIT"
] | null | null | null | #if 0
#include "stdafx.h"
void MunicipalAirport(Town *tn);
bool MA_OwnerHandler(PlayerID owner);
void MA_Tax(int income, Vehicle *v);
void MA_EditorAddAirport(Town* tn);
bool MA_VehicleIsAtMunicipalAirport(Vehicle *v);
bool MA_WithinVehicleQuota(Station *st);
StationID MA_Find_MS_InVehicleOrders(Vehicle *v, int count);
int MA_VehicleServesMS(Vehicle *v);
| 18.3 | 60 | 0.784153 |
afae05fb03a233b324f4703455c862f640f78a51 | 1,428 | h | C | includes/fractal.h | aljourda/fractol | 1276bba90292b553cb12dac4d1c052002c5df679 | [
"Apache-2.0"
] | null | null | null | includes/fractal.h | aljourda/fractol | 1276bba90292b553cb12dac4d1c052002c5df679 | [
"Apache-2.0"
] | null | null | null | includes/fractal.h | aljourda/fractol | 1276bba90292b553cb12dac4d1c052002c5df679 | [
"Apache-2.0"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fractal.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aljourda <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/08/25 13:52:55 by aljourda #+# #+# */
/* Updated: 2016/08/25 13:53:42 by aljourda ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FRACTAL_H
# define FRACTAL_H
# define GETRGB(r,g,b) (((r) << 16) | ((g) << 8)| ((b) << 0))
# define HSV(value) (int)((value) * 255.0f + 0.5)
typedef struct s_fractal
{
double x;
double y;
double z;
double w;
double h;
int n;
double cre;
double cim;
int type;
} t_fractal;
t_fractal *fractal_init(int type, int width, int height);
void fractal_zoom(t_fractal *f, double value);
int fractal_get_pixel(t_fractal *f, int x, int y);
int hsv_to_rgb(float hue, float saturation, float value);
#endif
| 38.594595 | 80 | 0.307423 |
17d6c5da5df65c1ee1ef86aed4cc374e81d653c6 | 428 | h | C | opengl-gui/include/Drawables/Text.h | ChewyGumball/opengl_gui | b2bd1803f0cfb01db08c88da5091546076dfc2a3 | [
"MIT"
] | 2 | 2019-08-27T00:37:11.000Z | 2021-11-25T14:34:23.000Z | opengl-gui/include/Drawables/Text.h | ChewyGumball/opengl_gui | b2bd1803f0cfb01db08c88da5091546076dfc2a3 | [
"MIT"
] | null | null | null | opengl-gui/include/Drawables/Text.h | ChewyGumball/opengl_gui | b2bd1803f0cfb01db08c88da5091546076dfc2a3 | [
"MIT"
] | 2 | 2018-10-18T12:12:28.000Z | 2019-08-27T00:36:21.000Z | #pragma once
#include <string>
#include "Drawables\Drawable.h"
#include "Text\Font.h"
#include "Brushes/FontBrush.h"
#include "Util/Mesh.h"
namespace OpenGLGUI {
class Text : public Drawable
{
private:
std::shared_ptr<FontBrush> brush;
std::shared_ptr<Util::InstancedMesh> mesh;
public:
Text(std::string& text, std::shared_ptr<FontBrush> font);
~Text();
void draw(glm::vec2 origin, glm::vec2 canvasSize);
};
}
| 19.454545 | 59 | 0.71028 |
172b00334fa1563f73d91f0ca9c1faf870a523aa | 6,811 | c | C | lib-src/portaudio-v19/src/hostapi/jack/pa_jack_dynload.c | Marcusz97/CILP_Facilitatore_Audacity | fe7f59365317ce425abbaa79c973e931232c8680 | [
"CC-BY-3.0"
] | 986 | 2021-07-05T22:58:16.000Z | 2022-03-31T03:02:03.000Z | lib-src/portaudio-v19/src/hostapi/jack/pa_jack_dynload.c | Marcusz97/CILP_Facilitatore_Audacity | fe7f59365317ce425abbaa79c973e931232c8680 | [
"CC-BY-3.0"
] | 191 | 2021-07-05T23:02:36.000Z | 2022-03-29T20:31:08.000Z | lib-src/portaudio-v19/src/hostapi/jack/pa_jack_dynload.c | Marcusz97/CILP_Facilitatore_Audacity | fe7f59365317ce425abbaa79c973e931232c8680 | [
"CC-BY-3.0"
] | 124 | 2021-07-05T22:58:01.000Z | 2022-03-27T04:50:02.000Z | /*
* $Id: pa_jack.c 1668 2011-05-02 17:07:11Z rossb $
* PortAudio Portable Real-Time Audio Library
* Latest Version at: http://www.portaudio.com
* JACK Implementation by Joshua Haberman
*
* Copyright (c) 2004 Stefan Westerfeld <stefan@space.twc.de>
* Copyright (c) 2004 Arve Knudsen <aknuds-1@broadpark.no>
* Copyright (c) 2002 Joshua Haberman <joshua@haberman.com>
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2002 Ross Bencina, Phil Burk
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/**
@file
@ingroup hostapi_src
*/
#define PADL_DEFINE_POINTERS
#include "pa_dynload.h"
#include "pa_jack_dynload.h"
#if defined(PA_DYNAMIC_JACK)
static paDynamicLib jacklib = NULL;
#endif
int PaJack_Load(void)
{
#if !defined(PA_DYNAMIC_JACK)
return 1;
#else
#if defined(__APPLE__)
jacklib = PaDL_Load("libjack.dylib");
#elif defined(_WIN64)
jacklib = PaDL_Load("libjack64.dll");
#elif defined(WIN32)
jacklib = PaDL_Load("libjack.dll");
#else
jacklib = PaDL_Load("libjack.so");
#endif
if (!jacklib) {
return 0;
}
PADL_FINDSYMBOL(jacklib, jack_client_name_size, goto error);
PADL_FINDSYMBOL(jacklib, jack_client_name_size, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_ports, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_sample_rate, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_ports, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_by_name, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_get_latency, goto error);
PADL_FINDSYMBOL(jacklib, jack_free, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_ports, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_by_name, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_get_latency, goto error);
PADL_FINDSYMBOL(jacklib, jack_free, goto error);
PADL_FINDSYMBOL(jacklib, jack_client_open, goto error);
PADL_FINDSYMBOL(jacklib, jack_on_shutdown, goto error);
PADL_FINDSYMBOL(jacklib, jack_set_error_function, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_buffer_size, goto error);
PADL_FINDSYMBOL(jacklib, jack_set_sample_rate_callback, goto error);
PADL_FINDSYMBOL(jacklib, jack_set_xrun_callback, goto error);
PADL_FINDSYMBOL(jacklib, jack_set_process_callback, goto error);
PADL_FINDSYMBOL(jacklib, jack_activate, goto error);
PADL_FINDSYMBOL(jacklib, jack_deactivate, goto error);
PADL_FINDSYMBOL(jacklib, jack_client_close, goto error);
PADL_FINDSYMBOL(jacklib, jack_deactivate, goto error);
PADL_FINDSYMBOL(jacklib, jack_client_close, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_sample_rate, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_unregister, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_unregister, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_name_size, goto error);
PADL_FINDSYMBOL(jacklib, jack_client_name_size, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_sample_rate, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_sample_rate, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_name_size, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_register, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_name_size, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_register, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_ports, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_by_name, goto error);
PADL_FINDSYMBOL(jacklib, jack_free, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_ports, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_by_name, goto error);
PADL_FINDSYMBOL(jacklib, jack_free, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_get_latency, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_buffer_size, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_get_latency, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_buffer_size, goto error);
PADL_FINDSYMBOL(jacklib, jack_frame_time, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_sample_rate, goto error);
PADL_FINDSYMBOL(jacklib, jack_frame_time, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_get_latency, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_get_latency, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_get_buffer, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_get_buffer, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_sample_rate, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_get_buffer, goto error);
PADL_FINDSYMBOL(jacklib, jack_connect, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_name, goto error);
PADL_FINDSYMBOL(jacklib, jack_connect, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_name, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_connected, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_disconnect, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_connected, goto error);
PADL_FINDSYMBOL(jacklib, jack_port_disconnect, goto error);
PADL_FINDSYMBOL(jacklib, jack_frame_time, goto error);
PADL_FINDSYMBOL(jacklib, jack_client_name_size, goto error);
PADL_FINDSYMBOL(jacklib, jack_get_client_name, goto error);
return 1;
error:
PaJack_Unload();
return 0;
#endif
}
void PaJack_Unload(void)
{
#if defined(PA_DYNAMIC_JACK)
if (jacklib) {
PaDL_Unload(jacklib);
jacklib = NULL;
}
#endif
}
| 41.785276 | 73 | 0.765673 |
c0a116a28dcc8594ba120bec06f3578c171cd2f9 | 1,462 | h | C | include/exec/global_ddl_manager_node.h | tullyliu/BaikalDB | 08c4430a79c2621714a2bc9b024380877b7db499 | [
"Apache-2.0"
] | 984 | 2018-08-03T16:22:49.000Z | 2022-03-22T07:54:48.000Z | include/exec/global_ddl_manager_node.h | tullyliu/BaikalDB | 08c4430a79c2621714a2bc9b024380877b7db499 | [
"Apache-2.0"
] | 100 | 2018-08-07T11:33:18.000Z | 2021-12-22T19:22:43.000Z | include/exec/global_ddl_manager_node.h | tullyliu/BaikalDB | 08c4430a79c2621714a2bc9b024380877b7db499 | [
"Apache-2.0"
] | 157 | 2018-08-04T05:32:34.000Z | 2022-03-10T03:16:47.000Z | // Copyright (c) 2018-present Baidu, Inc. All Rights Reserved.
//
// 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.
#pragma once
#include "dml_manager_node.h"
#include "fetcher_store.h"
namespace baikaldb {
class GlobalDDLManagerNode : public DmlManagerNode {
public:
GlobalDDLManagerNode();
virtual ~GlobalDDLManagerNode();
virtual int open(RuntimeState* state);
void set_table_id(int64_t table_id) {
_table_id = table_id;
}
void set_index_id(int64_t index_id) {
_index_id = index_id;
}
void set_region_infos(std::map<int64_t, pb::RegionInfo> region_infos) {
_region_infos.swap(region_infos);
}
void set_task_id(const std::string& task_id) {
_task_id = task_id;
}
private:
FetcherStore _fetcher_store;
int64_t _table_id {0};
int64_t _index_id {0};
std::map<int64_t, pb::RegionInfo> _region_infos;
std::string _task_id;
};
} // namespace baikaldbame
| 29.24 | 75 | 0.709986 |
cbd1b2ad66c66cb5f4e196cf29f454d5c9e20d9b | 4,533 | h | C | include/otter-trace/trace-structs.h | adamtuft/otter | e9ac2d337c2c82fb3bd7e1ad68309c02a4494da0 | [
"BSD-3-Clause"
] | 7 | 2021-05-04T17:18:10.000Z | 2022-03-08T07:27:31.000Z | include/otter-trace/trace-structs.h | adamtuft/otter | e9ac2d337c2c82fb3bd7e1ad68309c02a4494da0 | [
"BSD-3-Clause"
] | 13 | 2021-07-02T10:01:43.000Z | 2021-09-09T22:21:19.000Z | include/otter-trace/trace-structs.h | adamtuft/otter | e9ac2d337c2c82fb3bd7e1ad68309c02a4494da0 | [
"BSD-3-Clause"
] | 1 | 2021-07-07T10:47:06.000Z | 2021-07-07T10:47:06.000Z | #if !defined(OTTER_TRACE_STRUCTS_H)
#define OTTER_TRACE_STRUCTS_H
#include <stdint.h>
#include <stdbool.h>
#include <otf2/otf2.h>
#include <otter-ompt-header.h>
#include <otter-common.h>
#include <otter-datatypes/queue.h>
#include <otter-datatypes/stack.h>
#include <otter-trace/trace.h>
/* Forward definitions */
typedef struct trace_parallel_region_attr_t trace_parallel_region_attr_t;
typedef struct trace_region_attr_empty_t trace_region_attr_empty_t;
typedef struct trace_wshare_region_attr_t trace_wshare_region_attr_t;
typedef struct trace_master_region_attr_t trace_master_region_attr_t;
typedef struct trace_sync_region_attr_t trace_sync_region_attr_t;
typedef struct trace_task_region_attr_t trace_task_region_attr_t;
/* Attributes of a parallel region */
struct trace_parallel_region_attr_t {
unique_id_t id;
unique_id_t master_thread;
bool is_league;
unsigned int requested_parallelism;
unsigned int ref_count;
unsigned int enter_count;
pthread_mutex_t lock_rgn;
queue_t *rgn_defs;
};
/* Attributes of a workshare region */
struct trace_wshare_region_attr_t {
ompt_work_t type;
uint64_t count;
};
/* Attributes of a master region */
struct trace_master_region_attr_t {
uint64_t thread;
};
/* Attributes of a sync region */
struct trace_sync_region_attr_t {
ompt_sync_region_t type;
unique_id_t encountering_task_id;
};
/* Attributes of a task region */
struct trace_task_region_attr_t {
unique_id_t id;
ompt_task_flag_t type;
ompt_task_flag_t flags;
int has_dependences;
unique_id_t parent_id;
ompt_task_flag_t parent_type;
ompt_task_status_t task_status;
};
/* Store values needed to register region definition (tasks, parallel regions,
workshare constructs etc.) with OTF2 */
struct trace_region_def_t {
OTF2_RegionRef ref;
OTF2_RegionRole role;
OTF2_AttributeList *attributes;
trace_region_type_t type;
unique_id_t encountering_task_id;
union {
trace_parallel_region_attr_t parallel;
trace_wshare_region_attr_t wshare;
trace_master_region_attr_t master;
trace_sync_region_attr_t sync;
trace_task_region_attr_t task;
} attr;
};
/* Store values needed to register location definition (threads) with OTF2 */
struct trace_location_def_t {
unique_id_t id;
ompt_thread_t thread_type;
uint64_t events;
stack_t *rgn_stack;
queue_t *rgn_defs;
stack_t *rgn_defs_stack;
OTF2_LocationRef ref;
OTF2_LocationType type;
OTF2_LocationGroupRef location_group;
OTF2_AttributeList *attributes;
OTF2_EvtWriter *evt_writer;
OTF2_DefWriter *def_writer;
};
/* Create new location */
trace_location_def_t *
trace_new_location_definition(
uint64_t id,
ompt_thread_t thread_type,
OTF2_LocationType loc_type,
OTF2_LocationGroupRef loc_grp);
/* Create new region */
trace_region_def_t *
trace_new_parallel_region(
unique_id_t id,
unique_id_t master,
unique_id_t encountering_task_id,
int flags,
unsigned int requested_parallelism);
trace_region_def_t *
trace_new_workshare_region(
trace_location_def_t *loc,
ompt_work_t wstype,
uint64_t count,
unique_id_t encountering_task_id);
trace_region_def_t *
trace_new_master_region(
trace_location_def_t *loc,
unique_id_t encountering_task_id);
trace_region_def_t *
trace_new_sync_region(
trace_location_def_t *loc,
ompt_sync_region_t stype,
unique_id_t encountering_task_id);
trace_region_def_t *
trace_new_task_region(
trace_location_def_t *loc,
trace_region_def_t *parent_task_region,
unique_id_t task_id,
ompt_task_flag_t flags,
int has_dependences);
/* Destroy location/region */
void trace_destroy_location(trace_location_def_t *loc);
void trace_destroy_parallel_region(trace_region_def_t *rgn);
void trace_destroy_workshare_region(trace_region_def_t *rgn);
void trace_destroy_master_region(trace_region_def_t *rgn);
void trace_destroy_sync_region(trace_region_def_t *rgn);
void trace_destroy_task_region(trace_region_def_t *rgn);
#endif // OTTER_TRACE_STRUCTS_H
| 30.836735 | 79 | 0.709243 |
c44207ccd9579af7c2346e9950f51b4e864b5f53 | 2,545 | h | C | 4I504 - Compilation/MIPS Analyzer/include/Function.h | ghivert/Student-Projects | 43d7a61eac94365b3296ea09311f855ac00d71d1 | [
"MIT"
] | 2 | 2017-09-11T19:13:06.000Z | 2020-01-20T09:05:40.000Z | 4I504 - Compilation/MIPS Analyzer/include/Function.h | ghivert/Student-Projects | 43d7a61eac94365b3296ea09311f855ac00d71d1 | [
"MIT"
] | null | null | null | 4I504 - Compilation/MIPS Analyzer/include/Function.h | ghivert/Student-Projects | 43d7a61eac94365b3296ea09311f855ac00d71d1 | [
"MIT"
] | 3 | 2017-02-08T18:01:56.000Z | 2018-10-04T21:30:08.000Z | #ifndef _Function_H
#define _Function_H
/** \file Function.h
\brief Function class
\author Hajjem
*/
#include <Line.h>
/*#include <Directive.h>
#include <Instruction.h>*/
#include <Basic_block.h>
#include <Instruction.h>
#include <string>
#include <stdio.h>
#include <Label.h>
#include <Enum_type.h>
#include <list>
#include <Cfg.h>
#include <fstream>
using namespace std;
/** \class Function
\brief class representing a Function on a program
*/
class Function{
public:
/** \brief Constructor of a function
*/
Function();
/** \brief Destructor of a function
*/
~Function();
/** \brief setter of the head of the function
*/
void set_head(Line *);
/** \brief setter of the end of the function
*/
void set_end(Line *);
/** \brief get the head of the function
*/
Line* get_head();
Basic_block *get_firstBB();
/** \brief get the end of the function
*/
Line* get_end();
/** \brief display the function
*/
void display();
/** \brief get the size of the function
*/
int size();
/** \brief restitute the function in a file
*/
void restitution(string const);
/** \brief creates a new BB with the given start line, end line and branch line and its index, add it to the BB list of this
*/
void add_BB(Line *, Line*, Line*, int);
/** \brief Calculate the basics bolck of the function
*/
void comput_basic_block();
/** \brief get the number of Basic block in the function
*/
int nbr_BB();
/** \brief get the Basic Block in the list
*/
Basic_block *get_BB(int);
list<Basic_block*>::iterator bb_list_begin();
list<Basic_block*>::iterator bb_list_end();
/** \brief comput labels of the function in list
*/
void comput_label();
/** \brief get all labels of the function
*/
Label* get_label(int);
/** \brief get the size of the list label
*/
int nbr_label();
/** \brief Get the basic block corresponding to the label
*/
Basic_block *find_label_BB(OPLabel*);
/** \brief Associate for each Basic block its successors
*/
void comput_succ_pred_BB();
/** \brief method to test other methods
*/
void test();
/** \brief compute live variable
*/
void compute_live_var();
void compute_dom();
private:
bool BB_computed;
bool BB_pred_succ;
bool dom_computed;
Line *_head;
Line *_end;
list <Basic_block*> _myBB;
list <Label*> _list_lab;
};
#endif
| 19.728682 | 127 | 0.620825 |
c485970cec02801f990ce92a60f3b8ebad6462af | 3,235 | c | C | doublyLinkedList.c | guilherme9820/Scheduling-Test | e54f10dbdf3aeaa2d83daa70ef632c166d2ff2a5 | [
"Unlicense"
] | null | null | null | doublyLinkedList.c | guilherme9820/Scheduling-Test | e54f10dbdf3aeaa2d83daa70ef632c166d2ff2a5 | [
"Unlicense"
] | null | null | null | doublyLinkedList.c | guilherme9820/Scheduling-Test | e54f10dbdf3aeaa2d83daa70ef632c166d2ff2a5 | [
"Unlicense"
] | null | null | null | #include "doublyLinkedList.h"
lista* inicializa_lista(){
lista *novo_valor;
novo_valor = (lista*) malloc(sizeof(lista));
novo_valor->tamanho = 0;
novo_valor->anterior = NULL;
novo_valor->proximo = NULL;
return novo_valor;
}
tarefa* inicializa_tarefa(int compt, int period){
tarefa *task;
task = (tarefa*) malloc(sizeof(tarefa));
task->periodo = period;
task->computacao = compt;
task->posicao = 0;
task->prox = NULL;
task->ant = NULL;
return task;
}
void adiciona_na_lista(lista *list, tarefa *task){
lista *novo_valor;
if(list->proximo == NULL){
list->proximo = task;
list->anterior = task;
}else{
novo_valor = (lista*) malloc(sizeof(lista));
novo_valor->proximo = task;
novo_valor->anterior = list->proximo;
list->proximo = task;
list->proximo->ant = novo_valor->anterior;
novo_valor->anterior->prox = list->proximo;
list->proximo->prox = NULL;
free(novo_valor);
}
list->tamanho++;
task->posicao = list->tamanho;
}
void printa_lista(lista *list){
tarefa *task_iterator;
if(list != NULL)
task_iterator = list->anterior;
else
task_iterator = NULL;
if(task_iterator != NULL){
while(task_iterator != NULL){
printf("Computacao: %d; Periodo: %d; Posicao: %d\n",task_iterator->computacao, task_iterator->periodo, task_iterator->posicao);
task_iterator = task_iterator->prox;
}
}else
printf("A lista esta vazia!");
}
void printa_lista_reversa(lista *list){
tarefa *task_iterator;
if(list != NULL)
task_iterator = list->proximo;
else
task_iterator = NULL;
if(task_iterator != NULL){
while(task_iterator != NULL){
printf("Computacao: %d; Periodo: %d; Posicao: %d\n",task_iterator->computacao, task_iterator->periodo, task_iterator->posicao);
task_iterator = task_iterator->ant;
}
}else
printf("A lista esta vazia!");
}
lista* apaga_lista(lista *list){
tarefa *task_iterator;
while(list->anterior != NULL){
task_iterator = list->anterior;
list->anterior = list->anterior->prox;
free(task_iterator);
task_iterator = NULL;
list->tamanho--;
}
free(list);
return NULL;
}
void recupera_extremidades(lista *list, tarefa *task){
tarefa *task_aux = task;
while(task_aux != NULL){
list->anterior = task_aux;
task_aux = task_aux->ant;
}
while(task != NULL){
list->proximo = task;
task = task->prox;
}
}
tarefa* procura_na_lista(lista *list, int pos){
tarefa *task_iterator;
if(list != NULL)
task_iterator = list->anterior;
else
task_iterator = NULL;
if(task_iterator != NULL){
while(task_iterator != NULL){
if(task_iterator->posicao == pos)
break;
else
task_iterator = task_iterator->prox;
}
}else
printf("A lista esta vazia!");
return task_iterator;
} | 27.887931 | 140 | 0.573416 |
1632b198fadaf716196bfd018128e6b02b91bc91 | 3,329 | c | C | goldenbox_128/CLCD.c | radii-dev/Ice-box-for-organ-transport | 187942d079dc95b6f66337cad1e373d1badfa9cc | [
"MIT"
] | null | null | null | goldenbox_128/CLCD.c | radii-dev/Ice-box-for-organ-transport | 187942d079dc95b6f66337cad1e373d1badfa9cc | [
"MIT"
] | null | null | null | goldenbox_128/CLCD.c | radii-dev/Ice-box-for-organ-transport | 187942d079dc95b6f66337cad1e373d1badfa9cc | [
"MIT"
] | null | null | null | /*
* CLCD.c
*
* Created: 2019-10-09 오후 3:24:03
* Author: gigas
*/
#define F_CPU 16000000L
#include <avr/io.h>
#include <stdio.h>
#include <util/delay.h>
#include "CLCD.h"
void LCD_pulse_enable(void){ // 하강에지에서 동작
PORT_CONTROL |= (1<<E_PIN);
_delay_ms(1);
PORT_CONTROL &= ~(1<<E_PIN);
_delay_ms(1);
}
void LCD_write_data(uint8_t data){ //문자 한글자 쓰기
PORT_CONTROL |=(1<<RS_PIN); //출력모드
PORT_DATA = data; //문자데이터
LCD_pulse_enable(); // 출력실행
_delay_ms(2);
}
void LCD_write_command(uint8_t command){
PORT_CONTROL &= ~(1<<RS_PIN); //명령어 실행모드
PORT_DATA = command; //명령어 전달
LCD_pulse_enable(); //명령어 실행
_delay_ms(2);
}
void LCD_clear(void){
LCD_write_command(COMMAND_CLEAR_DISPLAY);
_delay_ms(2); // LCD 지우기
}
void LCD_init(void){
_delay_ms(50);
DDR_DATA=0xFF; // PORTD를 출력으로 설정
PORT_DATA =0x00;
DDR_CONTROL |= (1<<RS_PIN) | (1<<RW_PIN) | (1<<E_PIN);
PORT_CONTROL &= ~(1<<RW_PIN); // 쓰기모드
LCD_write_command(COMMAND_8_BIT_MODE); //8비트 모드
uint8_t command = 0x08 | (1<<COMMAND_DISPLAY_ON_OFF_BIT);
LCD_write_command(command);
LCD_clear();
LCD_write_command(0x06);
}
void LCD_write_string(char *string){
uint8_t i;
for(i=0;string[i];i++)
LCD_write_data(string[i]); //문자열 출력
}
void LCD_goto_XY(uint8_t row, uint8_t col){
col %= 16;
row %= 2;
uint8_t address = (0x40 * row) + col;
uint8_t command = 0x80 + address;
LCD_write_command(command); //LCD 좌표설정
}
void timer(int t[], int mode) {
t[0]++;
if(t[0] == 58) {
t[0] = 48;
t[1]++;
}
if(t[1] == 54) {
t[0] = 48;
t[1] = 48;
t[2]++;
}
if(t[2] == 58) {
t[2] = 48;
t[3]++;
}
if(t[3] == 54){
t[2] = 48;
t[3] = 48;
t[4]++;
}
if(t[4]>=58){
t[4]=48;
t[5]++;
}
LCD_goto_XY(mode, 8);
LCD_write_data(t[5]);
LCD_goto_XY(mode, 9);
LCD_write_data(t[4]);
LCD_goto_XY(mode, 11);
LCD_write_data(t[3]);
LCD_goto_XY(mode, 12);
LCD_write_data(t[2]);
LCD_goto_XY(mode, 14);
LCD_write_data(t[1]);
LCD_goto_XY(mode, 15);
LCD_write_data(t[0]);
}
void setCLCD() {
LCD_goto_XY(1,8);
LCD_write_string("00:00:00");
LCD_goto_XY(0,8);
LCD_write_string("00:00:00");
}
void tempCLCD(float temp) {
char s1[10] = {0,};
sprintf(s1, "%.1f", temp);
if(temp == 0) {
LCD_goto_XY(0, 0);
LCD_write_string(" ");
LCD_goto_XY(0, 0);
LCD_write_string("0");
LCD_goto_XY(0, 2);
LCD_write_string("C");
}
else if(temp > 0 && temp < 10) {
LCD_goto_XY(0, 0);
LCD_write_string(" ");
LCD_goto_XY(0, 2);
LCD_write_string(s1);
LCD_goto_XY(0, 4);
LCD_write_string("C");
}
else if((temp < 0 && temp > -10) || (temp >= 10 && temp < 100)) {
LCD_goto_XY(0, 0);
LCD_write_string(" ");
LCD_goto_XY(0, 0);
LCD_write_string(s1);
LCD_goto_XY(0, 5);
LCD_write_string("C");
}
else if((temp <= -10 && temp > -100) || (temp >= 100)) {
LCD_goto_XY(0, 0);
LCD_write_string(" ");
LCD_goto_XY(0, 0);
LCD_write_string(s1);
LCD_goto_XY(0, 6);
LCD_write_string("C");
}
if(temp >= 10){
LCD_goto_XY(1, 0);
LCD_write_string("Danger ");
}
else if(temp >= 5 && temp < 10){
LCD_goto_XY(1, 0);
LCD_write_string("Warning ");
}
else if(temp < 5){
LCD_goto_XY(1, 0);
LCD_write_string("OK ");
}
} | 20.937107 | 66 | 0.582457 |
e99b592086f4a3d983d60236f85283484fa75493 | 587 | h | C | BarbaTunnel/BarbaPortRange.h | Soldie/BarbaTunnel-C- | d61924d20276f59e3e80286695d2359f95abd712 | [
"MIT"
] | 159 | 2017-06-06T02:05:08.000Z | 2022-03-27T05:37:42.000Z | BarbaTunnel/BarbaPortRange.h | Soldie/BarbaTunnel-C- | d61924d20276f59e3e80286695d2359f95abd712 | [
"MIT"
] | 5 | 2018-01-16T09:32:43.000Z | 2018-12-27T14:21:01.000Z | BarbaTunnel/BarbaPortRange.h | Soldie/BarbaTunnel-C- | d61924d20276f59e3e80286695d2359f95abd712 | [
"MIT"
] | 43 | 2017-06-06T00:42:44.000Z | 2022-01-24T16:07:19.000Z | #pragma once
#include "General.h"
class BarbaPortRange
{
public:
//PortRange
struct PortRangeItem
{
u_short StartPort;
u_short EndPort;
};
public:
BarbaPortRange(void);
~BarbaPortRange(void);
size_t GetPortsCount();
u_short GetRandomPort();
bool IsPortInRange(u_short port);
void GetAllPorts(BarbaArray<u_short>* ports);
//@param value: StartPort-EndPort,StartPort-EndPort,StartPort-EndPort
void Parse(LPCTSTR value);
std::tstring ToString();
static bool ParsePortRangeItem(LPCTSTR value, u_short* startPort, u_short* endPort);
BarbaArray<PortRangeItem> Items;
};
| 20.241379 | 85 | 0.764906 |
acbfda903451b5ef6f6e997370f258a79b6dab58 | 4,185 | h | C | third_party/webrtc/include/chromium/src/ash/common/system/tray/special_popup_row.h | ssaroha/node-webrtc | 74335bd07cbc52484a88c8eeb336c9bd001928a8 | [
"BSD-2-Clause"
] | 3 | 2018-02-22T18:06:56.000Z | 2021-08-28T12:49:27.000Z | third_party/webrtc/include/chromium/src/ash/common/system/tray/special_popup_row.h | ssaroha/node-webrtc | 74335bd07cbc52484a88c8eeb336c9bd001928a8 | [
"BSD-2-Clause"
] | null | null | null | third_party/webrtc/include/chromium/src/ash/common/system/tray/special_popup_row.h | ssaroha/node-webrtc | 74335bd07cbc52484a88c8eeb336c9bd001928a8 | [
"BSD-2-Clause"
] | 2 | 2017-08-16T08:15:01.000Z | 2018-03-27T00:07:30.000Z | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_COMMON_SYSTEM_TRAY_SPECIAL_POPUP_ROW_H_
#define ASH_COMMON_SYSTEM_TRAY_SPECIAL_POPUP_ROW_H_
#include "ash/ash_export.h"
#include "ash/common/login_status.h"
#include "ash/resources/vector_icons/vector_icons.h"
#include "base/macros.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/view.h"
namespace views {
class Button;
class ButtonListener;
class CustomButton;
class Label;
class ToggleButton;
}
namespace ash {
class SystemMenuButton;
class ThrobberView;
class TrayItemView;
class TrayPopupHeaderButton;
class ViewClickListener;
// For material design, this class represents the top title row for detailed
// views and handles the creation and layout of its elements (back button,
// title, settings button, and possibly other buttons). For non-MD, this class
// represents the bottom row of detailed views and the bottom row of the
// system menu (date, help, power, and lock). This row has a fixed height.
class ASH_EXPORT SpecialPopupRow : public views::View {
public:
SpecialPopupRow();
~SpecialPopupRow() override;
// Creates a text label corresponding to |string_id| and sets it as the
// content of this row.
void SetTextLabel(int string_id, ViewClickListener* listener);
// Sets |content_| to be |view| and adds |content_| as a child view of this
// row. This should only be called once, upon initialization of the row.
// TODO(tdanderson): Make this private when material design is enabled by
// default. See crbug.com/614453.
void SetContent(views::View* view);
// Creates UI elements for the material design title row and adds them to
// the view hierarchy rooted at |this|. Returns a pointer to the created
// view.
views::Button* AddBackButton(views::ButtonListener* listener);
views::CustomButton* AddSettingsButton(views::ButtonListener* listener,
LoginStatus status);
views::CustomButton* AddHelpButton(views::ButtonListener* listener,
LoginStatus status);
views::ToggleButton* AddToggleButton(views::ButtonListener* listener);
// Adds |view| after this row's content.
void AddViewToTitleRow(views::View* view);
// Adds |view| after this row's content, optionally with a separator. Only
// used for non-MD.
// TODO(tdanderson): Remove this when material design is enabled by default.
// See crbug.com/614453.
void AddViewToRowNonMd(views::View* view, bool add_separator);
// TODO(tdanderson): Remove this accessor when material design is enabled by
// default. See crbug.com/614453.
views::View* content() const { return content_; }
private:
// views::View:
gfx::Size GetPreferredSize() const override;
int GetHeightForWidth(int width) const override;
void Layout() override;
void OnNativeThemeChanged(const ui::NativeTheme* theme) override;
// Updates the style of |label_|, if it exists. Only used in material design.
void UpdateStyle();
// Used to add views to |views_before_content_container_| and
// |views_after_content_container_|, respectively. Views are added to both
// containers in a left-to-right order.
void AddViewBeforeContent(views::View* view);
void AddViewAfterContent(views::View* view);
void AddViewAfterContent(views::View* view, bool add_separator);
void SetTextLabelMd(int string_id, ViewClickListener* listener);
void SetTextLabelNonMd(int string_id, ViewClickListener* listener);
// The container for the views positioned before |content_|.
views::View* views_before_content_container_;
// The main content of this row, typically a label.
views::View* content_;
// The container for the views positioned after |content_|.
views::View* views_after_content_container_;
// A pointer to the label which is parented to |content_|; this is non-null
// only if this row's content is a single label. Not owned.
views::Label* label_;
DISALLOW_COPY_AND_ASSIGN(SpecialPopupRow);
};
} // namespace ash
#endif // ASH_COMMON_SYSTEM_TRAY_SPECIAL_POPUP_ROW_H_
| 37.366071 | 79 | 0.744325 |
3ac8f1f0eeed068d0b07c9a9aa7948b92de62e9a | 2,933 | h | C | Library/Math/RXO.h | avimosher/shapesifter | 8b42200220764b8082fadad9bf5346b5d1844c06 | [
"MIT"
] | null | null | null | Library/Math/RXO.h | avimosher/shapesifter | 8b42200220764b8082fadad9bf5346b5d1844c06 | [
"MIT"
] | null | null | null | Library/Math/RXO.h | avimosher/shapesifter | 8b42200220764b8082fadad9bf5346b5d1844c06 | [
"MIT"
] | null | null | null | #ifndef __RXO__
#define __RXO__
#include <Math/Q_V.h>
#include <Math/Q_W.h>
namespace Mechanics{
// rotation times offset
template<class TV,int R>
struct RXO:public Function<TV,TV,RXO<TV,R>>
{
typedef Function<TV,TV,RXO<TV,R>> BASE;
using typename BASE::T;using typename BASE::M_VxV;using typename BASE::T_TENSOR;using typename BASE::T_SPIN;using typename BASE::TV_T;
static TV Evaluate(const TV& f,const std::array<T_SPIN,2>& spin,const std::array<TV,2>& offset){
return ROTATION<TV>::From_Rotation_Vector(spin[R])*offset[R];}
template<int V1,int VTYPE,std::enable_if_t<VTYPE==ANGULAR && V1==R>* = nullptr>
static M_VxV First_Derivative(const TV& f,const std::array<T_SPIN,2>& spin,const std::array<TV,2>& offset){
T norm_spin=std::max((T)epsilon(),spin[R].norm());
TV_T dw_dspin=Q_W<TV>::First_Derivative(spin[R],norm_spin);
M_VxV dq_dspin=Q_V<TV>::First_Derivative(spin[R],norm_spin);
T w=cos(norm_spin/2);
TV q=sinc(norm_spin/2)*spin[R]/2;
return (2*q.cross(offset[R])*dw_dspin-2*(Cross_Product_Matrix(offset[R])*w+Cross_Product_Matrix(q.cross(offset[R]))+Cross_Product_Matrix(q)*Cross_Product_Matrix(offset[R]))*dq_dspin).transpose();
}
template<int V1,int VTYPE,std::enable_if_t<!(VTYPE==ANGULAR && V1==R)>* = nullptr>
static M_VxV First_Derivative(const TV& f,const std::array<T_SPIN,2>& spin,const std::array<TV,2>& offset){
return M_VxV::Zero();}
template<int V1,int VTYPE1,int V2,int VTYPE2,std::enable_if_t<VTYPE1==ANGULAR && VTYPE2==ANGULAR && V1==V2 && V1==R>* = nullptr>
static T_TENSOR Second_Derivative(const TV& f,const std::array<T_SPIN,2>& spin,const std::array<TV,2>& offset){
ROTATION<TV> rotation(ROTATION<TV>::From_Rotation_Vector(spin[R]));
TV q=rotation.vec();
T w=rotation.w();
M_VxV ostar=Cross_Product_Matrix(offset[R]);
T ns=std::max((T)epsilon(),spin[R].norm());
M_VxV d2w_ds2=Q_W<TV>::Second_Derivative(spin[R],ns);
T_TENSOR d2q_ds2=Q_V<TV>::Second_Derivative(spin[R],ns);
TV s_ns=spin[R]/ns;
M_VxV dq_ds=Q_V<TV>::First_Derivative(spin[R],ns);
TV dw_ds=Q_W<TV>::First_Derivative(spin[R],ns);
return Outer_Product(-2*ostar*dq_ds,dw_ds,{2,1,0})+
Outer_Product(d2w_ds2,(2*q.cross(offset[R])).eval(),{0,1,2})+
Outer_Product(ostar*dq_ds,(dw_ds*(-2)).eval(),{2,0,1})+Cross_Product(-2*dq_ds,(ostar*dq_ds).eval())+Cross_Product(2*ostar*dq_ds,dq_ds)+
Cross_Product(-2*(w*ostar+Cross_Product_Matrix(q.cross(offset[R]))+Cross_Product_Matrix(q)*ostar),d2q_ds2);
}
template<int V1,int VTYPE1,int V2,int VTYPE2,std::enable_if_t<!(VTYPE1==ANGULAR && VTYPE2==ANGULAR && V1==V2 && V1==R)>* = nullptr>
static T_TENSOR Second_Derivative(const TV& f,const std::array<T_SPIN,2>& spin,const std::array<TV,2>& offset){
T_TENSOR t;t.setZero();return t;
}
};
}
#endif
| 51.45614 | 203 | 0.670644 |
5c672234482f164983bd3c18fdb9065100d30033 | 6,671 | h | C | key.h | qbit-t/qb | c1fd82df3838f8526fc5e335254529ab6f953f78 | [
"MIT"
] | 1 | 2021-02-14T04:04:50.000Z | 2021-02-14T04:04:50.000Z | key.h | qbit-t/qb | c1fd82df3838f8526fc5e335254529ab6f953f78 | [
"MIT"
] | null | null | null | key.h | qbit-t/qb | c1fd82df3838f8526fc5e335254529ab6f953f78 | [
"MIT"
] | 1 | 2021-08-28T07:42:43.000Z | 2021-08-28T07:42:43.000Z | // Copyright (c) 2019 Andrew Demuskov
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef QBIT_KEY_H
#define QBIT_KEY_H
//
// allocator.h _MUST_ be included BEFORE all other
//
#include "allocator.h"
#include "uint256.h"
#include "crypto/sha256.h"
#include <list>
#include "hash.h"
#include "context.h"
#include "containers.h"
#include "utilstrencodings.h"
#include "serialize.h"
namespace qbit {
#define KEY_LEN 32
#define KEY_HASH_LEN 64
#define KEY_BUF_LEN 128
#define WORD_LEN 64
#define PKEY_LEN 65
//
// TODO: PKey consists: 4 bytes - chain identity, 65 | 33 - pubkey data calculated from secret key
// chain identity - genesis block hash (sha256 first 32 bit)
//
class PKey
{
public:
PKey() {}
PKey(ContextPtr context) { context_ = context; }
PKey(const std::string& str) { fromString(str); }
~PKey() {
if (context_) context_.reset();
}
template <typename T> PKey(const T pbegin, const T pend)
{
set(pbegin, pend);
}
PKey(const std::vector<unsigned char>& vch)
{
set(vch.begin(), vch.end());
}
void setContext(ContextPtr context) { context_ = context; }
void setPackedSize(unsigned int size) { size_ = size; }
unsigned int getPackedSize() { return size_; }
unsigned int size() const { return length(vch_[0]); }
const unsigned char* begin() const { return vch_; }
const unsigned char* end() const { return vch_ + size(); }
const unsigned char& operator[](unsigned int pos) const { return vch_[pos]; }
std::string toString() const;
std::string toString(unsigned int len) const;
std::string toHex() { return HexStr(begin(), end()); }
bool fromString(const std::string&);
bool valid() const
{
return size() > 0;
}
static unsigned short miner() {
return 0xFFFA;
}
uint256 hash();
void invalidate()
{
vch_[0] = 0xFF;
}
qbit::vector<unsigned char> get()
{
qbit::vector<unsigned char> lKey;
lKey.insert(lKey.end(), vch_, vch_+size());
return lKey;
}
template <typename T> void set(const T pbegin, const T pend)
{
int len = pend == pbegin ? 0 : length(pbegin[0]);
if (len && len == (pend - pbegin))
memcpy(vch_, (unsigned char*)&pbegin[0], len);
else
invalidate();
}
uint160 id() const
{
return Hash160(vch_, vch_ + size());
}
bool verify(const uint256& hash /*data chunk hash*/, std::vector<unsigned char>& signature /*resulting signature*/);
bool verify(const uint256& hash /*data chunk hash*/, const uint512& signature /*resulting signature*/);
std::vector<unsigned char> unpack();
bool pack(unsigned char*);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void serializationOp(Stream& s, Operation ser_action) {
READWRITE(vch_);
}
friend inline bool operator < (const PKey& a, const PKey& b) {
return a.id() < b.id();
}
private:
unsigned int static length(unsigned char chHeader)
{
if (chHeader == 2 || chHeader == 3)
return 33;
if (chHeader == 4 || chHeader == 6 || chHeader == 7)
return 65;
return 0;
}
inline ContextPtr getContext() { if (!context_) context_ = Context::instance(); return context_; }
ContextPtr context_;
unsigned char vch_[PKEY_LEN] = {0};
unsigned int size_;
};
class SKey;
typedef std::shared_ptr<SKey> SKeyPtr;
class SKey {
public:
class Word {
public:
Word() {}
Word(const std::string& word) {
if (word.size() < WORD_LEN) memcpy(word_, word.c_str(), word.size());
else memcpy(word_, word.c_str(), WORD_LEN-1);
}
template<typename Stream>
void serialize(Stream& s) const
{
s.write((char*)word_, sizeof(word_));
}
template<typename Stream>
void deserialize(Stream& s)
{
s.read((char*)word_, sizeof(word_));
}
std::basic_string<unsigned char> word() { return std::basic_string<unsigned char>(word_); }
std::basic_string<char> wordA() { return std::basic_string<char>((char*)word_); }
private:
unsigned char word_[WORD_LEN] = {0};
};
public:
SKey() { valid_ = false; }
SKey(ContextPtr);
SKey(ContextPtr, const std::list<std::string>&);
SKey(const std::list<std::string>&);
~SKey() {
if (context_) context_.reset();
}
const unsigned char* begin() const { return vch_; }
const unsigned char* end() const { return vch_ + size(); }
unsigned int size() const { return (valid_ ? KEY_LEN : 0); }
const unsigned char& operator[](unsigned int pos) const { return vch_[pos]; }
bool create();
PKey createPKey();
std::string toString() const;
std::string toHex() { return HexStr(begin(), end()); }
static SKeyPtr instance() {
return std::make_shared<SKey>();
}
static SKeyPtr instance(const SKey& key) {
return std::make_shared<SKey>(key);
}
template <typename T> void set(const T pbegin, const T pend)
{
if (pend - pbegin != KEY_LEN) {
valid_ = false;
return;
}
if (check(&pbegin[0])) {
memcpy(vch_, (unsigned char*)&pbegin[0], KEY_LEN);
valid_ = true;
} else {
valid_ = false;
}
}
bool valid() { return valid_; }
bool encrypted() { return encrypted_; }
bool equal(const uint256& key) {
return !memcmp(vch_, key.begin(), key.size());
}
void setEncryptedKey(const std::vector<unsigned char>& key) {
encryptedKey_.clear();
encryptedKey_.insert(encryptedKey_.end(), key.begin(), key.end());
}
void encrypt(const std::string&);
void decrypt(const std::string&);
bool sign(const uint256& hash /*data chunk hash*/, std::vector<unsigned char>& signature /*resulting signature*/);
bool sign(const uint256& hash /*data chunk hash*/, uint512& signature /*resulting signature*/);
uint256 shared(const PKey& other);
inline ContextPtr context() { return getContext(); }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void serializationOp(Stream& s, Operation ser_action) {
//
if (!ser_action.ForRead()) {
READWRITE(valid_);
READWRITE(encrypted_);
//
if (encrypted_) {
READWRITE(encryptedKey_);
} else {
READWRITE(vch_);
READWRITE(seed_);
}
if (vch_[0] != 0 && vch_[KEY_LEN-1] != 0)
valid_ = true;
} else {
READWRITE(valid_);
READWRITE(encrypted_);
//
if (encrypted_) {
READWRITE(encryptedKey_);
} else {
READWRITE(vch_);
READWRITE(seed_);
}
}
}
std::vector<Word>& seed() { return seed_; }
private:
bool check(const unsigned char *vch);
inline ContextPtr getContext() { if (!context_) context_ = Context::instance(); return context_; }
private:
ContextPtr context_;
std::vector<Word> seed_;
unsigned char vch_[KEY_LEN] = {0};
std::vector<unsigned char> encryptedKey_;
bool encrypted_ = false;
bool valid_ = false;
PKey pkey_;
};
} // qbit
#endif
| 23.003448 | 117 | 0.671264 |
b155f103f769363fa50f403d79ae279ebe6561a1 | 210 | h | C | gzcom-dll/include/cIGZCanvasMessage.h | caspervg/gzcom-dll | 58662321b12d8db2f82421902d6048390a90c365 | [
"MIT"
] | 20 | 2016-05-17T07:15:19.000Z | 2022-01-03T14:00:18.000Z | gzcom-dll/include/cIGZCanvasMessage.h | caspervg/gzcom-dll | 58662321b12d8db2f82421902d6048390a90c365 | [
"MIT"
] | 2 | 2016-10-30T07:05:00.000Z | 2017-07-17T14:19:33.000Z | gzcom-dll/include/cIGZCanvasMessage.h | caspervg/gzcom-dll | 58662321b12d8db2f82421902d6048390a90c365 | [
"MIT"
] | 7 | 2015-07-10T08:38:23.000Z | 2021-09-15T15:09:13.000Z | #pragma once
#include "cIGZMessage2.h"
class cIGZCanvasMessage : public cIGZMessage2
{
public:
virtual cIGZCanvasMessage* Initialize(uint32_t dwCanvasEventID) = 0;
virtual uint32_t EventType(void) = 0;
}; | 23.333333 | 70 | 0.77619 |
7515065384423a05621aaf04db0380d78c09e262 | 5,161 | h | C | stratum/hal/lib/common/admin_utils_interface.h | aweimeow/stratum | c59318e43ddc1572c04f3e7b0d2a4d0e0c243ae4 | [
"Apache-2.0"
] | null | null | null | stratum/hal/lib/common/admin_utils_interface.h | aweimeow/stratum | c59318e43ddc1572c04f3e7b0d2a4d0e0c243ae4 | [
"Apache-2.0"
] | null | null | null | stratum/hal/lib/common/admin_utils_interface.h | aweimeow/stratum | c59318e43ddc1572c04f3e7b0d2a4d0e0c243ae4 | [
"Apache-2.0"
] | 1 | 2019-12-02T01:18:10.000Z | 2019-12-02T01:18:10.000Z | // Copyright 2018 Google LLC
// Copyright 2018-present Open Networking Foundation
//
// 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 STRATUM_HAL_LIB_COMMON_ADMIN_UTILS_INTERFACE_H_
#define STRATUM_HAL_LIB_COMMON_ADMIN_UTILS_INTERFACE_H_
#include <string>
#include <memory>
#include <vector>
#include "gnoi/types/types.pb.h"
#include "stratum/glue/status/status.h"
#include "gnoi/system/system.grpc.pb.h"
#include "stratum/glue/integral_types.h"
namespace { // NOLINT
const int ERROR_RETURN_CODE = -1;
}
namespace stratum {
namespace hal {
// Provides interface to call a shell command, and retrieve the results
class AdminServiceShellHelper {
public:
explicit AdminServiceShellHelper(const std::string& command)
: command_(command),
cmd_return_code_(
ERROR_RETURN_CODE) {}
// Runs the command provided in the constructor
// @return true if cmd succeeded, false if failure
virtual bool Execute();
// Getters for the private stdout/stderr vectors
virtual std::vector<std::string> GetStdout();
virtual std::vector<std::string> GetStderr();
// Gets the return code of the executed command
int GetReturnCode();
private:
// Command to be executed (cmdline)
std::string command_;
// Return of the executed command, populated after cmd exits;
// By default is zero
int cmd_return_code_;
std::vector<std::string> cmd_stdout_;
std::vector<std::string> cmd_stderr_;
// Storing the stdout/stderr descriptors after output re-targetting
int stdout_back_up_;
int stderr_back_up_;
// Pipes for stdout/stderr from the child process
int stdout_fd_[2];
int stderr_fd_[2];
// Retargets the streams of the process into the above pipes;
// Closes the terminal descriptors but stores the current ones in the back_up_
// @return false if failed, true otherwise
bool LinkPipesToStreams();
// Restores the stdout/stderr
void UnlinkPipes();
// Child portion after fork()
//
// Link pipes
// Execute command
// Notify on error
void ExecuteChild();
// Parent portion after fork()
//
// Wait for child
// Check exit status
// Retrieve the output
void ExecuteParent();
// Reads everything available on the file descriptor
//
// Will return empty lines as an empty string
// @param pipe_fd File descriptor to read
// @return List of lines without new_line character at the end
std::vector<std::string> FlushPipe(int pipe_fd);
};
// Provides interface to filesystem
class FileSystemHelper {
public:
FileSystemHelper() = default;
virtual ~FileSystemHelper() = default;
virtual bool CheckHashSumFile(const std::string& path,
const std::string& old_hash,
::gnoi::types::HashType_HashMethod method) const;
virtual std::string GetHashSum(std::istream& istream, // NOLINTNEXTKINE
::gnoi::types::HashType_HashMethod method) const;
// Create temporary directory and return it name
// @return Temporary directory name in std:string
virtual std::string CreateTempDir() const;
// Create temporary file and return it name
// @return Temporary file name in std:string
virtual std::string TempFileName(std::string path = std::string()) const;
// Removes a dir from the given path.
// Returns error if the path does not exist
// or the path is a file.
virtual ::util::Status RemoveDir(const std::string& path) const;
virtual ::util::Status RemoveFile(const std::string& path) const;
virtual bool PathExists(const std::string& path) const;
virtual ::util::Status CopyFile(const std::string& src,
const std::string& dst) const;
virtual ::util::Status StringToFile(const std::string& data,
const std::string& file_name,
bool append = false) const;
};
// Wrapper/fabric class for the Admin Service utils;
// To use, retrieve the desired object via Get___Helper
class AdminServiceUtilsInterface {
public:
AdminServiceUtilsInterface() : file_system_helper_(new FileSystemHelper) {}
virtual ~AdminServiceUtilsInterface() = default;
virtual std::shared_ptr<AdminServiceShellHelper>
GetShellHelper(const std::string& command);
// Retrieves time since epoch in ns
virtual uint64_t GetTime();
virtual std::shared_ptr<FileSystemHelper>
GetFileSystemHelper();
// Reboot the system
virtual ::util::Status Reboot();
private:
std::shared_ptr<FileSystemHelper> file_system_helper_;
};
} // namespace hal
} // namespace stratum
#endif // STRATUM_HAL_LIB_COMMON_ADMIN_UTILS_INTERFACE_H_
| 30.904192 | 82 | 0.70994 |
55fd0d385cd4e81ca90273f78552ab9c47b03670 | 22,625 | c | C | src/test/modules/test_csn_xact/test_csn_xact.c | qiuwenhuifx/PolarDB-for-PostgreSQL | 398902a8ba8cc3a89dc581f3d681971e887e7ebd | [
"Apache-2.0"
] | 202 | 2021-10-13T09:21:34.000Z | 2022-03-31T09:52:47.000Z | src/test/modules/test_csn_xact/test_csn_xact.c | qiuwenhuifx/PolarDB-for-PostgreSQL | 398902a8ba8cc3a89dc581f3d681971e887e7ebd | [
"Apache-2.0"
] | 9 | 2021-11-01T09:10:56.000Z | 2022-03-28T14:24:23.000Z | src/test/modules/test_csn_xact/test_csn_xact.c | qiuwenhuifx/PolarDB-for-PostgreSQL | 398902a8ba8cc3a89dc581f3d681971e887e7ebd | [
"Apache-2.0"
] | 47 | 2021-10-21T07:15:26.000Z | 2022-03-29T11:37:15.000Z | #include "postgres.h"
#include "access/heapam.h"
#include "access/hio.h"
#include "access/htup_details.h"
#include "access/multixact.h"
#include "access/transam.h"
#include "access/xact.h"
#include "access/visibilitymap.h"
#include "catalog/pg_am.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "nodes/makefuncs.h"
#include "storage/bufmgr.h"
#include "storage/procarray.h"
#include "utils/guc.h"
#include "utils/rel.h"
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(test_csn_xact_xmin);
PG_FUNCTION_INFO_V1(test_csn_xact_xmax);
PG_FUNCTION_INFO_V1(test_csn_xact_multixact);
Datum
test_csn_xact_xmin(PG_FUNCTION_ARGS)
{
bool commit = PG_GETARG_BOOL(0);
RangeVar *rv;
Relation rel;
Datum values[2];
bool isnull[2];
HeapTuple tup, tup2;
TransactionId xid1, xid2;
int ret;
Buffer buffer;
Buffer vmbuffer = InvalidBuffer;
SnapshotData snapshot1 = {HeapTupleSatisfiesMVCC};
SnapshotData snapshot2 = {HeapTupleSatisfiesMVCC};
SnapshotData snapshot3 = {HeapTupleSatisfiesMVCC};
if (!polar_csn_enable)
elog(ERROR, "test_csn_xact: polar_csn_enable must be on");
/* Connect to SPI manager */
if ((ret = SPI_connect()) < 0)
/* internal error */
elog(ERROR, "test_csn_xact: SPI_connect returned %d", ret);
SPI_execute("DROP TABLE IF EXISTS csn_xact_table_case1", false, 0);
SPI_execute("CREATE TABLE csn_xact_table_case1(i int4)", false, 0);
SPI_finish();
/* Generate a XID */
xid2 = GetNewTransactionId(false);
xid1 = GetNewTransactionId(false);
rv = makeRangeVar(NULL, "csn_xact_table_case1", -1);
rel = heap_openrv(rv, RowExclusiveLock);
values[0] = Int32GetDatum(0);
isnull[0] = false;
values[1] = Int32GetDatum(0);
isnull[1] = false;
tup = heap_form_tuple(RelationGetDescr(rel), &values[0], &isnull[0]);
tup2 = heap_form_tuple(RelationGetDescr(rel), &values[1], &isnull[1]);
/* Fill the header fields, like heap_prepare_insert does */
tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
HeapTupleHeaderSetXmin(tup->t_data, xid1);
HeapTupleHeaderSetCmin(tup->t_data, 1);
HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
tup->t_tableOid = RelationGetRelid(rel);
tup2->t_data->t_infomask &= ~(HEAP_XACT_MASK);
tup2->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
tup2->t_data->t_infomask |= HEAP_XMAX_INVALID;
HeapTupleHeaderSetXmin(tup2->t_data, xid2);
HeapTupleHeaderSetCmin(tup2->t_data, 1);
HeapTupleHeaderSetXmax(tup2->t_data, 0); /* for cleanliness */
tup2->t_tableOid = RelationGetRelid(rel);
/*
* Find buffer to insert this tuple into. If the page is all visible,
* this will also pin the requisite visibility map page.
*/
buffer = RelationGetBufferForTuple(rel, tup->t_len + tup2->t_len,
InvalidBuffer,
0, NULL,
&vmbuffer, NULL);
RelationPutHeapTuple(rel, buffer, tup, false);
RelationPutHeapTuple(rel, buffer, tup2, false);
heap_close(rel, NoLock);
if (PageIsAllVisible(BufferGetPage(buffer)))
{
PageClearAllVisible(BufferGetPage(buffer));
visibilitymap_clear(rel, ItemPointerGetBlockNumber(&(tup->t_self)),
vmbuffer, VISIBILITYMAP_VALID_BITS, NULL);
}
MarkBufferDirty(buffer);
GetSnapshotData(&snapshot1);
if (TransactionIdDidCommit(xid1))
{
elog(WARNING, "test1.1: expected xid1's status is not committed, failed");
}
if (TransactionIdDidAbort(xid1))
{
elog(WARNING, "test 1.2: expected xid1's status is not aborted, failed");
}
if (polar_xact_get_status(xid1) != XID_INPROGRESS)
{
elog(WARNING, "test 1.3: expected xid1's status is in progess, failed");
}
else
{
elog(NOTICE, "test 1.4: expected xid1's status is in progess, success");
}
if (HeapTupleSatisfiesMVCC(tup, &snapshot1, buffer))
{
elog(WARNING, "test 1.4: expected HeapTupleSatisfiesMVCC returns false, failed");
}
if (HeapTupleSatisfiesUpdate(tup, 2, buffer) != HeapTupleInvisible)
{
elog(WARNING, "test 1.5: expected HeapTupleSatisfiesUpdate returns HeapTupleInvisible, failed");
}
if (commit)
{
TransactionIdCommitTree(xid1, 0, NULL);
TransactionIdCommitTree(xid2, 0, NULL);
polar_xact_commit_tree_csn(xid2, 0, NULL, InvalidXLogRecPtr);
GetSnapshotData(&snapshot2);
if (TransactionIdDidCommit(xid1))
{
elog(WARNING, "test 2.1: expected xid1's status is not committed, failed");
}
if (TransactionIdDidAbort(xid1))
{
elog(WARNING, "test 2.2: expected xid1's status is not aborted, failed");
}
if (polar_xact_get_status(xid1) != XID_INPROGRESS)
{
elog(WARNING, "test 2.3: expected xid1's status is in progess, failed");
}
else
{
elog(NOTICE, "test 2.3: expected xid1's status is in progess, success");
}
if (HeapTupleSatisfiesMVCC(tup, &snapshot1, buffer))
{
elog(WARNING, "test 2.4: expected HeapTupleSatisfiesMVCC returns false, failed");
}
if (HeapTupleSatisfiesMVCC(tup, &snapshot2, buffer))
{
elog(WARNING, "test 2.5: expected HeapTupleSatisfiesMVCC returns false, failed");
}
if (HeapTupleSatisfiesUpdate(tup, 2, buffer) != HeapTupleInvisible)
{
elog(WARNING, "test 2.6: expected HeapTupleSatisfiesUpdate's returns HeapTupleInvisible, failed");
}
polar_xact_commit_tree_csn(xid1, 0, NULL, InvalidXLogRecPtr);
GetSnapshotData(&snapshot3);
if (TransactionIdDidAbort(xid1))
{
elog(WARNING, "test 3.1: expected xid1's status is not aborted, failed");
}
if (polar_xact_get_status(xid1) == XID_INPROGRESS)
{
elog(WARNING, "test 3.2: expected xid1's status is not in progess, failed");
}
if (!TransactionIdDidCommit(xid1))
{
elog(WARNING, "test 3.3: expected xid1's status is committed, failed");
}
else
{
elog(NOTICE, "test 3.3: expected xid1's status is committed, success");
}
if (HeapTupleSatisfiesMVCC(tup, &snapshot1, buffer))
{
elog(WARNING, "test 3.4: expected HeapTupleSatisfiesMVCC returns false, failed");
}
if (HeapTupleSatisfiesMVCC(tup, &snapshot2, buffer))
{
elog(WARNING, "test 3.5: expected HeapTupleSatisfiesMVCC returns false, failed");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot3, buffer))
{
elog(WARNING, "test 3.6: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (!HeapTupleSatisfiesMVCC(tup2, &snapshot3, buffer))
{
elog(WARNING, "test 3.7: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot3, buffer))
{
elog(WARNING, "test 3.8: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (HeapTupleSatisfiesUpdate(tup, 2, buffer) != HeapTupleMayBeUpdated)
{
elog(WARNING, "test 3.9: expected HeapTupleSatisfiesUpdate's result is HeapTupleMayBeUpdated, failed");
}
}
else
{
TransactionIdAbortTree(xid1, 0, NULL);
GetSnapshotData(&snapshot2);
if (TransactionIdDidCommit(xid1))
{
elog(WARNING, "test 4.1: expected xid1's status is not committed, failed");
}
if (polar_xact_get_status(xid1) == XID_INPROGRESS)
{
elog(WARNING, "test 4.2: expected xid1's status is not in progess, failed");
}
if (!TransactionIdDidAbort(xid1))
{
elog(WARNING, "test 4.3: expected xid1's status is not aborted, failed");
}
else
{
elog(NOTICE, "test 4.3: expected xid1's status is aborted, success");
}
if (HeapTupleSatisfiesMVCC(tup, &snapshot1, buffer))
{
elog(WARNING, "test 4.4: expected HeapTupleSatisfiesMVCC returns false, failed");
}
if (HeapTupleSatisfiesMVCC(tup, &snapshot2, buffer))
{
elog(WARNING, "test 4.5: expected HeapTupleSatisfiesMVCC returns false, failed");
}
if (HeapTupleSatisfiesUpdate(tup, 2, buffer) != HeapTupleInvisible)
{
elog(WARNING, "test 4.6: expected HeapTupleSatisfiesUpdate's result is HeapTupleInvisible, failed");
}
}
UnlockReleaseBuffer(buffer);
heap_freetuple(tup);
heap_freetuple(tup2);
if (vmbuffer != InvalidBuffer)
ReleaseBuffer(vmbuffer);
/* Connect to SPI manager */
if ((ret = SPI_connect()) < 0)
/* internal error */
elog(ERROR, "test_csn_xact: SPI_connect returned %d", ret);
SPI_execute("DROP TABLE csn_xact_table_case1;", false, 0);
SPI_finish();
PG_RETURN_VOID();
}
Datum
test_csn_xact_xmax(PG_FUNCTION_ARGS)
{
bool commit = PG_GETARG_BOOL(0);
RangeVar *rv;
Relation rel;
Datum values[2];
bool isnull[2];
HeapTuple tup, tup2;
TransactionId xid1, xid2;
int ret;
Buffer buffer;
Buffer vmbuffer = InvalidBuffer;
SnapshotData snapshot1 = {HeapTupleSatisfiesMVCC};
SnapshotData snapshot2 = {HeapTupleSatisfiesMVCC};
SnapshotData snapshot3 = {HeapTupleSatisfiesMVCC};
if (!polar_csn_enable)
elog(ERROR, "test_csn_xact: polar_csn_enable must be on");
/* Connect to SPI manager */
if ((ret = SPI_connect()) < 0)
/* internal error */
elog(ERROR, "test_csn_xact: SPI_connect returned %d", ret);
SPI_execute("DROP TABLE IF EXISTS csn_xact_table_case2", false, 0);
SPI_execute("CREATE TABLE csn_xact_table_case2(i int4)", false, 0);
SPI_finish();
/* Generate a XID */
xid2 = GetNewTransactionId(false);
xid1 = GetNewTransactionId(false);
rv = makeRangeVar(NULL, "csn_xact_table_case2", -1);
rel = heap_openrv(rv, RowExclusiveLock);
values[0] = Int32GetDatum(0);
isnull[0] = false;
values[1] = Int32GetDatum(0);
isnull[1] = false;
tup = heap_form_tuple(RelationGetDescr(rel), &values[0], &isnull[0]);
tup2 = heap_form_tuple(RelationGetDescr(rel), &values[1], &isnull[1]);
/* Fill the header fields, like heap_prepare_insert does */
tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
tup->t_data->t_infomask |= HEAP_XMIN_FROZEN;
HeapTupleHeaderSetXmin(tup->t_data, FrozenTransactionId);
HeapTupleHeaderSetCmin(tup->t_data, 1);
HeapTupleHeaderSetXmax(tup->t_data, xid1);
tup->t_tableOid = RelationGetRelid(rel);
tup2->t_data->t_infomask &= ~(HEAP_XACT_MASK);
tup2->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
tup2->t_data->t_infomask |= HEAP_XMIN_FROZEN;
HeapTupleHeaderSetXmin(tup2->t_data, FrozenTransactionId);
HeapTupleHeaderSetCmin(tup2->t_data, 1);
HeapTupleHeaderSetXmax(tup2->t_data, xid1);
tup2->t_tableOid = RelationGetRelid(rel);
/*
* Find buffer to insert this tuple into. If the page is all visible,
* this will also pin the requisite visibility map page.
*/
buffer = RelationGetBufferForTuple(rel, tup->t_len + tup2->t_len,
InvalidBuffer,
0, NULL,
&vmbuffer, NULL);
RelationPutHeapTuple(rel, buffer, tup, false);
RelationPutHeapTuple(rel, buffer, tup2, false);
heap_close(rel, NoLock);
if (PageIsAllVisible(BufferGetPage(buffer)))
{
PageClearAllVisible(BufferGetPage(buffer));
visibilitymap_clear(rel, ItemPointerGetBlockNumber(&(tup->t_self)),
vmbuffer, VISIBILITYMAP_VALID_BITS, NULL);
}
MarkBufferDirty(buffer);
GetSnapshotData(&snapshot1);
if (TransactionIdDidCommit(xid1))
{
elog(WARNING, "test 1.1: expected xid1's status is not committed, failed");
}
if (TransactionIdDidAbort(xid1))
{
elog(WARNING, "test 1.2: expected xid1's status is not aborted, failed");
}
if (polar_xact_get_status(xid1) != XID_INPROGRESS)
{
elog(WARNING, "test 1.3: expected xid1's status is in progress, failed");
}
else
{
elog(NOTICE, "test 1.3: expected xid1's status is in progress, success");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot1, buffer))
{
elog(WARNING, "test 1.4: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (HeapTupleSatisfiesUpdate(tup, 2, buffer) != HeapTupleBeingUpdated)
{
elog(WARNING, "test 1.5: expected HeapTupleSatisfiesUpdate returns HeapTupleBeingUpdated, failed");
}
if (commit)
{
TransactionIdCommitTree(xid1, 0, NULL);
TransactionIdCommitTree(xid2, 0, NULL);
polar_xact_commit_tree_csn(xid2, 0, NULL, InvalidXLogRecPtr);
GetSnapshotData(&snapshot2);
if (TransactionIdDidCommit(xid1))
{
elog(WARNING, "test 2.1: expected xid1's status is not committed, failed");
}
if (TransactionIdDidAbort(xid1))
{
elog(WARNING, "test 2.2: expected xid1's status is not aborted, failed");
}
if (polar_xact_get_status(xid1) != XID_INPROGRESS)
{
elog(WARNING, "test 2.3: expected xid1's status is in progess, failed");
}
else
{
elog(NOTICE, "test 2.4: expected xid1's status is in progess, success");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot1, buffer))
{
elog(WARNING, "test 2.5: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot2, buffer))
{
elog(WARNING, "test 2.6: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (HeapTupleSatisfiesUpdate(tup, 2, buffer) != HeapTupleBeingUpdated)
{
elog(WARNING, "test 2.7: expected HeapTupleSatisfiesUpdate's returns HeapTupleBeingUpdated, failed");
}
polar_xact_commit_tree_csn(xid1, 0, NULL, InvalidXLogRecPtr);
GetSnapshotData(&snapshot3);
if (TransactionIdDidAbort(xid1))
{
elog(WARNING, "test 3.1: expected xid1's status is not aborted, failed");
}
if (polar_xact_get_status(xid1) == XID_INPROGRESS)
{
elog(WARNING, "test 3.2: expected xid1's status is not in progess, failed");
}
if (!TransactionIdDidCommit(xid1))
{
elog(WARNING, "test 3.3: expected xid1's status is committed, failed");
}
else
{
elog(NOTICE, "test 3.3: expected xid1's status is committed, success");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot1, buffer))
{
elog(WARNING, "test 3.4: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot2, buffer))
{
elog(WARNING, "test 3.5: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (HeapTupleSatisfiesMVCC(tup, &snapshot3, buffer))
{
elog(WARNING, "test 3.6: expected HeapTupleSatisfiesMVCC returns false, failed");
}
if (HeapTupleSatisfiesMVCC(tup2, &snapshot3, buffer))
{
elog(WARNING, "test 3.7: expected HeapTupleSatisfiesMVCC returns false, failed");
}
if (HeapTupleSatisfiesMVCC(tup, &snapshot3, buffer))
{
elog(WARNING, "test 3.8: expected HeapTupleSatisfiesMVCC returns false, failed");
}
if (HeapTupleSatisfiesUpdate(tup, 2, buffer) != HeapTupleUpdated)
{
elog(WARNING, "test 3.9: expected HeapTupleSatisfiesUpdate's result is HeapTupleUpdated, failed");
}
}
else
{
TransactionIdAbortTree(xid1, 0, NULL);
GetSnapshotData(&snapshot2);
snapshot2.xmax = xid1;
if (TransactionIdDidCommit(xid1))
{
elog(WARNING, "test 4.1: expected xid1's status is not committed, failed");
}
if (polar_xact_get_status(xid1) == XID_INPROGRESS)
{
elog(WARNING, "test 4.2: expected xid1's status is not in progess, failed");
}
if (!TransactionIdDidAbort(xid1))
{
elog(WARNING, "test 4.3: expected xid1's status is not aborted, failed");
}
else
{
elog(NOTICE, "test 4.3: expected xid1's status is aborted, success");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot1, buffer))
{
elog(WARNING, "test 4.4: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot2, buffer))
{
elog(WARNING, "test 4.5: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (HeapTupleSatisfiesUpdate(tup, 2, buffer) != HeapTupleMayBeUpdated)
{
elog(WARNING, "test 4.6: expected HeapTupleSatisfiesUpdate's result is HeapTupleMayBeUpdated, failed");
}
}
UnlockReleaseBuffer(buffer);
heap_freetuple(tup);
heap_freetuple(tup2);
if (vmbuffer != InvalidBuffer)
ReleaseBuffer(vmbuffer);
/* Connect to SPI manager */
if ((ret = SPI_connect()) < 0)
/* internal error */
elog(ERROR, "test_csn_xact: SPI_connect returned %d", ret);
SPI_execute("DROP TABLE csn_xact_table_case2;", false, 0);
SPI_finish();
PG_RETURN_VOID();
}
Datum
test_csn_xact_multixact(PG_FUNCTION_ARGS)
{
bool commit = PG_GETARG_BOOL(0);
RangeVar *rv;
Relation rel;
Datum values[1];
bool isnull[1];
HeapTuple tup;
TransactionId xid1;
MultiXactId new_xmax;
int ret;
Buffer buffer;
Buffer vmbuffer = InvalidBuffer;
SnapshotData snapshot1 = {HeapTupleSatisfiesMVCC};
SnapshotData snapshot2 = {HeapTupleSatisfiesMVCC};
SnapshotData snapshot3 = {HeapTupleSatisfiesMVCC};
MultiXactStatus status1, status2;
if (!polar_csn_enable)
elog(ERROR, "test_csn_xact: polar_csn_enable must be on");
/* Connect to SPI manager */
if ((ret = SPI_connect()) < 0)
/* internal error */
elog(ERROR, "test_csn_xact: SPI_connect returned %d", ret);
SPI_execute("DROP TABLE IF EXISTS csn_xact_table_case3", false, 0);
SPI_execute("CREATE TABLE csn_xact_table_case3(i int4)", false, 0);
SPI_finish();
/* Generate a XID */
xid1 = GetNewTransactionId(false);
rv = makeRangeVar(NULL, "csn_xact_table_case3", -1);
rel = heap_openrv(rv, RowExclusiveLock);
values[0] = Int32GetDatum(0);
isnull[0] = false;
tup = heap_form_tuple(RelationGetDescr(rel), values, isnull);
status1 = MultiXactStatusNoKeyUpdate;
status2 = MultiXactStatusForKeyShare,
MultiXactIdSetOldestMember();
new_xmax = MultiXactIdCreate(xid1, status1, FrozenTransactionId, status2);
/* Fill the header fields, like heap_prepare_insert does */
tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
tup->t_data->t_infomask |= HEAP_XMIN_FROZEN;
tup->t_data->t_infomask |= HEAP_XMAX_IS_MULTI;
tup->t_data->t_infomask |= HEAP_XMAX_EXCL_LOCK;
HeapTupleHeaderSetXmin(tup->t_data, FrozenTransactionId);
HeapTupleHeaderSetCmin(tup->t_data, 1);
HeapTupleHeaderSetXmax(tup->t_data, new_xmax);
tup->t_tableOid = RelationGetRelid(rel);
/*
* Find buffer to insert this tuple into. If the page is all visible,
* this will also pin the requisite visibility map page.
*/
buffer = RelationGetBufferForTuple(rel, tup->t_len,
InvalidBuffer,
0, NULL,
&vmbuffer, NULL);
RelationPutHeapTuple(rel, buffer, tup, false);
heap_close(rel, NoLock);
if (PageIsAllVisible(BufferGetPage(buffer)))
{
PageClearAllVisible(BufferGetPage(buffer));
visibilitymap_clear(rel, ItemPointerGetBlockNumber(&(tup->t_self)),
vmbuffer, VISIBILITYMAP_VALID_BITS, NULL);
}
MarkBufferDirty(buffer);
GetSnapshotData(&snapshot1);
if (TransactionIdDidCommit(xid1))
{
elog(WARNING, "test 1.1: expected xid1's status is not committed, failed");
}
if (TransactionIdDidAbort(xid1))
{
elog(WARNING, "test 1.2: expected xid1's status is not aborted, failed");
}
if (polar_xact_get_status(xid1) != XID_INPROGRESS)
{
elog(WARNING, "test 1.3: expected xid1's status is in progress, failed");
}
else
{
elog(NOTICE, "test 1.3: expected xid1's status is in progress, success");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot1, buffer))
{
elog(WARNING, "test 1.4: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (HeapTupleSatisfiesUpdate(tup, 2, buffer) != HeapTupleBeingUpdated)
{
elog(WARNING, "test 1.5: expected HeapTupleSatisfiesUpdate returns HeapTupleBeingUpdated, failed");
}
if (commit)
{
TransactionIdCommitTree(xid1, 0, NULL);
GetSnapshotData(&snapshot2);
if (TransactionIdDidCommit(xid1))
{
elog(WARNING, "test 2.1: expected xid1's status is not committed, failed");
}
if (TransactionIdDidAbort(xid1))
{
elog(WARNING, "test 2.2: expected xid1's status is not aborted, failed");
}
if (polar_xact_get_status(xid1) != XID_INPROGRESS)
{
elog(WARNING, "test 2.3: expected xid1's status is in progess, failed");
}
else
{
elog(NOTICE, "test 2.3: expected xid1's status is in progess, success");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot1, buffer))
{
elog(WARNING, "test 2.4: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot2, buffer))
{
elog(WARNING, "test 2.5: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (HeapTupleSatisfiesUpdate(tup, 2, buffer) != HeapTupleBeingUpdated)
{
elog(WARNING, "test 2.6: expected HeapTupleSatisfiesUpdate's returns HeapTupleBeingUpdated, failed");
}
polar_xact_commit_tree_csn(xid1, 0, NULL, InvalidXLogRecPtr);
GetSnapshotData(&snapshot3);
if (TransactionIdDidAbort(xid1))
{
elog(WARNING, "test 3.1: expected xid1's status is not aborted, failed");
}
if (polar_xact_get_status(xid1) == XID_INPROGRESS)
{
elog(WARNING, "test 3.2: expected xid1's status is not in progess, failed");
}
if (!TransactionIdDidCommit(xid1))
{
elog(WARNING, "test 3.3: expected xid1's status is committed, failed");
}
else
{
elog(NOTICE, "test 3.3: expected xid1's status is committed, success");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot1, buffer))
{
elog(WARNING, "test 3.4: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot2, buffer))
{
elog(WARNING, "test 3.5: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (HeapTupleSatisfiesMVCC(tup, &snapshot3, buffer))
{
elog(WARNING, "test 3.6: expected HeapTupleSatisfiesMVCC returns false, failed");
}
if (HeapTupleSatisfiesMVCC(tup, &snapshot3, buffer))
{
elog(WARNING, "test 3.7: expected HeapTupleSatisfiesMVCC returns false, failed");
}
if (HeapTupleSatisfiesUpdate(tup, 2, buffer) != HeapTupleUpdated)
{
elog(WARNING, "test 3.8: expected HeapTupleSatisfiesUpdate's result is HeapTupleUpdated, failed");
}
}
else
{
TransactionIdAbortTree(xid1, 0, NULL);
GetSnapshotData(&snapshot2);
if (TransactionIdDidCommit(xid1))
{
elog(WARNING, "test 4.1: expected xid1's status is not committed, failed");
}
if (polar_xact_get_status(xid1) == XID_INPROGRESS)
{
elog(WARNING, "test 4.2: expected xid1's status is not in progess, failed");
}
if (!TransactionIdDidAbort(xid1))
{
elog(WARNING, "test 4.3: expected xid1's status is not aborted, failed");
}
else
{
elog(NOTICE, "test 4.3: expected xid1's status is aborted, success");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot1, buffer))
{
elog(WARNING, "test 4.4: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (!HeapTupleSatisfiesMVCC(tup, &snapshot2, buffer))
{
elog(WARNING, "test 4.5: expected HeapTupleSatisfiesMVCC returns true, failed");
}
if (HeapTupleSatisfiesUpdate(tup, 2, buffer) != HeapTupleMayBeUpdated)
{
elog(WARNING, "test 4.7: expected HeapTupleSatisfiesUpdate's result is HeapTupleMayBeUpdated, failed");
}
}
UnlockReleaseBuffer(buffer);
heap_freetuple(tup);
if (vmbuffer != InvalidBuffer)
ReleaseBuffer(vmbuffer);
/* Connect to SPI manager */
if ((ret = SPI_connect()) < 0)
/* internal error */
elog(ERROR, "test_csn_xact: SPI_connect returned %d", ret);
SPI_execute("DROP TABLE csn_xact_table_case3;", false, 0);
SPI_finish();
PG_RETURN_VOID();
}
| 27.79484 | 106 | 0.717834 |
361daa8385efe3875f53e8a590fcdc4834e15cac | 1,240 | h | C | include/gigraph/node_rttr_gen.h | xzrunner/gigraph | 628b73a9b4ee226642672065818a5e8f5e3cf9fb | [
"MIT"
] | null | null | null | include/gigraph/node_rttr_gen.h | xzrunner/gigraph | 628b73a9b4ee226642672065818a5e8f5e3cf9fb | [
"MIT"
] | null | null | null | include/gigraph/node_rttr_gen.h | xzrunner/gigraph | 628b73a9b4ee226642672065818a5e8f5e3cf9fb | [
"MIT"
] | null | null | null | #define XSTR(s) STR(s)
#define STR(s) #s
#ifndef PARM_NODE_TYPE
#error "You must define PARM_NODE_TYPE macro before include this file"
#endif
#ifndef PARM_NODE_NAME
#error "You must define PARM_NODE_NAME macro before include this file"
#endif
#ifndef PARM_FILEPATH_PARM
#ifdef PARM_NODE_GROUP
#define PARM_FILEPATH_PARM gigraph/component/##PARM_NODE_GROUP##/##PARM_NODE_TYPE##.parm.h
#else
#define PARM_FILEPATH_PARM gigraph/component/##PARM_NODE_TYPE##.parm.h
#endif // PARM_NODE_GROUP
#endif
#define RTTR_NAME gigraph::##PARM_NODE_NAME
#ifdef PARM_NODE_GROUP
rttr::registration::class_<gigraph::comp::PARM_NODE_GROUP::PARM_NODE_TYPE>(XSTR(RTTR_NAME))
#else
rttr::registration::class_<gigraph::comp::PARM_NODE_TYPE>(XSTR(RTTR_NAME))
#endif // PARM_NODE_GROUP
.constructor<>()
#ifndef NO_PARM_FILEPATH
#define PARM_FILEPATH XSTR(PARM_FILEPATH_PARM)
#endif // NO_PARM_FILEPATH
#ifdef PARM_NODE_GROUP
#define PARM_NODE_CLASS gigraph::comp::##PARM_NODE_GROUP::##PARM_NODE_TYPE
#else
#define PARM_NODE_CLASS gigraph::comp::##PARM_NODE_TYPE
#endif // PARM_NODE_GROUP
#include <dag/rttr_prop_gen.h>
#undef PARM_FILEPATH
#undef PARM_NODE_CLASS
;
//#undef PARM_NODE_GROUP
#undef PARM_NODE_NAME
#undef PARM_NODE_TYPE
#undef PARM_FILEPATH_PARM
| 27.555556 | 91 | 0.808065 |
1d1ed122d35859ede072775b03ab25b9623a6c15 | 1,286 | h | C | apps/test_app_io/fsw/platform_inc/test_app_io_platform_cfg.h | ammarrm/cFS_MSTAR | f7d59eec4a445bb8572d01a580c043ec7a33df44 | [
"Apache-2.0"
] | null | null | null | apps/test_app_io/fsw/platform_inc/test_app_io_platform_cfg.h | ammarrm/cFS_MSTAR | f7d59eec4a445bb8572d01a580c043ec7a33df44 | [
"Apache-2.0"
] | null | null | null | apps/test_app_io/fsw/platform_inc/test_app_io_platform_cfg.h | ammarrm/cFS_MSTAR | f7d59eec4a445bb8572d01a580c043ec7a33df44 | [
"Apache-2.0"
] | 1 | 2021-04-23T04:26:08.000Z | 2021-04-23T04:26:08.000Z | /*=======================================================================================
** File Name: test_app_io_platform_cfg.h
**
** Title: Platform Configuration Header File for TEST_APP_IO Application
**
** $Author: Darren Chiu
** $Revision: 1.1 $
** $Date: 2020-12-31
**
** Purpose: This header file contains declartions and definitions of all TEST_APP_IO's
** platform-specific configurations.
**
** Modification History:
** Date | Author | Description
** ---------------------------
** 2020-12-31 | Darren Chiu | Build #: Code Started
**
**=====================================================================================*/
#ifndef _TEST_APP_IO_PLATFORM_CFG_H_
#define _TEST_APP_IO_PLATFORM_CFG_H_
/*
** test_app_io Platform Configuration Parameter Definitions
*/
#define TEST_APP_IO_SCH_PIPE_DEPTH 2
#define TEST_APP_IO_CMD_PIPE_DEPTH 10
#define TEST_APP_IO_TLM_PIPE_DEPTH 10
/* TODO: Add more platform configuration parameter definitions here, if necessary. */
#endif /* _TEST_APP_IO_PLATFORM_CFG_H_ */
/*=======================================================================================
** End of file test_app_io_platform_cfg.h
**=====================================================================================*/
| 33.842105 | 89 | 0.514774 |
8a97e089632675c3c497d993e0a999a9dc417765 | 992 | h | C | algorithms/medium/1338. Reduce Array Size to The Half.h | MultivacX/letcode2020 | f86289f8718237303918a7705ae31625a12b68f6 | [
"MIT"
] | null | null | null | algorithms/medium/1338. Reduce Array Size to The Half.h | MultivacX/letcode2020 | f86289f8718237303918a7705ae31625a12b68f6 | [
"MIT"
] | null | null | null | algorithms/medium/1338. Reduce Array Size to The Half.h | MultivacX/letcode2020 | f86289f8718237303918a7705ae31625a12b68f6 | [
"MIT"
] | null | null | null | // 1338. Reduce Array Size to The Half
// Runtime: 256 ms, faster than 54.62% of C++ online submissions for Reduce Array Size to The Half.
// Memory Usage: 34.3 MB, less than 100.00% of C++ online submissions for Reduce Array Size to The Half.
class Solution {
public:
int minSetSize(vector<int>& arr) {
// {integer, cnt}
unordered_map<int, int> m;
for (int a : arr) ++m[a];
// {cnt, kinds of integers}
map<int, int> n;
for (auto it : m) ++n[it.second];
int ans = 0;
int removed = 0;
int target = arr.size() / 2;
for (auto it = n.rbegin(); it != n.rend() && removed < target; ++it) {
// removed + k * it->first >= target
// 1 <= k <= it->second
float r = floor((target - removed) / (float)it->first);
int k = min(max(1, (int)r), it->second);
ans += k;
removed += k * it->first;
}
return ans;
}
}; | 33.066667 | 104 | 0.50504 |
def8d44ecbb6b8d5b4e4bbe85c4f8b5f88bcd25a | 1,560 | h | C | arrows/ocv/feature_set.h | willdunklin/kwiver | 7642af7cc9c8727f85b322331164569665bae224 | [
"BSD-3-Clause"
] | null | null | null | arrows/ocv/feature_set.h | willdunklin/kwiver | 7642af7cc9c8727f85b322331164569665bae224 | [
"BSD-3-Clause"
] | null | null | null | arrows/ocv/feature_set.h | willdunklin/kwiver | 7642af7cc9c8727f85b322331164569665bae224 | [
"BSD-3-Clause"
] | null | null | null | // This file is part of KWIVER, and is distributed under the
// OSI-approved BSD 3-Clause License. See top-level LICENSE file or
// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.
/// \file
/// \brief OCV feature_set interface
#ifndef KWIVER_ARROWS_OCV_FEATURE_SET_H_
#define KWIVER_ARROWS_OCV_FEATURE_SET_H_
#include <vital/vital_config.h>
#include <arrows/ocv/kwiver_algo_ocv_export.h>
#include <opencv2/features2d/features2d.hpp>
#include <vital/types/feature_set.h>
namespace kwiver {
namespace arrows {
namespace ocv {
/// A concrete feature set that wraps OpenCV KeyPoints
class KWIVER_ALGO_OCV_EXPORT feature_set
: public vital::feature_set
{
public:
/// Default Constructor
feature_set() {}
/// Constructor from a vector of cv::KeyPoints
explicit feature_set(const std::vector<cv::KeyPoint>& features)
: data_(features) {}
/// Return the number of feature in the set
virtual size_t size() const { return data_.size(); }
/// Return a vector of feature shared pointers
virtual std::vector<vital::feature_sptr> features() const;
/// Return the underlying OpenCV vector of cv::KeyPoints
const std::vector<cv::KeyPoint>& ocv_keypoints() const { return data_; }
protected:
/// The vector of KeyPoints
std::vector<cv::KeyPoint> data_;
};
/// Convert any feature set to a vector of OpenCV cv::KeyPoints
KWIVER_ALGO_OCV_EXPORT std::vector<cv::KeyPoint>
features_to_ocv_keypoints(const vital::feature_set& features);
} // end namespace ocv
} // end namespace arrows
} // end namespace kwiver
#endif
| 26.896552 | 74 | 0.749359 |
7200766c5b182802137ee41b29e66ee33d1f97cc | 3,433 | h | C | src/SignalFlowTableEditor/GridDlg.h | lefevre-fraser/openmeta-mms | 08f3115e76498df1f8d70641d71f5c52cab4ce5f | [
"MIT"
] | null | null | null | src/SignalFlowTableEditor/GridDlg.h | lefevre-fraser/openmeta-mms | 08f3115e76498df1f8d70641d71f5c52cab4ce5f | [
"MIT"
] | null | null | null | src/SignalFlowTableEditor/GridDlg.h | lefevre-fraser/openmeta-mms | 08f3115e76498df1f8d70641d71f5c52cab4ce5f | [
"MIT"
] | null | null | null | #if !defined(AFX_GRIDDLG_H__CEF65935_5737_49A0_AF82_8854513FA90F__INCLUDED_)
#define AFX_GRIDDLG_H__CEF65935_5737_49A0_AF82_8854513FA90F__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// GridDlg.h : header file
//
#include "resource.h"
#include "GridCtrl_src/GridCtrl.h"
#include "ComHelp.h"
#include "GMECOM.h"
#include "Mga.h"
/////////////////////////////////////////////////////////////////////////////
// CGridDlg dialog
class CGridDlg : public CDialog
{
// Construction
public:
CGridDlg(CWnd* pParent = NULL); // standard constructor
CGridDlg(IMgaFCOs* selectedObjs, CWnd* pParent = NULL);
void SetProject(IMgaProject *proj) {m_Project = proj;}
void SetFilter(IMgaFilter *filter);
// Dialog Data
//{{AFX_DATA(CGridDlg)
enum { IDD = IDD_GRIDDLG };
CButton m_btnImport;
CStatic m_stcFilters;
CStatic m_stcSelect;
CButton m_btnAllTypes;
CButton m_btnAllKinds;
CStatic m_stcType;
CStatic m_stcKind;
CStatic m_stcHelp;
CButton m_btnDisp;
CButton m_btnSet;
CButton m_btnRef;
CButton m_btnModel;
CButton m_btnCon;
CButton m_btnAtom;
CListBox m_lstKind;
CButton m_btnExport;
CButton m_btnCANCEL;
CButton m_btnOK;
BOOL m_chkAllKinds;
BOOL m_chkAllTypes;
BOOL m_chkAtom;
BOOL m_chkCon;
BOOL m_chkModel;
BOOL m_chkRef;
BOOL m_chkSet;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CGridDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
//void Trace(LPCTSTR szFmt, ...);
// Implementation
protected:
CGridCtrl m_Grid;
CComPtr<IMgaProject> m_Project;
CComPtr<IMgaFCOs> m_FCOs;
CComPtr<IMgaFilter> m_Filter;
CComPtr<IMgaMetaFolder> m_rootMetaFolder;
CSize m_OldSize;
void GetMetaObjectNames(IMgaMetaBase *metaBase);
void BuildExtendedName(IMgaFCO *named, CString &extName);
void BuildExtendedName(IMgaFolder *named, CString &extName);
void MoveWndDown(CWnd *wnd, int offset);
BOOL GetMultiLine(CComPtr<IMgaMetaAttribute> p_Meta);
void InitGrid();
HRESULT ShowItemsRecursively();
// Generated message map functions
//{{AFX_MSG(CGridDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnRecursivelyShowItems();
afx_msg void OnButtonDisplay();
afx_msg void OnCheckAllKinds();
afx_msg void OnChkAllTypes();
afx_msg void OnChkAtom();
afx_msg void OnChkCon();
afx_msg void OnChkModel();
afx_msg void OnChkRef();
afx_msg void OnChkSet();
//}}AFX_MSG
afx_msg void OnGridDblClick(NMHDR *pNotifyStruct, LRESULT* pResult);
afx_msg void OnGridClick(NMHDR *pNotifyStruct, LRESULT* pResult);
afx_msg void OnGridRClick(NMHDR *pNotifyStruct, LRESULT* pResult);
afx_msg void OnGridStartEdit(NMHDR *pNotifyStruct, LRESULT* pResult);
afx_msg void OnGridEndEdit(NMHDR *pNotifyStruct, LRESULT* pResult);
afx_msg void OnGridStartSelChange(NMHDR *pNotifyStruct, LRESULT* pResult);
afx_msg void OnGridEndSelChange(NMHDR *pNotifyStruct, LRESULT* pResult);
afx_msg void OnGridBeginDrag(NMHDR *pNotifyStruct, LRESULT* pResult);
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_GRIDDLG_H__CEF65935_5737_49A0_AF82_8854513FA90F__INCLUDED_)
| 27.910569 | 98 | 0.7291 |
7244a80f2e0c92d990961c0a6b69110e65898d90 | 7,491 | h | C | src/net/quic/quic_transport_client.h | kiss2u/naiveproxy | 724caf7f3c8bc2d2d0dcdf090e97429a3c88a85a | [
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | src/net/quic/quic_transport_client.h | kiss2u/naiveproxy | 724caf7f3c8bc2d2d0dcdf090e97429a3c88a85a | [
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | src/net/quic/quic_transport_client.h | kiss2u/naiveproxy | 724caf7f3c8bc2d2d0dcdf090e97429a3c88a85a | [
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_QUIC_QUIC_TRANSPORT_CLIENT_H_
#define NET_QUIC_QUIC_TRANSPORT_CLIENT_H_
#include "base/memory/weak_ptr.h"
#include "net/base/network_isolation_key.h"
#include "net/dns/host_resolver.h"
#include "net/log/net_log_with_source.h"
#include "net/proxy_resolution/proxy_info.h"
#include "net/quic/quic_chromium_packet_reader.h"
#include "net/quic/quic_chromium_packet_writer.h"
#include "net/quic/quic_context.h"
#include "net/quic/quic_event_logger.h"
#include "net/quic/quic_transport_error.h"
#include "net/quic/web_transport_client.h"
#include "net/socket/client_socket_factory.h"
#include "net/third_party/quiche/src/quic/core/crypto/quic_crypto_client_config.h"
#include "net/third_party/quiche/src/quic/core/quic_config.h"
#include "net/third_party/quiche/src/quic/core/quic_versions.h"
#include "net/third_party/quiche/src/quic/core/web_transport_interface.h"
#include "net/third_party/quiche/src/quic/quic_transport/quic_transport_client_session.h"
#include "net/third_party/quiche/src/quic/quic_transport/web_transport_fingerprint_proof_verifier.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace net {
class ProxyResolutionRequest;
class QuicChromiumAlarmFactory;
class URLRequestContext;
// QuicTransportClient is the top-level API for QuicTransport in //net.
class NET_EXPORT QuicTransportClient
: public WebTransportClient,
public quic::WebTransportVisitor,
public QuicChromiumPacketReader::Visitor,
public QuicChromiumPacketWriter::Delegate,
public quic::QuicSession::Visitor {
public:
// QUIC protocol versions that are used in the origin trial.
static quic::ParsedQuicVersionVector
QuicVersionsForWebTransportOriginTrial() {
return quic::ParsedQuicVersionVector{
quic::ParsedQuicVersion::Draft29(), // Enabled in M85
};
}
// |visitor| and |context| must outlive this object.
QuicTransportClient(const GURL& url,
const url::Origin& origin,
WebTransportClientVisitor* visitor,
const NetworkIsolationKey& isolation_key,
URLRequestContext* context,
const WebTransportParameters& parameters);
~QuicTransportClient() override;
WebTransportState state() const { return state_; }
const QuicTransportError& error() const override;
// Connect() is an asynchronous operation. Once the operation is finished,
// OnConnected() or OnConnectionFailed() is called on the Visitor.
void Connect() override;
quic::WebTransportSession* session() override;
quic::QuicTransportClientSession* quic_session();
// QuicTransportClientSession::ClientVisitor methods.
void OnSessionReady() override;
void OnIncomingBidirectionalStreamAvailable() override;
void OnIncomingUnidirectionalStreamAvailable() override;
void OnDatagramReceived(absl::string_view datagram) override;
void OnCanCreateNewOutgoingBidirectionalStream() override;
void OnCanCreateNewOutgoingUnidirectionalStream() override;
// QuicChromiumPacketReader::Visitor methods.
bool OnReadError(int result, const DatagramClientSocket* socket) override;
bool OnPacket(const quic::QuicReceivedPacket& packet,
const quic::QuicSocketAddress& local_address,
const quic::QuicSocketAddress& peer_address) override;
// QuicChromiumPacketWriter::Delegate methods.
int HandleWriteError(int error_code,
scoped_refptr<QuicChromiumPacketWriter::ReusableIOBuffer>
last_packet) override;
void OnWriteError(int error_code) override;
void OnWriteUnblocked() override;
// QuicSession::Visitor methods.
void OnConnectionClosed(quic::QuicConnectionId server_connection_id,
quic::QuicErrorCode error,
const std::string& error_details,
quic::ConnectionCloseSource source) override;
void OnWriteBlocked(
quic::QuicBlockedWriterInterface* /*blocked_writer*/) override {}
void OnRstStreamReceived(const quic::QuicRstStreamFrame& /*frame*/) override {
}
void OnStopSendingReceived(
const quic::QuicStopSendingFrame& /*frame*/) override {}
void OnNewConnectionIdSent(
const quic::QuicConnectionId& /*server_connection_id*/,
const quic::QuicConnectionId& /*new_connecition_id*/) override {}
void OnConnectionIdRetired(
const quic::QuicConnectionId& /*server_connection_id*/) override {}
private:
// State of the connection establishment process.
//
// These values are logged to UMA. Entries should not be renumbered and
// numeric values should never be reused. Please keep in sync with
// "QuicTransportClientConnectState" in
// src/tools/metrics/histograms/enums.xml.
enum ConnectState {
CONNECT_STATE_NONE,
CONNECT_STATE_INIT,
CONNECT_STATE_CHECK_PROXY,
CONNECT_STATE_CHECK_PROXY_COMPLETE,
CONNECT_STATE_RESOLVE_HOST,
CONNECT_STATE_RESOLVE_HOST_COMPLETE,
CONNECT_STATE_CONNECT,
CONNECT_STATE_CONFIRM_CONNECTION,
CONNECT_STATE_NUM_STATES,
};
class DatagramObserverProxy : public quic::QuicDatagramQueue::Observer {
public:
explicit DatagramObserverProxy(QuicTransportClient* client)
: client_(client) {}
void OnDatagramProcessed(
absl::optional<quic::MessageStatus> status) override;
private:
QuicTransportClient* client_;
};
// DoLoop processing the Connect() call.
void DoLoop(int rv);
// Verifies the basic preconditions for setting up the connection.
int DoInit();
// Verifies that there is no mandatory proxy configured for the specified URL.
int DoCheckProxy();
int DoCheckProxyComplete(int rv);
// Resolves the hostname in the URL.
int DoResolveHost();
int DoResolveHostComplete(int rv);
// Establishes the QUIC connection.
int DoConnect();
void CreateConnection();
// Verifies that the connection has succeeded.
int DoConfirmConnection();
void TransitionToState(WebTransportState next_state);
const GURL url_;
const url::Origin origin_;
const NetworkIsolationKey isolation_key_;
URLRequestContext* const context_; // Unowned.
WebTransportClientVisitor* const visitor_; // Unowned.
ClientSocketFactory* const client_socket_factory_;
QuicContext* const quic_context_;
NetLogWithSource net_log_;
base::SequencedTaskRunner* task_runner_;
quic::ParsedQuicVersionVector supported_versions_;
// TODO(vasilvv): move some of those into QuicContext.
std::unique_ptr<QuicChromiumAlarmFactory> alarm_factory_;
quic::QuicCryptoClientConfig crypto_config_;
WebTransportState state_ = NEW;
ConnectState next_connect_state_ = CONNECT_STATE_NONE;
QuicTransportError error_;
bool retried_with_new_version_ = false;
ProxyInfo proxy_info_;
std::unique_ptr<ProxyResolutionRequest> proxy_resolution_request_;
std::unique_ptr<HostResolver::ResolveHostRequest> resolve_host_request_;
std::unique_ptr<DatagramClientSocket> socket_;
std::unique_ptr<quic::QuicConnection> connection_;
std::unique_ptr<quic::QuicTransportClientSession> session_;
std::unique_ptr<QuicChromiumPacketReader> packet_reader_;
std::unique_ptr<QuicEventLogger> event_logger_;
base::WeakPtrFactory<QuicTransportClient> weak_factory_{this};
};
} // namespace net
#endif // NET_QUIC_QUIC_TRANSPORT_CLIENT_H_
| 38.613402 | 100 | 0.759178 |
54dbf507f59c90a56132687f1755362fe198f4ce | 307 | h | C | impl/src/exceptions/ex_invalid_date.h | mvendra/bolotracker | 2eab0505030b8615de173ce596bb12491a8977f2 | [
"MIT"
] | null | null | null | impl/src/exceptions/ex_invalid_date.h | mvendra/bolotracker | 2eab0505030b8615de173ce596bb12491a8977f2 | [
"MIT"
] | null | null | null | impl/src/exceptions/ex_invalid_date.h | mvendra/bolotracker | 2eab0505030b8615de173ce596bb12491a8977f2 | [
"MIT"
] | null | null | null |
#ifndef __EX_INVALID_DATE_H__
#define __EX_INVALID_DATE_H__
#include "exceptions/ex_base.h"
class Ex_Invalid_Date final : public Ex_Base {
public:
Ex_Invalid_Date(const std::string &msg, const std::string &func, const unsigned int line):Ex_Base(msg, func, line){}
};
#endif // __EX_INVALID_DATE_H__
| 23.615385 | 120 | 0.771987 |
8ec9037e1034c6f4bbd6faeebd1d3f33c2d08b34 | 1,660 | h | C | experimental/Intersection/QuadraticUtilities.h | quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_skia | 90b3f9b82dbad266f960601d2120082bb841fb97 | [
"BSD-3-Clause"
] | 111 | 2015-01-13T22:01:50.000Z | 2021-06-10T15:32:48.000Z | experimental/Intersection/QuadraticUtilities.h | quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_skia | 90b3f9b82dbad266f960601d2120082bb841fb97 | [
"BSD-3-Clause"
] | 129 | 2015-01-14T16:07:02.000Z | 2020-03-11T19:44:42.000Z | experimental/Intersection/QuadraticUtilities.h | quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_skia | 90b3f9b82dbad266f960601d2120082bb841fb97 | [
"BSD-3-Clause"
] | 64 | 2015-01-14T16:45:39.000Z | 2021-09-08T11:16:05.000Z | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#if !defined QUADRATIC_UTILITIES_H
#define QUADRATIC_UTILITIES_H
#include "DataTypes.h"
int add_valid_ts(double s[], int realRoots, double* t);
void chop_at(const Quadratic& src, QuadraticPair& dst, double t);
double dx_at_t(const Quadratic& , double t);
double dy_at_t(const Quadratic& , double t);
//void dxdy_at_t(const Quadratic& , double t, _Point& xy);
_Vector dxdy_at_t(const Quadratic& , double t);
double nearestT(const Quadratic& , const _Point& );
bool point_in_hull(const Quadratic& , const _Point& );
/* Parameterization form, given A*t*t + 2*B*t*(1-t) + C*(1-t)*(1-t)
*
* a = A - 2*B + C
* b = 2*B - 2*C
* c = C
*/
inline void set_abc(const double* quad, double& a, double& b, double& c) {
a = quad[0]; // a = A
b = 2 * quad[2]; // b = 2*B
c = quad[4]; // c = C
b -= c; // b = 2*B - C
a -= b; // a = A - 2*B + C
b -= c; // b = 2*B - 2*C
}
int quadraticRootsReal(double A, double B, double C, double t[2]);
int quadraticRootsValidT(const double A, const double B, const double C, double s[2]);
void sub_divide(const Quadratic& src, double t1, double t2, Quadratic& dst);
_Point sub_divide(const Quadratic& src, const _Point& a, const _Point& c, double t1, double t2);
void toCubic(const Quadratic& , Cubic& );
_Point top(const Quadratic& , double startT, double endT);
void xy_at_t(const Quadratic& , double t, double& x, double& y);
_Point xy_at_t(const Quadratic& , double t);
#endif
| 34.583333 | 96 | 0.633133 |
fd01ee2b3afb77eb2a6f17b22f97cbaef875fca5 | 4,100 | c | C | upc/upc_local/main.c | madfist/ParallelLbmCranfield | 166852c55968c5715bd557f13258e02a38f4cbce | [
"MIT"
] | 4 | 2018-09-10T04:41:54.000Z | 2021-03-27T07:11:21.000Z | upc/upc_local/main.c | madfist/ParallelLbmCranfield | 166852c55968c5715bd557f13258e02a38f4cbce | [
"MIT"
] | null | null | null | upc/upc_local/main.c | madfist/ParallelLbmCranfield | 166852c55968c5715bd557f13258e02a38f4cbce | [
"MIT"
] | 5 | 2017-01-28T18:46:46.000Z | 2021-05-27T20:38:29.000Z | // In a Linux System compile and run as (e.g. Ubuntu):
// upcc -T=4 main.c Iterate.c ShellFunctions.c FilesReading.c FilesWriting.c CellFunctions.c BoundaryConditions.c ComputeResiduals.c -lm -o LBMSolver && upcrun LBMSolver
#include <string.h> // String operations
#include <upc_relaxed.h> // Required for UPC
#include "include/Iterate.h" // Iteration takes place
#include "include/ShellFunctions.h" // For convenience
#include "include/FilesReading.h" // For reading files
#include "include/FilesWriting.h" // For writing files e.g. tecplot
#include "include/CellFunctions.h" // For cell modifications
#include "include/BoundaryConditions.h" // boundary conditions
int main(int argc, char* argv[])
{
/////////////////////////////////////////////////////////////////////////
//////////////////////////// INITIAL DATA ///////////////////////////////
/////////////////////////////////////////////////////////////////////////
// Name of folder to which we write the files
char MainWorkDir[] = "Results";
if(MYTHREAD==0)
{
printf("\n###############################################\n");
printf("#### This is a 2D lattice-Boltzmann solver ####\n");
printf("#### Written in UPC, running on %02d threads ####\n", THREADS);
printf("###############################################\n");
// Create the working directory, continue if it already exist!
CreateDirectory(MainWorkDir);
}
///////////////////// Declare Simulation Variables //////////////////////
// inlet parameters
float Uavg, Vavg, rho_ini, Viscosity;
// integer (logical) inlet parameters
int InletProfile, CollisionModel, CurvedBoundaries, OutletProfile, CalculateDragLift;
// numbers regarding the iterations
int Iterations, AutosaveEvery, AutosaveAfter, PostprocProg;
float ConvergenceCritVeloc, ConvergenceCritRho;
// Import Simulation Variables
char IniFileName[] = "SetUpData.ini";
ReadIniData(IniFileName, &Uavg, &Vavg, &rho_ini, &Viscosity,
&InletProfile, &CollisionModel, &CurvedBoundaries,
&OutletProfile, &Iterations, &AutosaveEvery,
&AutosaveAfter, &PostprocProg, &CalculateDragLift,
&ConvergenceCritVeloc, &ConvergenceCritRho);
// Mesh files
char NodeDataFile[]="Mesh/D2node.dat";
char BCconnectorDataFile[]="Mesh/BCconnectors.dat";
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
//////////////////////
// START THE SOLVER //
//////////////////////
Iteration(NodeDataFile, // data from mesher
BCconnectorDataFile, // data from mesher
Uavg, // mean x velocity
Vavg, // mean y velocity
rho_ini, // initial density
Viscosity, // viscosity of fluid
InletProfile, // do we have inlet profile?
CollisionModel, // which collision model to use
CurvedBoundaries, // do we have curved boundaries?
OutletProfile, // do we have outlet profile?
Iterations, // how many iterations to perform
AutosaveAfter, // autosave after this many iterations
AutosaveEvery, // autosave every #th iteration
PostprocProg, // postproc with Tecplot or ParaView
CalculateDragLift, // 0: no calculation, 1: calc on BC_ID (1), 2: calc on BC_ID (2), etc
ConvergenceCritVeloc, // convergence criterion for velocity
ConvergenceCritRho); // convergence criterion for density
///////////////////////
// END OF THE SOLVER //
///////////////////////
return 0;
}
| 45.555556 | 170 | 0.503171 |
b81da30aefca817a86469133e97f1d3b8d0c49b0 | 55,693 | c | C | Socket-Fvt/Socket-Fvt/common/qrencode/backend/hanxin.c | ChinaClever/ScalePoint | 8aba361c06452ede25eaa4a0e01753c51814858d | [
"Apache-2.0"
] | null | null | null | Socket-Fvt/Socket-Fvt/common/qrencode/backend/hanxin.c | ChinaClever/ScalePoint | 8aba361c06452ede25eaa4a0e01753c51814858d | [
"Apache-2.0"
] | null | null | null | Socket-Fvt/Socket-Fvt/common/qrencode/backend/hanxin.c | ChinaClever/ScalePoint | 8aba361c06452ede25eaa4a0e01753c51814858d | [
"Apache-2.0"
] | null | null | null | /* hanxin.c - Han Xin Code
libzint - the open source barcode library
Copyright (C) 2009-2021 Robin Stuart <rstuart114@gmail.com>
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.
3. Neither the name of the project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
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.
*/
/* vim: set ts=4 sw=4 et : */
/* This code attempts to implement Han Xin Code according to ISO/IEC 20830 (draft 2019-10-10)
* (previously AIMD-015:2010 (Rev 0.8)) */
#include <stdio.h>
#ifdef _MSC_VER
#include <malloc.h>
#endif
#include "zcommon.h"
#include "reedsol.h"
#include "hanxin.h"
#include "gb2312.h"
#include "gb18030.h"
#include "eci.h"
#include <assert.h>
/* Find which submode to use for a text character */
static int getsubmode(const unsigned int input) {
if ((input >= '0') && (input <= '9')) {
return 1;
}
if ((input >= 'A') && (input <= 'Z')) {
return 1;
}
if ((input >= 'a') && (input <= 'z')) {
return 1;
}
return 2;
}
/* Return length of terminator for encoding mode */
static int terminator_length(const char mode) {
int result = 0;
switch (mode) {
case 'n':
result = 10;
break;
case 't':
result = 6;
break;
case '1':
case '2':
result = 12;
break;
case 'd':
result = 15;
break;
}
return result;
}
/* Calculate the length of the binary string */
static int calculate_binlength(const char mode[], const unsigned int source[], const int length, const int eci) {
int i;
char lastmode = '\0';
int est_binlen = 0;
int submode = 1;
int numeric_run = 0;
if (eci != 0) {
est_binlen += 4;
if (eci <= 127) {
est_binlen += 8;
} else if (eci <= 16383) {
est_binlen += 16;
} else {
est_binlen += 24;
}
}
i = 0;
do {
if (mode[i] != lastmode) {
if (i > 0) {
est_binlen += terminator_length(lastmode);
}
/* GB 4-byte has indicator for each character (and no terminator) so not included here */
/* Region1/Region2 have special terminator to go directly into each other's mode so not included here */
if (mode[i] != 'f' || ((mode[i] == '1' && lastmode == '2') || (mode[i] == '2' && lastmode == '1'))) {
est_binlen += 4;
}
if (mode[i] == 'b') { /* Byte mode has byte count (and no terminator) */
est_binlen += 13;
}
lastmode = mode[i];
submode = 1;
numeric_run = 0;
}
switch (mode[i]) {
case 'n':
if (numeric_run % 3 == 0) {
est_binlen += 10;
}
numeric_run++;
break;
case 't':
if (getsubmode(source[i]) != submode) {
est_binlen += 6;
submode = getsubmode(source[i]);
}
est_binlen += 6;
break;
case 'b':
est_binlen += source[i] > 0xFF ? 16 : 8;
break;
case '1':
case '2':
est_binlen += 12;
break;
case 'd':
est_binlen += 15;
break;
case 'f':
est_binlen += 25;
i++;
break;
}
i++;
} while (i < length);
est_binlen += terminator_length(lastmode);
return est_binlen;
}
static int isRegion1(const unsigned int glyph) {
unsigned int byte;
byte = glyph >> 8;
if ((byte >= 0xb0) && (byte <= 0xd7)) {
byte = glyph & 0xff;
if ((byte >= 0xa1) && (byte <= 0xfe)) {
return 1;
}
} else if ((byte >= 0xa1) && (byte <= 0xa3)) {
byte = glyph & 0xff;
if ((byte >= 0xa1) && (byte <= 0xfe)) {
return 1;
}
} else if ((glyph >= 0xa8a1) && (glyph <= 0xa8c0)) {
return 1;
}
return 0;
}
static int isRegion2(const unsigned int glyph) {
unsigned int byte;
byte = glyph >> 8;
if ((byte >= 0xd8) && (byte <= 0xf7)) {
byte = glyph & 0xff;
if ((byte >= 0xa1) && (byte <= 0xfe)) {
return 1;
}
}
return 0;
}
static int isDoubleByte(const unsigned int glyph) {
unsigned int byte;
byte = glyph >> 8;
if ((byte >= 0x81) && (byte <= 0xfe)) {
byte = glyph & 0xff;
if ((byte >= 0x40) && (byte <= 0x7e)) {
return 1;
}
if ((byte >= 0x80) && (byte <= 0xfe)) {
return 1;
}
}
return 0;
}
static int isFourByte(const unsigned int glyph, const unsigned int glyph2) {
unsigned int byte;
byte = glyph >> 8;
if ((byte >= 0x81) && (byte <= 0xfe)) {
byte = glyph & 0xff;
if ((byte >= 0x30) && (byte <= 0x39)) {
byte = glyph2 >> 8;
if ((byte >= 0x81) && (byte <= 0xfe)) {
byte = glyph2 & 0xff;
if ((byte >= 0x30) && (byte <= 0x39)) {
return 1;
}
}
}
}
return 0;
}
/* Convert Text 1 sub-mode character to encoding value, as given in table 3 */
static int lookup_text1(const unsigned int input) {
if ((input >= '0') && (input <= '9')) {
return input - '0';
}
if ((input >= 'A') && (input <= 'Z')) {
return input - 'A' + 10;
}
if ((input >= 'a') && (input <= 'z')) {
return input - 'a' + 36;
}
return -1;
}
/* Convert Text 2 sub-mode character to encoding value, as given in table 4 */
static int lookup_text2(const unsigned int input) {
if (input <= 27) {
return input;
}
if ((input >= ' ') && (input <= '/')) {
return input - ' ' + 28;
}
if ((input >= ':') && (input <= '@')) {
return input - ':' + 44;
}
if ((input >= '[') && (input <= 96)) {
return input - '[' + 51;
}
if ((input >= '{') && (input <= 127)) {
return input - '{' + 57;
}
return -1;
}
/* hx_define_mode() stuff */
/* Bits multiplied by this for costs, so as to be whole integer divisible by 2 and 3 */
#define HX_MULT 6
/* Whether in numeric or not. If in numeric, *p_end is set to position after numeric,
* and *p_cost is set to per-numeric cost */
static int in_numeric(const unsigned int gbdata[], const int length, const int in_posn,
unsigned int *p_end, unsigned int *p_cost) {
int i, digit_cnt;
if (in_posn < (int) *p_end) {
return 1;
}
/* Attempt to calculate the average 'cost' of using numeric mode in number of bits (times HX_MULT) */
for (i = in_posn; i < length && i < in_posn + 4 && gbdata[i] >= '0' && gbdata[i] <= '9'; i++);
digit_cnt = i - in_posn;
if (digit_cnt == 0) {
*p_end = 0;
return 0;
}
*p_end = i;
*p_cost = digit_cnt == 1 ? 60 /* 10 * HX_MULT */ : digit_cnt == 2 ? 30 /* (10 / 2) * HX_MULT */ : 20 /* (10 / 3) * HX_MULT */;
return 1;
}
/* Whether in four-byte or not. If in four-byte, *p_fourbyte is set to position after four-byte,
* and *p_fourbyte_cost is set to per-position cost */
static int in_fourbyte(const unsigned int gbdata[], const int length, const int in_posn,
unsigned int *p_end, unsigned int *p_cost) {
if (in_posn < (int) *p_end) {
return 1;
}
if (in_posn == length - 1 || !isFourByte(gbdata[in_posn], gbdata[in_posn + 1])) {
*p_end = 0;
return 0;
}
*p_end = in_posn + 2;
*p_cost = 75; /* ((4 + 21) / 2) * HX_MULT */
return 1;
}
/* Indexes into mode_types array */
#define HX_N 0 /* Numeric */
#define HX_T 1 /* Text */
#define HX_B 2 /* Binary */
#define HX_1 3 /* Common Chinese Region One */
#define HX_2 4 /* Common Chinese Region Two */
#define HX_D 5 /* GB 18030 2-byte Region */
#define HX_F 6 /* GB 18030 4-byte Region */
/* Note Unicode, GS1 and URI modes not implemented */
#define HX_NUM_MODES 7
/* Calculate optimized encoding modes. Adapted from Project Nayuki */
/* Copyright (c) Project Nayuki. (MIT License) See qr.c for detailed notice */
static void hx_define_mode(char *mode, const unsigned int gbdata[], const int length, const int debug) {
/* Must be in same order as HX_N etc */
static const char mode_types[] = { 'n', 't', 'b', '1', '2', 'd', 'f', '\0' };
/* Initial mode costs */
static unsigned int head_costs[HX_NUM_MODES] = {
/* N T B 1 2 D F */
4 * HX_MULT, 4 * HX_MULT, (4 + 13) * HX_MULT, 4 * HX_MULT, 4 * HX_MULT, 4 * HX_MULT, 0
};
/* Cost of switching modes from k to j */
static const unsigned int switch_costs[HX_NUM_MODES][HX_NUM_MODES] = {
/* N T B 1 2 D F */
/*N*/ { 0, (10 + 4) * HX_MULT, (10 + 4 + 13) * HX_MULT, (10 + 4) * HX_MULT, (10 + 4) * HX_MULT, (10 + 4) * HX_MULT, 10 * HX_MULT },
/*T*/ { (6 + 4) * HX_MULT, 0, (6 + 4 + 13) * HX_MULT, (6 + 4) * HX_MULT, (6 + 4) * HX_MULT, (6 + 4) * HX_MULT, 6 * HX_MULT },
/*B*/ { 4 * HX_MULT, 4 * HX_MULT, 0, 4 * HX_MULT, 4 * HX_MULT, 4 * HX_MULT, 0 },
/*1*/ { (12 + 4) * HX_MULT, (12 + 4) * HX_MULT, (12 + 4 + 13) * HX_MULT, 0, 12 * HX_MULT, (12 + 4) * HX_MULT, 12 * HX_MULT },
/*2*/ { (12 + 4) * HX_MULT, (12 + 4) * HX_MULT, (12 + 4 + 13) * HX_MULT, 12 * HX_MULT, 0, (12 + 4) * HX_MULT, 12 * HX_MULT },
/*D*/ { (15 + 4) * HX_MULT, (15 + 4) * HX_MULT, (15 + 4 + 13) * HX_MULT, (15 + 4) * HX_MULT, (15 + 4) * HX_MULT, 0, 15 * HX_MULT },
/*F*/ { 4 * HX_MULT, 4 * HX_MULT, (4 + 13) * HX_MULT, 4 * HX_MULT, 4 * HX_MULT, 4 * HX_MULT, 0 },
};
/* Final end-of-data costs */
static const unsigned int eod_costs[HX_NUM_MODES] = {
/* N T B 1 2 D F */
10 * HX_MULT, 6 * HX_MULT, 0, 12 * HX_MULT, 12 * HX_MULT, 15 * HX_MULT, 0
};
unsigned int numeric_end = 0, numeric_cost = 0, text_submode = 1, fourbyte_end = 0, fourbyte_cost = 0; /* State */
int text1, text2;
int i, j, k, cm_i;
unsigned int min_cost;
char cur_mode;
unsigned int prev_costs[HX_NUM_MODES];
unsigned int cur_costs[HX_NUM_MODES];
#ifndef _MSC_VER
char char_modes[length * HX_NUM_MODES];
#else
char *char_modes = (char *) _alloca(length * HX_NUM_MODES);
#endif
/* char_modes[i * HX_NUM_MODES + j] represents the mode to encode the code point at index i such that the final
* segment ends in mode_types[j] and the total number of bits is minimized over all possible choices */
memset(char_modes, 0, length * HX_NUM_MODES);
/* At the beginning of each iteration of the loop below, prev_costs[j] is the minimum number of 1/6 (1/XX_MULT)
* bits needed to encode the entire string prefix of length i, and end in mode_types[j] */
memcpy(prev_costs, head_costs, HX_NUM_MODES * sizeof(unsigned int));
/* Calculate costs using dynamic programming */
for (i = 0, cm_i = 0; i < length; i++, cm_i += HX_NUM_MODES) {
memset(cur_costs, 0, HX_NUM_MODES * sizeof(unsigned int));
if (in_numeric(gbdata, length, i, &numeric_end, &numeric_cost)) {
cur_costs[HX_N] = prev_costs[HX_N] + numeric_cost;
char_modes[cm_i + HX_N] = 'n';
text1 = 1;
text2 = 0;
} else {
text1 = lookup_text1(gbdata[i]) != -1;
text2 = lookup_text2(gbdata[i]) != -1;
}
if (text1 || text2) {
if ((text_submode == 1 && text2) || (text_submode == 2 && text1)) {
cur_costs[HX_T] = prev_costs[HX_T] + 72; /* (6 + 6) * HX_MULT */
text_submode = text2 ? 2 : 1;
} else {
cur_costs[HX_T] = prev_costs[HX_T] + 36; /* 6 * HX_MULT */
}
char_modes[cm_i + HX_T] = 't';
} else {
text_submode = 1;
}
/* Binary mode can encode anything */
cur_costs[HX_B] = prev_costs[HX_B] + (gbdata[i] > 0xFF ? 96 : 48); /* (16 : 8) * HX_MULT */
char_modes[cm_i + HX_B] = 'b';
if (in_fourbyte(gbdata, length, i, &fourbyte_end, &fourbyte_cost)) {
cur_costs[HX_F] = prev_costs[HX_F] + fourbyte_cost;
char_modes[cm_i + HX_F] = 'f';
} else {
if (isDoubleByte(gbdata[i])) {
cur_costs[HX_D] = prev_costs[HX_D] + 90; /* 15 * HX_MULT */
char_modes[cm_i + HX_D] = 'd';
if (isRegion1(gbdata[i])) { /* Subset */
cur_costs[HX_1] = prev_costs[HX_1] + 72; /* 12 * HX_MULT */
char_modes[cm_i + HX_1] = '1';
} else if (isRegion2(gbdata[i])) { /* Subset */
cur_costs[HX_2] = prev_costs[HX_2] + 72; /* 12 * HX_MULT */
char_modes[cm_i + HX_2] = '2';
}
}
}
if (i == length - 1) { /* Add end of data costs if last character */
for (j = 0; j < HX_NUM_MODES; j++) {
if (char_modes[cm_i + j]) {
cur_costs[j] += eod_costs[j];
}
}
}
/* Start new segment at the end to switch modes */
for (j = 0; j < HX_NUM_MODES; j++) { /* To mode */
for (k = 0; k < HX_NUM_MODES; k++) { /* From mode */
if (j != k && char_modes[cm_i + k]) {
unsigned int new_cost = cur_costs[k] + switch_costs[k][j];
if (!char_modes[cm_i + j] || new_cost < cur_costs[j]) {
cur_costs[j] = new_cost;
char_modes[cm_i + j] = mode_types[k];
}
}
}
}
memcpy(prev_costs, cur_costs, HX_NUM_MODES * sizeof(unsigned int));
}
/* Find optimal ending mode */
min_cost = prev_costs[0];
cur_mode = mode_types[0];
for (i = 1; i < HX_NUM_MODES; i++) {
if (prev_costs[i] < min_cost) {
min_cost = prev_costs[i];
cur_mode = mode_types[i];
}
}
/* Get optimal mode for each code point by tracing backwards */
for (i = length - 1, cm_i = i * HX_NUM_MODES; i >= 0; i--, cm_i -= HX_NUM_MODES) {
j = strchr(mode_types, cur_mode) - mode_types;
cur_mode = char_modes[cm_i + j];
mode[i] = cur_mode;
}
if (debug & ZINT_DEBUG_PRINT) {
printf(" Mode: %.*s\n", length, mode);
}
}
/* Convert input data to binary stream */
static void calculate_binary(char binary[], const char mode[], unsigned int source[], const int length, const int eci,
int *bin_len, const int debug) {
int position = 0;
int i, count, encoding_value;
int first_byte, second_byte;
int third_byte, fourth_byte;
int glyph;
int submode;
int bp = 0;
if (eci != 0) {
/* Encoding ECI assignment number, according to Table 5 */
bp = bin_append_posn(8, 4, binary, bp); // ECI
if (eci <= 127) {
bp = bin_append_posn(eci, 8, binary, bp);
} else if (eci <= 16383) {
bp = bin_append_posn(2, 2, binary, bp);
bp = bin_append_posn(eci, 14, binary, bp);
} else {
bp = bin_append_posn(6, 3, binary, bp);
bp = bin_append_posn(eci, 21, binary, bp);
}
}
do {
int block_length = 0;
int double_byte = 0;
do {
if (mode[position] == 'b' && source[position + block_length] > 0xFF) {
double_byte++;
}
block_length++;
} while (position + block_length < length && mode[position + block_length] == mode[position]);
switch (mode[position]) {
case 'n':
/* Numeric mode */
/* Mode indicator */
bp = bin_append_posn(1, 4, binary, bp);
if (debug & ZINT_DEBUG_PRINT) {
printf("Numeric\n");
}
count = 0; /* Suppress gcc -Wmaybe-uninitialized */
i = 0;
while (i < block_length) {
int first = 0;
first = posn(NEON, (char) source[position + i]);
count = 1;
encoding_value = first;
if (i + 1 < block_length && mode[position + i + 1] == 'n') {
int second = posn(NEON, (char) source[position + i + 1]);
count = 2;
encoding_value = (encoding_value * 10) + second;
if (i + 2 < block_length && mode[position + i + 2] == 'n') {
int third = posn(NEON, (char) source[position + i + 2]);
count = 3;
encoding_value = (encoding_value * 10) + third;
}
}
bp = bin_append_posn(encoding_value, 10, binary, bp);
if (debug & ZINT_DEBUG_PRINT) {
printf("0x%3x (%d)", encoding_value, encoding_value);
}
i += count;
}
/* Mode terminator depends on number of characters in last group (Table 2) */
switch (count) {
case 1:
bp = bin_append_posn(1021, 10, binary, bp);
break;
case 2:
bp = bin_append_posn(1022, 10, binary, bp);
break;
case 3:
bp = bin_append_posn(1023, 10, binary, bp);
break;
}
if (debug & ZINT_DEBUG_PRINT) {
printf(" (TERM %d)\n", count);
}
break;
case 't':
/* Text mode */
/* Mode indicator */
bp = bin_append_posn(2, 4, binary, bp);
if (debug & ZINT_DEBUG_PRINT) {
printf("Text\n");
}
submode = 1;
i = 0;
while (i < block_length) {
if (getsubmode(source[i + position]) != submode) {
/* Change submode */
bp = bin_append_posn(62, 6, binary, bp);
submode = getsubmode(source[i + position]);
if (debug & ZINT_DEBUG_PRINT) {
printf("SWITCH ");
}
}
if (submode == 1) {
encoding_value = lookup_text1(source[i + position]);
} else {
encoding_value = lookup_text2(source[i + position]);
}
bp = bin_append_posn(encoding_value, 6, binary, bp);
if (debug & ZINT_DEBUG_PRINT) {
printf("%.2x [ASC %.2x] ", encoding_value, source[i + position]);
}
i++;
}
/* Terminator */
bp = bin_append_posn(63, 6, binary, bp);
if (debug & ZINT_DEBUG_PRINT) {
printf("\n");
}
break;
case 'b':
/* Binary Mode */
/* Mode indicator */
bp = bin_append_posn(3, 4, binary, bp);
/* Count indicator */
bp = bin_append_posn(block_length + double_byte, 13, binary, bp);
if (debug & ZINT_DEBUG_PRINT) {
printf("Binary (length %d)\n", block_length + double_byte);
}
i = 0;
while (i < block_length) {
/* 8-bit bytes with no conversion */
bp = bin_append_posn(source[i + position], source[i + position] > 0xFF ? 16 : 8, binary, bp);
if (debug & ZINT_DEBUG_PRINT) {
printf("%d ", source[i + position]);
}
i++;
}
if (debug & ZINT_DEBUG_PRINT) {
printf("\n");
}
break;
case '1':
/* Region 1 encoding */
/* Mode indicator */
if (position == 0 || mode[position - 1] != '2') { /* Unless previous mode Region 2 */
bp = bin_append_posn(4, 4, binary, bp);
}
if (debug & ZINT_DEBUG_PRINT) {
printf("Region 1%s\n", position == 0 || mode[position - 1] != '2' ? "" : " (NO indicator)" );
}
i = 0;
while (i < block_length) {
first_byte = (source[i + position] & 0xff00) >> 8;
second_byte = source[i + position] & 0xff;
/* Subset 1 */
glyph = (0x5e * (first_byte - 0xb0)) + (second_byte - 0xa1);
/* Subset 2 */
if ((first_byte >= 0xa1) && (first_byte <= 0xa3)) {
if ((second_byte >= 0xa1) && (second_byte <= 0xfe)) {
glyph = (0x5e * (first_byte - 0xa1)) + (second_byte - 0xa1) + 0xeb0;
}
}
/* Subset 3 */
if ((source[i + position] >= 0xa8a1) && (source[i + position] <= 0xa8c0)) {
glyph = (second_byte - 0xa1) + 0xfca;
}
if (debug & ZINT_DEBUG_PRINT) {
printf("%.3x [GB %.4x] ", glyph, source[i + position]);
}
bp = bin_append_posn(glyph, 12, binary, bp);
i++;
}
/* Terminator */
bp = bin_append_posn(position + block_length == length || mode[position + block_length] != '2' ? 4095 : 4094, 12, binary, bp);
if (debug & ZINT_DEBUG_PRINT) {
printf("(TERM %x)\n", position + block_length == length || mode[position + block_length] != '2' ? 4095 : 4094);
}
break;
case '2':
/* Region 2 encoding */
/* Mode indicator */
if (position == 0 || mode[position - 1] != '1') { /* Unless previous mode Region 1 */
bp = bin_append_posn(5, 4, binary, bp);
}
if (debug & ZINT_DEBUG_PRINT) {
printf("Region 2%s\n", position == 0 || mode[position - 1] != '1' ? "" : " (NO indicator)" );
}
i = 0;
while (i < block_length) {
first_byte = (source[i + position] & 0xff00) >> 8;
second_byte = source[i + position] & 0xff;
glyph = (0x5e * (first_byte - 0xd8)) + (second_byte - 0xa1);
if (debug & ZINT_DEBUG_PRINT) {
printf("%.3x [GB %.4x] ", glyph, source[i + position]);
}
bp = bin_append_posn(glyph, 12, binary, bp);
i++;
}
/* Terminator */
bp = bin_append_posn(position + block_length == length || mode[position + block_length] != '1' ? 4095 : 4094, 12, binary, bp);
if (debug & ZINT_DEBUG_PRINT) {
printf("(TERM %x)\n", position + block_length == length || mode[position + block_length] != '1' ? 4095 : 4094);
}
break;
case 'd':
/* Double byte encoding */
/* Mode indicator */
bp = bin_append_posn(6, 4, binary, bp);
if (debug & ZINT_DEBUG_PRINT) {
printf("Double byte\n");
}
i = 0;
while (i < block_length) {
first_byte = (source[i + position] & 0xff00) >> 8;
second_byte = source[i + position] & 0xff;
if (second_byte <= 0x7e) {
glyph = (0xbe * (first_byte - 0x81)) + (second_byte - 0x40);
} else {
glyph = (0xbe * (first_byte - 0x81)) + (second_byte - 0x41);
}
if (debug & ZINT_DEBUG_PRINT) {
printf("%.4x ", glyph);
}
bp = bin_append_posn(glyph, 15, binary, bp);
i++;
}
/* Terminator */
bp = bin_append_posn(32767, 15, binary, bp);
/* Terminator sequence of length 12 is a mistake
- confirmed by Wang Yi */
if (debug & ZINT_DEBUG_PRINT) {
printf("\n");
}
break;
case 'f':
/* Four-byte encoding */
if (debug & ZINT_DEBUG_PRINT) {
printf("Four byte\n");
}
i = 0;
while (i < block_length) {
/* Mode indicator */
bp = bin_append_posn(7, 4, binary, bp);
first_byte = (source[i + position] & 0xff00) >> 8;
second_byte = source[i + position] & 0xff;
third_byte = (source[i + position + 1] & 0xff00) >> 8;
fourth_byte = source[i + position + 1] & 0xff;
glyph = (0x3138 * (first_byte - 0x81)) + (0x04ec * (second_byte - 0x30)) +
(0x0a * (third_byte - 0x81)) + (fourth_byte - 0x30);
if (debug & ZINT_DEBUG_PRINT) {
printf("%d ", glyph);
}
bp = bin_append_posn(glyph, 21, binary, bp);
i += 2;
}
/* No terminator */
if (debug & ZINT_DEBUG_PRINT) {
printf("\n");
}
break;
}
position += block_length;
} while (position < length);
binary[bp] = '\0';
if (debug & ZINT_DEBUG_PRINT) printf("Binary (%d): %s\n", bp, binary);
*bin_len = bp;
}
/* Finder pattern for top left of symbol */
static void hx_place_finder_top_left(unsigned char *grid, const int size) {
int xp, yp;
int x = 0, y = 0;
char finder[] = {0x7F, 0x40, 0x5F, 0x50, 0x57, 0x57, 0x57};
for (xp = 0; xp < 7; xp++) {
for (yp = 0; yp < 7; yp++) {
if (finder[yp] & 0x40 >> xp) {
grid[((yp + y) * size) + (xp + x)] = 0x11;
} else {
grid[((yp + y) * size) + (xp + x)] = 0x10;
}
}
}
}
/* Finder pattern for top right and bottom left of symbol */
static void hx_place_finder(unsigned char *grid, const int size, const int x, const int y) {
int xp, yp;
char finder[] = {0x7F, 0x01, 0x7D, 0x05, 0x75, 0x75, 0x75};
for (xp = 0; xp < 7; xp++) {
for (yp = 0; yp < 7; yp++) {
if (finder[yp] & 0x40 >> xp) {
grid[((yp + y) * size) + (xp + x)] = 0x11;
} else {
grid[((yp + y) * size) + (xp + x)] = 0x10;
}
}
}
}
/* Finder pattern for bottom right of symbol */
static void hx_place_finder_bottom_right(unsigned char *grid, const int size) {
int xp, yp;
int x = size - 7, y = size - 7;
char finder[] = {0x75, 0x75, 0x75, 0x05, 0x7D, 0x01, 0x7F};
for (xp = 0; xp < 7; xp++) {
for (yp = 0; yp < 7; yp++) {
if (finder[yp] & 0x40 >> xp) {
grid[((yp + y) * size) + (xp + x)] = 0x11;
} else {
grid[((yp + y) * size) + (xp + x)] = 0x10;
}
}
}
}
/* Avoid plotting outside symbol or over finder patterns */
static void hx_safe_plot(unsigned char *grid, const int size, const int x, const int y, const int value) {
if ((x >= 0) && (x < size)) {
if ((y >= 0) && (y < size)) {
if (grid[(y * size) + x] == 0) {
grid[(y * size) + x] = value;
}
}
}
}
/* Plot an alignment pattern around top and right of a module */
static void hx_plot_alignment(unsigned char *grid, const int size, const int x, const int y, const int w, const int h) {
int i;
hx_safe_plot(grid, size, x, y, 0x11);
hx_safe_plot(grid, size, x - 1, y + 1, 0x10);
for (i = 1; i <= w; i++) {
/* Top */
hx_safe_plot(grid, size, x - i, y, 0x11);
hx_safe_plot(grid, size, x - i - 1, y + 1, 0x10);
}
for (i = 1; i < h; i++) {
/* Right */
hx_safe_plot(grid, size, x, y + i, 0x11);
hx_safe_plot(grid, size, x - 1, y + i + 1, 0x10);
}
}
/* Plot assistant alignment patterns */
static void hx_plot_assistant(unsigned char *grid, const int size, const int x, const int y) {
hx_safe_plot(grid, size, x - 1, y - 1, 0x10);
hx_safe_plot(grid, size, x, y - 1, 0x10);
hx_safe_plot(grid, size, x + 1, y - 1, 0x10);
hx_safe_plot(grid, size, x - 1, y, 0x10);
hx_safe_plot(grid, size, x, y, 0x11);
hx_safe_plot(grid, size, x + 1, y, 0x10);
hx_safe_plot(grid, size, x - 1, y + 1, 0x10);
hx_safe_plot(grid, size, x, y + 1, 0x10);
hx_safe_plot(grid, size, x + 1, y + 1, 0x10);
}
/* Put static elements in the grid */
static void hx_setup_grid(unsigned char *grid, const int size, const int version) {
int i;
memset(grid, 0, (size_t) size * size);
/* Add finder patterns */
hx_place_finder_top_left(grid, size);
hx_place_finder(grid, size, 0, size - 7);
hx_place_finder(grid, size, size - 7, 0);
hx_place_finder_bottom_right(grid, size);
/* Add finder pattern separator region */
for (i = 0; i < 8; i++) {
/* Top left */
grid[(7 * size) + i] = 0x10;
grid[(i * size) + 7] = 0x10;
/* Top right */
grid[(7 * size) + (size - i - 1)] = 0x10;
grid[((size - i - 1) * size) + 7] = 0x10;
/* Bottom left */
grid[(i * size) + (size - 8)] = 0x10;
grid[((size - 8) * size) + i] = 0x10;
/* Bottom right */
grid[((size - 8) * size) + (size - i - 1)] = 0x10;
grid[((size - i - 1) * size) + (size - 8)] = 0x10;
}
/* Reserve function information region */
for (i = 0; i < 9; i++) {
/* Top left */
grid[(8 * size) + i] = 0x10;
grid[(i * size) + 8] = 0x10;
/* Top right */
grid[(8 * size) + (size - i - 1)] = 0x10;
grid[((size - i - 1) * size) + 8] = 0x10;
/* Bottom left */
grid[(i * size) + (size - 9)] = 0x10;
grid[((size - 9) * size) + i] = 0x10;
/* Bottom right */
grid[((size - 9) * size) + (size - i - 1)] = 0x10;
grid[((size - i - 1) * size) + (size - 9)] = 0x10;
}
if (version > 3) {
int k = hx_module_k[version - 1];
int r = hx_module_r[version - 1];
int m = hx_module_m[version - 1];
int x, y, row_switch, column_switch;
int module_height, module_width;
int mod_x, mod_y;
/* Add assistant alignment patterns to left and right */
y = 0;
mod_y = 0;
do {
if (mod_y < m) {
module_height = k;
} else {
module_height = r - 1;
}
if ((mod_y & 1) == 0) {
if ((m & 1) == 1) {
hx_plot_assistant(grid, size, 0, y);
}
} else {
if ((m & 1) == 0) {
hx_plot_assistant(grid, size, 0, y);
}
hx_plot_assistant(grid, size, size - 1, y);
}
mod_y++;
y += module_height;
} while (y < size);
/* Add assistant alignment patterns to top and bottom */
x = (size - 1);
mod_x = 0;
do {
if (mod_x < m) {
module_width = k;
} else {
module_width = r - 1;
}
if ((mod_x & 1) == 0) {
if ((m & 1) == 1) {
hx_plot_assistant(grid, size, x, (size - 1));
}
} else {
if ((m & 1) == 0) {
hx_plot_assistant(grid, size, x, (size - 1));
}
hx_plot_assistant(grid, size, x, 0);
}
mod_x++;
x -= module_width;
} while (x >= 0);
/* Add alignment pattern */
column_switch = 1;
y = 0;
mod_y = 0;
do {
if (mod_y < m) {
module_height = k;
} else {
module_height = r - 1;
}
if (column_switch == 1) {
row_switch = 1;
column_switch = 0;
} else {
row_switch = 0;
column_switch = 1;
}
x = (size - 1);
mod_x = 0;
do {
if (mod_x < m) {
module_width = k;
} else {
module_width = r - 1;
}
if (row_switch == 1) {
if (!(y == 0 && x == (size - 1))) {
hx_plot_alignment(grid, size, x, y, module_width, module_height);
}
row_switch = 0;
} else {
row_switch = 1;
}
mod_x++;
x -= module_width;
} while (x >= 0);
mod_y++;
y += module_height;
} while (y < size);
}
}
/* Calculate error correction codes */
static void hx_add_ecc(unsigned char fullstream[], const unsigned char datastream[], const int data_codewords,
const int version, const int ecc_level) {
unsigned char data_block[180];
unsigned char ecc_block[36];
int i, j, block;
int input_position = -1;
int output_position = -1;
int table_d1_pos = ((version - 1) * 36) + ((ecc_level - 1) * 9);
rs_t rs;
rs_init_gf(&rs, 0x163); // x^8 + x^6 + x^5 + x + 1 = 0
for (i = 0; i < 3; i++) {
int batch_size = hx_table_d1[table_d1_pos + (3 * i)];
int data_length = hx_table_d1[table_d1_pos + (3 * i) + 1];
int ecc_length = hx_table_d1[table_d1_pos + (3 * i) + 2];
rs_init_code(&rs, ecc_length, 1);
for (block = 0; block < batch_size; block++) {
for (j = 0; j < data_length; j++) {
input_position++;
output_position++;
data_block[j] = input_position < data_codewords ? datastream[input_position] : 0;
fullstream[output_position] = data_block[j];
}
rs_encode(&rs, data_length, data_block, ecc_block);
for (j = 0; j < ecc_length; j++) {
output_position++;
fullstream[output_position] = ecc_block[ecc_length - j - 1];
}
}
}
}
static void hx_set_function_info(unsigned char *grid, const int size, const int version, const int ecc_level,
const int bitmask, const int debug) {
int i, j;
char function_information[34];
unsigned char fi_cw[3] = {0};
unsigned char fi_ecc[4];
int bp = 0;
rs_t rs;
/* Form function information string */
bp = bin_append_posn(version + 20, 8, function_information, bp);
bp = bin_append_posn(ecc_level - 1, 2, function_information, bp);
bp = bin_append_posn(bitmask, 2, function_information, bp);
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
if (function_information[(i * 4) + j] == '1') {
fi_cw[i] += (0x08 >> j);
}
}
}
rs_init_gf(&rs, 0x13);
rs_init_code(&rs, 4, 1);
rs_encode(&rs, 3, fi_cw, fi_ecc);
for (i = 3; i >= 0; i--) {
bp = bin_append_posn(fi_ecc[i], 4, function_information, bp);
}
/* This alternating filler pattern at end not mentioned in ISO/IEC 20830 (draft 2019-10-10) and does not appear
* in Figure 1 or the figures in Annex K but does appear in Figure 2 and Figures 4-9 */
for (i = 28; i < 34; i++) {
if (i & 1) {
function_information[i] = '1';
} else {
function_information[i] = '0';
}
}
if (debug & ZINT_DEBUG_PRINT) {
printf("Version: %d, ECC: %d, Mask: %d, Structural Info: %.34s\n", version, ecc_level, bitmask, function_information);
}
/* Add function information to symbol */
for (i = 0; i < 9; i++) {
if (function_information[i] == '1') {
grid[(8 * size) + i] = 0x01;
grid[((size - 8 - 1) * size) + (size - i - 1)] = 0x01;
}
if (function_information[i + 8] == '1') {
grid[((8 - i) * size) + 8] = 0x01;
grid[((size - 8 - 1 + i) * size) + (size - 8 - 1)] = 0x01;
}
if (function_information[i + 17] == '1') {
grid[(i * size) + (size - 1 - 8)] = 0x01;
grid[((size - 1 - i) * size) + 8] = 0x01;
}
if (function_information[i + 25] == '1') {
grid[(8 * size) + (size - 1 - 8 + i)] = 0x01;
grid[((size - 1 - 8) * size) + (8 - i)] = 0x01;
}
}
}
/* Rearrange data in batches of 13 codewords (section 5.8.2) */
static void make_picket_fence(const unsigned char fullstream[], unsigned char picket_fence[], const int streamsize) {
int i, start;
int output_position = 0;
for (start = 0; start < 13; start++) {
for (i = start; i < streamsize; i += 13) {
if (i < streamsize) {
picket_fence[output_position] = fullstream[i];
output_position++;
}
}
}
}
/* Evaluate a bitmask according to table 9 */
static int hx_evaluate(const unsigned char *local, const int size) {
static const unsigned char h1010111[7] = { 1, 0, 1, 0, 1, 1, 1 };
static const unsigned char h1110101[7] = { 1, 1, 1, 0, 1, 0, 1 };
int x, y, r, block;
int result = 0;
int state;
int a, b, afterCount, beforeCount;
/* Test 1: 1:1:1:1:3 or 3:1:1:1:1 ratio pattern in row/column */
/* Vertical */
for (x = 0; x < size; x++) {
for (y = 0; y <= (size - 7); y++) {
if (local[y * size + x] && local[(y + 1) * size + x] != local[(y + 5) * size + x] &&
local[(y + 2) * size + x] && !local[(y + 3) * size + x] &&
local[(y + 4) * size + x] && local[(y + 6) * size + x]) {
/* Pattern found, check before and after */
beforeCount = 0;
for (b = (y - 1); b >= (y - 3); b--) {
if (b < 0) { /* Count < edge as whitespace */
beforeCount = 3;
break;
}
if (local[(b * size) + x]) {
break;
}
beforeCount++;
}
if (beforeCount == 3) {
/* Pattern is preceded by light area 3 modules wide */
result += 50;
} else {
afterCount = 0;
for (a = (y + 7); a <= (y + 9); a++) {
if (a >= size) { /* Count > edge as whitespace */
afterCount = 3;
break;
}
if (local[(a * size) + x]) {
break;
}
afterCount++;
}
if (afterCount == 3) {
/* Pattern is followed by light area 3 modules wide */
result += 50;
}
}
y++; /* Skip to next possible match */
}
}
}
/* Horizontal */
for (y = 0; y < size; y++) {
r = y * size;
for (x = 0; x <= (size - 7); x++) {
if (memcmp(local + r + x, h1010111, 7) == 0 || memcmp(local + r + x, h1110101, 7) == 0) {
/* Pattern found, check before and after */
beforeCount = 0;
for (b = (x - 1); b >= (x - 3); b--) {
if (b < 0) { /* Count < edge as whitespace */
beforeCount = 3;
break;
}
if (local[r + b]) {
break;
}
beforeCount++;
}
if (beforeCount == 3) {
/* Pattern is preceded by light area 3 modules wide */
result += 50;
} else {
afterCount = 0;
for (a = (x + 7); a <= (x + 9); a++) {
if (a >= size) { /* Count > edge as whitespace */
afterCount = 3;
break;
}
if (local[r + a]) {
break;
}
afterCount++;
}
if (afterCount == 3) {
/* Pattern is followed by light area 3 modules wide */
result += 50;
}
}
x++; /* Skip to next possible match */
}
}
}
/* Test 2: Adjacent modules in row/column in same colour */
/* In AIMD-15 section 5.8.3.2 it is stated... “In Table 9 below, i refers to the row
* position of the module.” - however i being the length of the run of the
* same colour (i.e. "block" below) in the same fashion as ISO/IEC 18004
* makes more sense. -- Confirmed by Wang Yi */
/* Fixed in ISO/IEC 20830 (draft 2019-10-10) section 5.8.3.2 "In Table 12 below, i refers to the modules with same color." */
/* Vertical */
for (x = 0; x < size; x++) {
block = 0;
state = 0;
for (y = 0; y < size; y++) {
if (local[(y * size) + x] == state) {
block++;
} else {
if (block >= 3) {
result += block * 4;
}
block = 1;
state = local[(y * size) + x];
}
}
if (block >= 3) {
result += block * 4;
}
}
/* Horizontal */
for (y = 0; y < size; y++) {
r = y * size;
block = 0;
state = 0;
for (x = 0; x < size; x++) {
if (local[r + x] == state) {
block++;
} else {
if (block >= 3) {
result += block * 4;
}
block = 1;
state = local[r + x];
}
}
if (block >= 3) {
result += block * 4;
}
}
return result;
}
/* Apply the four possible bitmasks for evaluation */
/* TODO: Haven't been able to replicate (or even get close to) the penalty scores in ISO/IEC 20830
* (draft 2019-10-10) Annex K examples; however they don't use alternating filler pattern on structural info */
static void hx_apply_bitmask(unsigned char *grid, const int size, const int version, const int ecc_level,
const int user_mask, const int debug) {
int x, y;
int i, j, r, k;
int pattern, penalty[4] = {0};
int best_pattern;
int bit;
int size_squared = size * size;
#ifndef _MSC_VER
unsigned char mask[size_squared];
unsigned char local[size_squared];
#else
unsigned char *mask = (unsigned char *) _alloca(size_squared * sizeof(unsigned char));
unsigned char *local = (unsigned char *) _alloca(size_squared * sizeof(unsigned char));
#endif
/* Perform data masking */
memset(mask, 0, size_squared);
for (y = 0; y < size; y++) {
r = y * size;
for (x = 0; x < size; x++) {
k = r + x;
if (!(grid[k] & 0xf0)) {
j = x + 1;
i = y + 1;
if (((i + j) & 1) == 0) {
mask[k] |= 0x02;
}
if (((((i + j) % 3) + (j % 3)) & 1) == 0) {
mask[k] |= 0x04;
}
if ((((i % j) + (j % i) + (i % 3) + (j % 3)) & 1) == 0) {
mask[k] |= 0x08;
}
}
}
}
if (user_mask) {
best_pattern = user_mask - 1;
} else {
// apply data masks to grid, result in local
/* Do null pattern 00 separately first */
pattern = 0;
for (k = 0; k < size_squared; k++) {
local[k] = grid[k] & 0x0f;
}
/* Set the Structural Info */
hx_set_function_info(local, size, version, ecc_level, pattern, 0 /*debug*/);
/* Evaluate result */
penalty[pattern] = hx_evaluate(local, size);
best_pattern = 0;
for (pattern = 1; pattern < 4; pattern++) {
bit = 1 << pattern;
for (k = 0; k < size_squared; k++) {
if (mask[k] & bit) {
local[k] = grid[k] ^ 0x01;
} else {
local[k] = grid[k] & 0x0f;
}
}
/* Set the Structural Info */
hx_set_function_info(local, size, version, ecc_level, pattern, 0 /*debug*/);
/* Evaluate result */
penalty[pattern] = hx_evaluate(local, size);
if (penalty[pattern] < penalty[best_pattern]) {
best_pattern = pattern;
}
}
}
if (debug & ZINT_DEBUG_PRINT) {
printf("Mask: %d (%s)", best_pattern, user_mask ? "specified" : "automatic");
if (!user_mask) {
for (pattern = 0; pattern < 4; pattern++) printf(" %d:%d", pattern, penalty[pattern]);
}
printf("\n");
}
/* Apply mask */
if (best_pattern) { /* If not null mask */
if (!user_mask && best_pattern == 3) { /* Reuse last */
memcpy(grid, local, size_squared);
} else {
bit = 1 << best_pattern;
for (k = 0; k < size_squared; k++) {
if (mask[k] & bit) {
grid[k] ^= 0x01;
}
}
}
}
/* Set the Structural Info */
hx_set_function_info(grid, size, version, ecc_level, best_pattern, debug);
}
/* Han Xin Code - main */
INTERNAL int han_xin(struct zint_symbol *symbol, unsigned char source[], int length) {
int est_binlen;
int ecc_level = symbol->option_1;
int i, j, j_max, version;
int full_multibyte;
int user_mask;
int data_codewords = 0, size;
int size_squared;
int codewords;
int bin_len;
int eci_length = get_eci_length(symbol->eci, source, length);
#ifndef _MSC_VER
unsigned int gbdata[eci_length + 1];
char mode[eci_length];
#else
unsigned int *gbdata = (unsigned int *) _alloca((eci_length + 1) * sizeof(unsigned int));
char *mode = (char *) _alloca(eci_length);
char *binary;
unsigned char *datastream;
unsigned char *fullstream;
unsigned char *picket_fence;
unsigned char *grid;
#endif
/* If ZINT_FULL_MULTIBYTE set use Hanzi mode in DATA_MODE or for non-GB 18030 in UNICODE_MODE */
full_multibyte = (symbol->option_3 & 0xFF) == ZINT_FULL_MULTIBYTE;
user_mask = (symbol->option_3 >> 8) & 0x0F; /* User mask is pattern + 1, so >= 1 and <= 4 */
if (user_mask > 4) {
user_mask = 0; /* Ignore */
}
if ((symbol->input_mode & 0x07) == DATA_MODE) {
gb18030_cpy(source, &length, gbdata, full_multibyte);
} else {
int done = 0;
if (symbol->eci != 29) { /* Unless ECI 29 (GB) */
/* Try other conversions (ECI 0 defaults to ISO/IEC 8859-1) */
int error_number = gb18030_utf8_to_eci(symbol->eci, source, &length, gbdata, full_multibyte);
if (error_number == 0) {
done = 1;
} else if (symbol->eci) {
strcpy(symbol->errtxt, "575: Invalid characters in input data");
return error_number;
}
}
if (!done) {
/* Try GB 18030 */
int error_number = gb18030_utf8(symbol, source, &length, gbdata);
if (error_number != 0) {
return error_number;
}
}
}
hx_define_mode(mode, gbdata, length, symbol->debug);
est_binlen = calculate_binlength(mode, gbdata, length, symbol->eci);
#ifndef _MSC_VER
char binary[est_binlen + 1];
#else
binary = (char *) _alloca((est_binlen + 1));
#endif
if ((ecc_level <= 0) || (ecc_level >= 5)) {
ecc_level = 1;
}
calculate_binary(binary, mode, gbdata, length, symbol->eci, &bin_len, symbol->debug);
codewords = bin_len >> 3;
if (bin_len & 0x07) {
codewords++;
}
version = 85;
for (i = 84; i > 0; i--) {
switch (ecc_level) {
case 1:
if (hx_data_codewords_L1[i - 1] > codewords) {
version = i;
data_codewords = hx_data_codewords_L1[i - 1];
}
break;
case 2:
if (hx_data_codewords_L2[i - 1] > codewords) {
version = i;
data_codewords = hx_data_codewords_L2[i - 1];
}
break;
case 3:
if (hx_data_codewords_L3[i - 1] > codewords) {
version = i;
data_codewords = hx_data_codewords_L3[i - 1];
}
break;
case 4:
if (hx_data_codewords_L4[i - 1] > codewords) {
version = i;
data_codewords = hx_data_codewords_L4[i - 1];
}
break;
default:
assert(0);
break;
}
}
if (version == 85) {
strcpy(symbol->errtxt, "541: Input too long for selected error correction level");
return ZINT_ERROR_TOO_LONG;
}
if ((symbol->option_2 < 0) || (symbol->option_2 > 84)) {
symbol->option_2 = 0;
}
if (symbol->option_2 > version) {
version = symbol->option_2;
}
if ((symbol->option_2 != 0) && (symbol->option_2 < version)) {
strcpy(symbol->errtxt, "542: Input too long for selected symbol size");
return ZINT_ERROR_TOO_LONG;
}
/* If there is spare capacity, increase the level of ECC */
if (symbol->option_1 == -1 || symbol->option_1 != ecc_level) { /* Unless explicitly specified (within min/max bounds) by user */
if ((ecc_level == 1) && (codewords < hx_data_codewords_L2[version - 1])) {
ecc_level = 2;
data_codewords = hx_data_codewords_L2[version - 1];
}
if ((ecc_level == 2) && (codewords < hx_data_codewords_L3[version - 1])) {
ecc_level = 3;
data_codewords = hx_data_codewords_L3[version - 1];
}
if ((ecc_level == 3) && (codewords < hx_data_codewords_L4[version - 1])) {
ecc_level = 4;
data_codewords = hx_data_codewords_L4[version - 1];
}
}
size = (version * 2) + 21;
size_squared = size * size;
#ifndef _MSC_VER
unsigned char datastream[data_codewords];
unsigned char fullstream[hx_total_codewords[version - 1]];
unsigned char picket_fence[hx_total_codewords[version - 1]];
unsigned char grid[size_squared];
#else
datastream = (unsigned char *) _alloca((data_codewords) * sizeof (unsigned char));
fullstream = (unsigned char *) _alloca((hx_total_codewords[version - 1]) * sizeof (unsigned char));
picket_fence = (unsigned char *) _alloca((hx_total_codewords[version - 1]) * sizeof (unsigned char));
grid = (unsigned char *) _alloca(size_squared * sizeof(unsigned char));
#endif
memset(datastream, 0, data_codewords);
for (i = 0; i < bin_len; i++) {
if (binary[i] == '1') {
datastream[i >> 3] |= 0x80 >> (i & 0x07);
}
}
if (symbol->debug & ZINT_DEBUG_PRINT) {
printf("Datastream length: %d\n", data_codewords);
printf("Datastream:\n");
for (i = 0; i < data_codewords; i++) {
printf("%.2x ", datastream[i]);
}
printf("\n");
}
#ifdef ZINT_TEST
if (symbol->debug & ZINT_DEBUG_TEST) debug_test_codeword_dump(symbol, datastream, data_codewords);
#endif
hx_setup_grid(grid, size, version);
hx_add_ecc(fullstream, datastream, data_codewords, version, ecc_level);
make_picket_fence(fullstream, picket_fence, hx_total_codewords[version - 1]);
/* Populate grid */
j = 0;
j_max = hx_total_codewords[version - 1] * 8;
for (i = 0; i < size_squared; i++) {
if (grid[i] == 0x00) {
if (j < j_max) {
if (picket_fence[(j >> 3)] & (0x80 >> (j & 0x07))) {
grid[i] = 0x01;
}
j++;
} else {
break;
}
}
}
hx_apply_bitmask(grid, size, version, ecc_level, user_mask, symbol->debug);
symbol->width = size;
symbol->rows = size;
for (i = 0; i < size; i++) {
int r = i * size;
for (j = 0; j < size; j++) {
if (grid[r + j] & 0x01) {
set_module(symbol, i, j);
}
}
symbol->row_height[i] = 1;
}
return 0;
}
| 33.489477 | 156 | 0.465678 |
92f108fc1b02fcacfa51f4a8a35dd5f13c5aaa5f | 1,305 | h | C | System/Library/PrivateFrameworks/NanoPassKit.framework/NPKPaymentProvisioningFlowControllerProvisioningResultStepContext.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | 1 | 2020-11-04T15:43:01.000Z | 2020-11-04T15:43:01.000Z | System/Library/PrivateFrameworks/NanoPassKit.framework/NPKPaymentProvisioningFlowControllerProvisioningResultStepContext.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/NanoPassKit.framework/NPKPaymentProvisioningFlowControllerProvisioningResultStepContext.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:54:47 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/NanoPassKit.framework/NanoPassKit
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <NanoPassKit/NPKPaymentProvisioningFlowStepContext.h>
@class PKPaymentPass, NSError;
@interface NPKPaymentProvisioningFlowControllerProvisioningResultStepContext : NPKPaymentProvisioningFlowStepContext {
BOOL _cardAdded;
PKPaymentPass* _provisionedPass;
NSError* _error;
}
@property (assign,nonatomic) BOOL cardAdded; //@synthesize cardAdded=_cardAdded - In the implementation block
@property (nonatomic,retain) PKPaymentPass * provisionedPass; //@synthesize provisionedPass=_provisionedPass - In the implementation block
@property (nonatomic,retain) NSError * error; //@synthesize error=_error - In the implementation block
-(NSError *)error;
-(void)setError:(NSError *)arg1 ;
-(void)setProvisionedPass:(PKPaymentPass *)arg1 ;
-(PKPaymentPass *)provisionedPass;
-(id)initWithRequestContext:(id)arg1 ;
-(id)description;
-(void)setCardAdded:(BOOL)arg1 ;
-(BOOL)cardAdded;
@end
| 38.382353 | 151 | 0.750958 |
dd7b82026ed20c86d746037acf6c33720ec864f7 | 540 | c | C | main.c | mscofield0/c-container-iteration | 734aa1cdf45f0f2430542cad2752af4d739affcc | [
"MIT"
] | null | null | null | main.c | mscofield0/c-container-iteration | 734aa1cdf45f0f2430542cad2752af4d739affcc | [
"MIT"
] | null | null | null | main.c | mscofield0/c-container-iteration | 734aa1cdf45f0f2430542cad2752af4d739affcc | [
"MIT"
] | null | null | null | #include <stdio.h>
#define FOR($Ty, $Container) \
for($Ty* it = ($Container).data; \
it != ($Container).data + ($Container).size; \
++it)
#define FOR_REVERSE($Ty, $Container) \
for($Ty* it = ($Container).data + ($Container).size - 1; \
it != ($Container).data - 1; \
--it)
#define FOR_ITER($Ty, $IterBegin, $IterEnd) \
for($Ty* it = ($IterBegin); \
it != ($IterEnd); \
++it)
#define FOR_ITER_REVERSE($Ty, $IterBegin, $IterEnd) \
for($Ty* it = ($IterBegin); \
it != ($IterEnd) - 1; \
--it)
int main() {
return 0;
}
| 20.769231 | 59 | 0.562963 |
1f9317d79646ef44b63c1eb28f154fb3201212f4 | 1,015 | h | C | impl/renderer/render_frame_observer_efl.h | isabella232/chromium-efl | db2d09aba6498fb09bbea1f8440d071c4b0fde78 | [
"BSD-3-Clause"
] | 9 | 2015-04-09T20:22:08.000Z | 2021-03-17T08:34:56.000Z | impl/renderer/render_frame_observer_efl.h | crosswalk-project/chromium-efl | db2d09aba6498fb09bbea1f8440d071c4b0fde78 | [
"BSD-3-Clause"
] | 2 | 2015-02-04T13:41:12.000Z | 2015-05-25T14:00:40.000Z | impl/renderer/render_frame_observer_efl.h | isabella232/chromium-efl | db2d09aba6498fb09bbea1f8440d071c4b0fde78 | [
"BSD-3-Clause"
] | 14 | 2015-02-12T16:20:47.000Z | 2022-01-20T10:36:26.000Z | // Copyright 2014 Samsung Electronics. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef RENDER_FRAME_OBSERVER_EFL_H_
#define RENDER_FRAME_OBSERVER_EFL_H_
#include <vector>
#include "content/public/renderer/render_frame_observer.h"
namespace blink {
class WebElement;
}
namespace content {
class RenderFrame;
class RenderFrameImpl;
class RenderFrameObserverEfl : public RenderFrameObserver {
public:
explicit RenderFrameObserverEfl(RenderFrame* render_frame);
virtual ~RenderFrameObserverEfl();
// IPC::Listener implementation.
bool OnMessageReceived(const IPC::Message& message) override;
private:
#if defined(OS_TIZEN)
void OnSelectPopupMenuItems(bool canceled,
const std::vector<int>& selected_indices);
void OnClosePopupMenu();
#endif
void OnMovePreviousSelectElement();
void OnMoveNextSelectElement();
};
} // namespace content
#endif // RENDER_FRAME_OBSERVER_EFL_H_
| 24.166667 | 73 | 0.768473 |
dd62bf33f96fdf89c7c4a336bb8b583669ef70c3 | 7,501 | h | C | include/simppl/typelist.h | edwardoid/simppl | 171df5f4670f2c44030e070756ab75c5d8ac496a | [
"MIT"
] | 50 | 2016-04-16T10:09:33.000Z | 2022-03-09T05:53:05.000Z | include/simppl/typelist.h | edwardoid/simppl | 171df5f4670f2c44030e070756ab75c5d8ac496a | [
"MIT"
] | 12 | 2016-09-26T12:58:59.000Z | 2021-01-28T09:16:08.000Z | include/simppl/typelist.h | edwardoid/simppl | 171df5f4670f2c44030e070756ab75c5d8ac496a | [
"MIT"
] | 19 | 2017-04-06T20:01:19.000Z | 2022-03-26T02:34:35.000Z | #ifndef SIMPPL_TYPELIST_H
#define SIMPPL_TYPELIST_H
#include <type_traits>
#include "simppl/type_wrappers.h"
namespace simppl
{
struct NilType {};
template<typename HeadT, typename TailT>
struct TypeList
{
typedef HeadT head_type;
typedef TailT tail_type;
};
// ---------------------------------- size ------------------------------------------
/// calculate the size of a given typelist
template<typename ListT>
struct Size;
template<typename HeadT, typename TailT>
struct Size<TypeList<HeadT, TailT> >
{
enum { value = Size<TailT>::value + 1 };
};
template<typename HeadT>
struct Size<TypeList<HeadT, NilType> >
{
enum { value = 1 };
};
// -------------------------------popfrontN ------------------------------------
template<int N, typename ListT>
struct PopFrontN;
template<int N, typename HeadT, typename TailT>
struct PopFrontN<N, TypeList<HeadT, TailT> >
{
typedef typename PopFrontN<N-1, TailT>::type type;
};
template<typename HeadT, typename TailT>
struct PopFrontN<0, TypeList<HeadT, TailT> >
{
typedef TypeList<HeadT, TailT> type;
};
template<int N>
struct PopFrontN<N, NilType>
{
typedef NilType type;
};
// ------------------------------ push front -------------------------------------
template<typename ListT, typename InsertT>
struct PushFront
{
typedef TypeList<InsertT, ListT> type;
};
// a NOOP
template<typename ListT>
struct PushFront<ListT, NilType>
{
typedef ListT type;
};
// ------------------------------- pop back ------------------------------------
template<typename ListT>
struct PopBack;
template<typename HeadT, typename TailT>
struct PopBack<TypeList<HeadT, TailT> >
{
typedef TypeList<HeadT, typename PopBack<TailT>::type> type;
};
template<typename HeadT>
struct PopBack<TypeList<HeadT, NilType> >
{
typedef NilType type;
};
template<>
struct PopBack<NilType>
{
typedef NilType type;
};
// --------------------------------------- back ------------------------------------------------
template<typename ListT>
struct Back;
template<typename T, typename ListT>
struct Back<TypeList<T, ListT> >
{
typedef typename Back<ListT>::type type;
};
template<typename T>
struct Back<TypeList<T, NilType> >
{
typedef T type;
};
// --------------------------------------- find ------------------------------------------------
// forward decl
template<typename SearchT, typename ListT, int N=0>
struct Find;
template<typename SearchT, typename HeadT, typename TailT, int N>
struct Find<SearchT, TypeList<HeadT, TailT>, N>
{
typedef typename std::conditional<(int)std::is_same<SearchT, HeadT>::value, std::integral_constant<int, N>, Find<SearchT, TailT, N+1> >::type type_;
static const int value = type_::value;
};
template<typename SearchT, typename HeadT, int N>
struct Find<SearchT, TypeList<HeadT, NilType>, N>
{
typedef typename std::conditional<(int)std::is_same<SearchT, HeadT>::value, std::integral_constant<int, N>, std::integral_constant<int, -1> >::type type_;
static const int value = type_::value;
};
template<typename SearchT, int N>
struct Find<SearchT, NilType, N>
{
enum { value = -1 };
};
// -------------------------------- type at -------------------------------------------
/// extract type at given position in typelist; position must be within bounds
template<int N, typename ListT>
struct TypeAt;
template<int N, typename HeadT, typename TailT>
struct TypeAt<N, TypeList<HeadT, TailT> >
{
typedef typename TypeAt<N-1, TailT>::type type;
typedef const typename TypeAt<N-1, TailT>::type const_type;
};
template<typename HeadT, typename TailT>
struct TypeAt<0, TypeList<HeadT, TailT> >
{
typedef HeadT type;
typedef const HeadT const_type;
};
// ------------------- type at (relaxed, does not matter if boundary was crossed) ---------------------
/// extract type at given position in typelist; if position is out of
/// typelist bounds it always returns the type NilType
template<int N, typename ListT>
struct RelaxedTypeAt;
template<int N>
struct RelaxedTypeAt<N, NilType>
{
typedef NilType type; ///< save access over end of typelist
typedef const NilType const_type;
};
template<int N, typename HeadT, typename TailT>
struct RelaxedTypeAt<N, TypeList<HeadT, TailT> >
{
typedef typename RelaxedTypeAt<N-1, TailT>::type type;
typedef const typename RelaxedTypeAt<N-1, TailT>::type const_type;
};
template<typename HeadT, typename TailT>
struct RelaxedTypeAt<0, TypeList<HeadT, TailT> >
{
typedef HeadT type;
typedef const HeadT const_type;
};
// --------------------------- reverse the sequence ------------------------------------
namespace detail
{
template<typename ListT, int N>
struct ReverseHelper
{
typedef TypeList<typename TypeAt<N - 1, ListT>::type, typename ReverseHelper<ListT, N - 1>::type> type;
};
template<typename ListT>
struct ReverseHelper<ListT, 1>
{
typedef TypeList<typename TypeAt<0, ListT>::type, NilType> type;
};
} // namespace detail
/// reverse the sequence
template<typename ListT>
struct Reverse
{
typedef typename detail::ReverseHelper<ListT, Size<ListT>::value>::type type;
};
// ------------------------ Count a certain type within the typelist ---------------------------------
template<typename SearchT, typename ListT>
struct Count;
template<typename SearchT, typename HeadT, typename TailT>
struct Count<SearchT, TypeList<HeadT, TailT> >
{
enum { value = std::is_same<SearchT, HeadT>::value + Count<SearchT, TailT>::value };
};
template<typename SearchT>
struct Count<SearchT, NilType>
{
enum { value = 0 };
};
// --------------------------- make a typelist (C++11) ------------------------------------
template<typename... T>
struct make_typelist;
template<typename T1, typename... T>
struct make_typelist<T1, T...>
{
typedef TypeList<T1, typename make_typelist<T...>::type> type;
};
template<>
struct make_typelist<>
{
typedef TypeList<NilType, NilType> type;
};
template<typename T>
struct make_typelist<T>
{
typedef TypeList<T, NilType> type;
};
// ---------------------------- all of ---------------------------------
template<typename TL, typename FuncT>
struct AllOf;
template<typename HeadT, typename TailT, typename FuncT>
struct AllOf<TypeList<HeadT, TailT>, FuncT>
{
enum { value = FuncT::template apply_<HeadT>::value && AllOf<TailT, FuncT>::value };
};
template<typename HeadT, typename FuncT>
struct AllOf<TypeList<HeadT, NilType>, FuncT>
{
enum { value = FuncT::template apply_<HeadT>::value };
};
template<typename FuncT>
struct AllOf<TypeList<NilType, NilType>, FuncT>
{
enum { value = true };
};
// ------------------ transform to other type --------------------------
template<typename ListT, typename FuncT>
struct transform;
template<typename HeadT, typename TailT, typename FuncT>
struct transform<TypeList<HeadT, TailT>, FuncT>
{
typedef TypeList<typename FuncT::template apply_<HeadT>::type, typename transform<TailT, FuncT>::type> type;
};
template<typename HeadT, typename FuncT>
struct transform<TypeList<HeadT, NilType>, FuncT>
{
typedef TypeList<typename FuncT::template apply_<HeadT>::type, NilType> type;
};
} // namespace simppl
#endif // SIMPPL_TYPELIST_H
| 24.593443 | 159 | 0.610852 |
1c05528529896677a3d79ad2a0d19b835ab489d0 | 1,379 | c | C | Search3.c | MBadriNarayanan/DataStructuresLab | 5c53442b16677282fb0cf18932644c9661032084 | [
"MIT"
] | null | null | null | Search3.c | MBadriNarayanan/DataStructuresLab | 5c53442b16677282fb0cf18932644c9661032084 | [
"MIT"
] | 1 | 2020-07-09T20:31:45.000Z | 2020-07-09T20:31:45.000Z | Search3.c | MBadriNarayanan/DataStructures | 5c53442b16677282fb0cf18932644c9661032084 | [
"MIT"
] | null | null | null | #include"Search1.h"
int main()
{
Array a,*p;
int option,temp;
option=temp=0;
any datatobesearched;
do
{
printf("\n\n\n Searching \n\n\n");
printf(" 1. Linear Search \n\n");
printf(" 2. Binary Search \n\n");
printf(" 3. Exit \n\n");
printf(" Enter Your Choice : ");
scanf("%d",&option);
switch(option)
{
case 1 :
{
printf("\n\n Linear Search \n\n");
p=input(&a);
temp=display(&a);
printf(" Enter Data To Be Searched : ");
scanf("%d",&datatobesearched);
temp=linearsearch(&a,datatobesearched);
break;
}
case 2 :
{
printf("\n\n Binary Search \n\n");
p=input(&a);
temp=display(&a);
printf(" Enter Data To Be Searched : ");
scanf("%d",&datatobesearched);
for(int i=0;i<p->size;i++)
{
for(int j=0;j<p->size-i-1;j++)
{
if(p->data[j]>p->data[j+1])
{
any t=p->data[j];
p->data[j]=p->data[j+1];
p->data[j+1]=t;
}
}
}
printf("\n\n Displaying The Sorted Array \n\n");
temp=display(p);
temp=binarysearch(p,datatobesearched);
break;
}
}
printf(" Do You Want To Continue (Type 0 Or 1) : ") ;
scanf("%d",&option);
}while(option);
return 0;
} | 23.775862 | 58 | 0.469906 |
e13659d021d95486a5463e2b5bd7239cc809c9eb | 8,579 | c | C | netbsd/sys/compat/irix/irix_prctl.c | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 91 | 2015-01-05T15:18:31.000Z | 2022-03-11T16:43:28.000Z | netbsd/sys/compat/irix/irix_prctl.c | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 1 | 2016-02-25T15:57:55.000Z | 2016-02-25T16:01:02.000Z | netbsd/sys/compat/irix/irix_prctl.c | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 21 | 2015-02-07T08:23:07.000Z | 2021-12-14T06:01:49.000Z | /* $NetBSD: irix_prctl.c,v 1.9 2002/05/02 17:17:29 manu Exp $ */
/*-
* Copyright (c) 2001-2002 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Emmanuel Dreyfus.
*
* 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: irix_prctl.c,v 1.9 2002/05/02 17:17:29 manu Exp $");
#include <sys/errno.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/signal.h>
#include <sys/systm.h>
#include <sys/exec.h>
#include <sys/resourcevar.h>
#include <uvm/uvm_extern.h>
#include <machine/regnum.h>
#include <machine/vmparam.h>
#include <compat/svr4/svr4_types.h>
#include <compat/irix/irix_types.h>
#include <compat/irix/irix_prctl.h>
#include <compat/irix/irix_signal.h>
#include <compat/irix/irix_syscallargs.h>
struct irix_sproc_child_args {
struct proc **isc_proc;
void *isc_entry;
void *isc_arg;
void *isc_aux;
};
static void irix_sproc_child __P((struct irix_sproc_child_args *));
static int irix_sproc __P((void *, unsigned int, void *, caddr_t, size_t,
pid_t, struct proc *, register_t *));
int
irix_sys_prctl(p, v, retval)
struct proc *p;
void *v;
register_t *retval;
{
struct irix_sys_prctl_args /* {
syscallarg(int) option;
syscallarg(void *) arg1;
} */ *uap = v;
int option = SCARG(uap, option);
#ifdef DEBUG_IRIX
printf("irix_sys_prctl(): option = %d\n", option);
#endif
switch(option) {
case IRIX_PR_GETSHMASK: { /* Get shared resources */
struct proc *p2;
int shmask = 0;
p2 = pfind((pid_t)SCARG(uap, arg1));
if (p2 == p || SCARG(uap, arg1) == 0) {
/* XXX return our own shmask */
return 0;
}
if (p2 == NULL)
return EINVAL;
if (p->p_vmspace == p2->p_vmspace)
shmask |= IRIX_PR_SADDR;
if (p->p_fd == p2->p_fd)
shmask |= IRIX_PR_SFDS;
if (p->p_cwdi == p2->p_cwdi);
shmask |= IRIX_PR_SDIR;
*retval = (register_t)shmask;
return 0;
break;
}
case IRIX_PR_LASTSHEXIT: /* "Last sproc exit" */
/* We do nothing */
break;
case IRIX_PR_GETNSHARE: /* Number of sproc share group memb.*/
/* XXX This only gives threads that share VM space ... */
*retval = p->p_vmspace->vm_refcnt;
break;
case IRIX_PR_TERMCHILD: /* Send SIGHUP to parrent on exit */
p->p_exitsig = SIGHUP;
*retval = 0;
break;
default:
printf("Warning: call to unimplemented prctl() command %d\n",
option);
return EINVAL;
break;
}
return 0;
}
int
irix_sys_pidsprocsp(p, v, retval)
struct proc *p;
void *v;
register_t *retval;
{
struct irix_sys_pidsprocsp_args /* {
syscallarg(void *) entry;
syscallarg(unsigned) inh;
syscallarg(void *) arg;
syscallarg(caddr_t) sp;
syscallarg(irix_size_t) len;
syscallarg(irix_pid_t) pid;
} */ *uap = v;
/* pid is ignored for now */
printf("Warning: unsupported pid argument to IRIX sproc\n");
return irix_sproc(SCARG(uap, entry), SCARG(uap, inh), SCARG(uap, arg),
SCARG(uap, sp), SCARG(uap, len), SCARG(uap, pid), p, retval);
}
int
irix_sys_sprocsp(p, v, retval)
struct proc *p;
void *v;
register_t *retval;
{
struct irix_sys_sprocsp_args /* {
syscallarg(void *) entry;
syscallarg(unsigned) inh;
syscallarg(void *) arg;
syscallarg(caddr_t) sp;
syscallarg(irix_size_t) len;
} */ *uap = v;
return irix_sproc(SCARG(uap, entry), SCARG(uap, inh), SCARG(uap, arg),
SCARG(uap, sp), SCARG(uap, len), 0, p, retval);
}
int
irix_sys_sproc(p, v, retval)
struct proc *p;
void *v;
register_t *retval;
{
struct irix_sys_sproc_args /* {
syscallarg(void *) entry;
syscallarg(unsigned) inh;
syscallarg(void *) arg;
} */ *uap = v;
return irix_sproc(SCARG(uap, entry), SCARG(uap, inh), SCARG(uap, arg),
NULL, 0, 0, p, retval);
}
static int irix_sproc(entry, inh, arg, sp, len, pid, p, retval)
void *entry;
unsigned int inh;
void *arg;
caddr_t sp;
size_t len;
pid_t pid;
struct proc *p;
register_t *retval;
{
int bsd_flags = 0;
struct exec_vmcmd vmc;
struct frame *tf = (struct frame *)p->p_md.md_regs;
int error;
struct proc *p2;
struct irix_sproc_child_args isc;
#ifdef DEBUG_IRIX
printf("irix_sproc(): entry = %p, inh = %d, arg = %p, sp = 0x%08lx, len = 0x%08lx, pid = %d\n", entry, inh, arg, (u_long)sp, (u_long)len, pid);
#endif
if (inh & IRIX_PR_SADDR)
bsd_flags |= FORK_SHAREVM;
if (inh & IRIX_PR_SFDS)
bsd_flags |= FORK_SHAREFILES;
if (inh & IRIX_PR_SDIR)
bsd_flags |= FORK_SHARECWD;
if (inh & IRIX_PR_SUMASK)
printf("Warning: unimplemented IRIX sproc flag PR_SUMASK\n");
if (inh & IRIX_PR_SULIMIT)
printf("Warning: unimplemented IRIX sproc flag PR_SULIMIT\n");
if (inh & IRIX_PR_SID)
printf("Warning: unimplemented IRIX sproc flag PR_SID\n");
/*
* Setting up child stack
*/
if (inh & IRIX_PR_SADDR) {
if (len == 0)
len = p->p_rlimit[RLIMIT_STACK].rlim_cur;
if (sp == NULL)
sp = (caddr_t)(round_page(tf->f_regs[SP])
- IRIX_SPROC_STACK_OFFSET - len);
while (trunc_page((u_long)sp) >=
(u_long)p->p_vmspace->vm_maxsaddr)
sp -= IRIX_SPROC_STACK_OFFSET;
bzero(&vmc, sizeof(vmc));
vmc.ev_addr = trunc_page((u_long)sp);
vmc.ev_len = round_page(len);
vmc.ev_prot = UVM_PROT_RWX;
vmc.ev_flags = UVM_FLAG_COPYONW|UVM_FLAG_FIXED|UVM_FLAG_OVERLAY;
vmc.ev_proc = vmcmd_map_zero;
#ifdef DEBUG_IRIX
printf("irix_sproc(): new stack addr=0x%08lx, len=0x%08lx\n",
(u_long)sp, (u_long)len);
#endif
if ((error = (*vmc.ev_proc)(p, &vmc)) != 0)
return error;
p->p_vmspace->vm_maxsaddr = (void *)trunc_page((u_long)sp);
}
/*
* Arguments for irix_sproc_child()
*/
isc.isc_proc = &p2;
isc.isc_entry = entry;
isc.isc_arg = arg;
if ((error = copyin((void *)(tf->f_regs[SP] + 28),
&isc.isc_aux, sizeof(isc.isc_aux))) != 0)
isc.isc_aux = 0;
if ((error = fork1(p, bsd_flags, SIGCHLD, (void *)sp, len,
(void *)irix_sproc_child, (void *)&isc, retval, &p2)) != 0)
return error;
/*
* Some local variables are referenced in irix_sproc_child()
* through isc. We need to ensure the child does not use them
* anymore before leaving.
*/
(void)ltsleep((void *)&isc, 0, "sproc", 0, NULL);
retval[0] = (register_t)p2->p_pid;
retval[1] = 0;
return 0;
}
static void
irix_sproc_child(isc)
struct irix_sproc_child_args *isc;
{
struct proc *p2 = *isc->isc_proc;
struct frame *tf = (struct frame *)p2->p_md.md_regs;
/*
* Setup PC to return to the child entry point
*/
tf->f_regs[PC] = (unsigned long)isc->isc_entry;
/*
* Setup child arguments
* The libc stub will copy S3 to A1 once we return to userland.
*/
tf->f_regs[A0] = (unsigned long)isc->isc_arg;
tf->f_regs[A1] = (unsigned long)isc->isc_aux;
tf->f_regs[S3] = (unsigned long)isc->isc_aux;
/*
* We do not need isc anymore, we can wakeup our parent
*/
wakeup((void *)isc);
/*
* Return to userland for a newly created process
*/
child_return((void *)p2);
return;
}
| 27.148734 | 144 | 0.687726 |
7cf2d426d193d5e684af0eca721123924033dfff | 335 | h | C | OpenPEARL/openpearl-code/runtime/lpc1768/lpc17_interruptState.h | BenniN/OpenPEARLThesis | d7db83b0ea15b7ba0f6244d918432c830ddcd697 | [
"Apache-2.0"
] | 1 | 2020-09-15T07:26:00.000Z | 2020-09-15T07:26:00.000Z | OpenPEARL/openpearl-code/runtime/lpc1768/lpc17_interruptState.h | BenniN/OpenPEARLThesis | d7db83b0ea15b7ba0f6244d918432c830ddcd697 | [
"Apache-2.0"
] | null | null | null | OpenPEARL/openpearl-code/runtime/lpc1768/lpc17_interruptState.h | BenniN/OpenPEARLThesis | d7db83b0ea15b7ba0f6244d918432c830ddcd697 | [
"Apache-2.0"
] | null | null | null | /**
\file
\brief test the interrupt state
This method works for all ARM-Cortex-M processors
*/
#include "chip.h"
/**
check the current interrupt state
\returns 0, if not in interrupt service
1, if interrupt is active
*/
static inline int lpc17_isInterrupt()
{
return (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) != 0 ;
}
| 14.565217 | 55 | 0.692537 |
9104553b178510984346b07df76022db586b82ef | 466 | h | C | AbstractInterfaceExample/AbstractInterface.h | bilaleluneis/AbstractInterfaceExample | e4cdb6bb2cf9919f9e5a3b836adb5744376599be | [
"Apache-2.0"
] | null | null | null | AbstractInterfaceExample/AbstractInterface.h | bilaleluneis/AbstractInterfaceExample | e4cdb6bb2cf9919f9e5a3b836adb5744376599be | [
"Apache-2.0"
] | null | null | null | AbstractInterfaceExample/AbstractInterface.h | bilaleluneis/AbstractInterfaceExample | e4cdb6bb2cf9919f9e5a3b836adb5744376599be | [
"Apache-2.0"
] | null | null | null | //
// AbstractInterface.h
// AbstractInterfaceExample
//
// Created by Bilal El Uneis on 1/13/15.
// Copyright (c) 2015 Bilal El Uneis. All rights reserved.
//
#ifndef AbstractInterfaceExample_AbstractInterface_h
#define AbstractInterfaceExample_AbstractInterface_h
@import Foundation;
@interface AbstractInterface : NSObject
#pragma mark must override those methods in Sub Interface
-(void) methodToOverride;
-(int) anotherMethodToOverride;
@end
#endif
| 19.416667 | 59 | 0.783262 |
9187cdaf47f576cc466a15ca4deb526a243322d3 | 2,737 | c | C | src/command/backup/common.c | srikanth-medikonda/pgbackrest | 51d67ce1ba932476b2349dbe611f77ab4f15213d | [
"MIT"
] | null | null | null | src/command/backup/common.c | srikanth-medikonda/pgbackrest | 51d67ce1ba932476b2349dbe611f77ab4f15213d | [
"MIT"
] | null | null | null | src/command/backup/common.c | srikanth-medikonda/pgbackrest | 51d67ce1ba932476b2349dbe611f77ab4f15213d | [
"MIT"
] | null | null | null | /***********************************************************************************************************************************
Common Functions and Definitions for Backup and Expire Commands
***********************************************************************************************************************************/
#include "build.auto.h"
#include "command/backup/common.h"
#include "common/debug.h"
#include "common/log.h"
/***********************************************************************************************************************************
Constants
***********************************************************************************************************************************/
#define DATE_TIME_REGEX "[0-9]{8}\\-[0-9]{6}"
/***********************************************************************************************************************************
Returns an anchored regex string for filtering backups based on the type (at least one type is required to be true)
***********************************************************************************************************************************/
String *
backupRegExp(BackupRegExpParam param)
{
FUNCTION_LOG_BEGIN(logLevelTrace);
FUNCTION_LOG_PARAM(BOOL, param.full);
FUNCTION_LOG_PARAM(BOOL, param.differential);
FUNCTION_LOG_PARAM(BOOL, param.incremental);
FUNCTION_LOG_END();
ASSERT(param.full || param.differential || param.incremental);
String *result = NULL;
// Start the expression with the anchor, date/time regexp and full backup indicator
result = strNew("^" DATE_TIME_REGEX "F");
// Add the diff and/or incr expressions if requested
if (param.differential || param.incremental)
{
// If full requested then diff/incr is optional
if (param.full)
{
strCat(result, "(\\_");
}
// Else diff/incr is required
else
{
strCat(result, "\\_");
}
// Append date/time regexp for diff/incr
strCat(result, DATE_TIME_REGEX);
// Filter on both diff/incr
if (param.differential && param.incremental)
{
strCat(result, "(D|I)");
}
// Else just diff
else if (param.differential)
{
strCatChr(result, 'D');
}
// Else just incr
else
{
strCatChr(result, 'I');
}
// If full requested then diff/incr is optional
if (param.full)
{
strCat(result, "){0,1}");
}
}
// Append the end anchor
strCat(result, "$");
FUNCTION_LOG_RETURN(STRING, result);
}
| 34.64557 | 132 | 0.411765 |
562279ba99bdc9f85632585a05722b610376c7e6 | 724 | h | C | src/include/writepackets.h | wanderingThroughSpaceAndTime/HaxBall | fc6a3e490a7c043cdbc9ec9018a8c7da23d14574 | [
"MIT"
] | null | null | null | src/include/writepackets.h | wanderingThroughSpaceAndTime/HaxBall | fc6a3e490a7c043cdbc9ec9018a8c7da23d14574 | [
"MIT"
] | null | null | null | src/include/writepackets.h | wanderingThroughSpaceAndTime/HaxBall | fc6a3e490a7c043cdbc9ec9018a8c7da23d14574 | [
"MIT"
] | null | null | null | #ifndef WRITEPACKETS_H
#define WRITEPACKETS_H
#include <iostream>
#include <vector>
#include <string>
#include "helperfunc.h"
#include "variables.h"
#include "Positions.h"
string writepeer_Firstpacket(string playername,string ip,int port);
string writehost_firstpacket(vector<peerdata> gamers);
string writepacket_startgame();
string writepacket_goal(int left,int right);
string writepacket_endgame();
string writepacket_random();
string writepacket_gamestate(vector<Position> input,int pos);
string writepacket_message(string input);
string writepacket_hostdrag(vector<peerdata> gamers);
string writepacket_ballpos(vector<Position> input);
string writepacket_disconnect(int input);
#endif // WRITEPACKETS_H
| 20.111111 | 67 | 0.80663 |
f0b61bfc513e6baf9fb1344da7de352d2aecd38b | 1,255 | h | C | src/ui/droplist.h | chys87/tiary | 09ed92b488cdc9cbf6ece016efe8f6fd99debc1d | [
"BSD-3-Clause"
] | null | null | null | src/ui/droplist.h | chys87/tiary | 09ed92b488cdc9cbf6ece016efe8f6fd99debc1d | [
"BSD-3-Clause"
] | null | null | null | src/ui/droplist.h | chys87/tiary | 09ed92b488cdc9cbf6ece016efe8f6fd99debc1d | [
"BSD-3-Clause"
] | null | null | null | // -*- mode:c++; tab-width:4; -*-
// vim:ft=cpp ts=4
/***************************************************************************
*
* Tiary, a terminal-based diary keeping system for Unix-like systems
* Copyright (C) 2009, 2018, 2019, chys <admin@CHYS.INFO>
*
* This software is licensed under the 3-clause BSD license.
* See LICENSE in the source package and/or online info for details.
*
**************************************************************************/
#ifndef TIARY_UI_DROPLIST_H
#define TIARY_UI_DROPLIST_H
#include "ui/control.h"
#include <vector>
namespace tiary {
namespace ui {
class DropList final : public Control {
public:
typedef std::vector<std::wstring> ItemList;
DropList (Window &, const ItemList &, size_t default_select);
DropList (Window &, ItemList &&, size_t default_select);
~DropList ();
size_t get_select() const { return select_; }
const ItemList &get_items() const { return items_; }
void set_select (size_t, bool emit_signal = true);
// Implement virtual functions
bool on_key (wchar_t);
bool on_mouse (MouseEvent);
void redraw ();
Signal sig_select_changed;
private:
const ItemList items_;
size_t select_;
};
} // namespace tiary::ui
} // namespace tiary
#endif // include guard
| 23.240741 | 76 | 0.627888 |
21914b659e9b197f9cc80d8bbab1a6c43cbacf06 | 231 | h | C | Classes/RootViewController.h | endemic/4iro | 0de6359b33944008d89666c399831c4e029864a4 | [
"MIT"
] | null | null | null | Classes/RootViewController.h | endemic/4iro | 0de6359b33944008d89666c399831c4e029864a4 | [
"MIT"
] | null | null | null | Classes/RootViewController.h | endemic/4iro | 0de6359b33944008d89666c399831c4e029864a4 | [
"MIT"
] | null | null | null | //
// RootViewController.h
// Yotsu Iro
//
// Created by Nathan Demick on 4/13/11.
// Copyright Ganbaru Games 2011. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface RootViewController : UIViewController {
}
@end
| 13.588235 | 54 | 0.692641 |
14dbc69af393d7dae9ba9c73ada8dd1ff8e59cb8 | 1,917 | h | C | components/no_state_prefetch/browser/no_state_prefetch_manager_delegate.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/no_state_prefetch/browser/no_state_prefetch_manager_delegate.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | components/no_state_prefetch/browser/no_state_prefetch_manager_delegate.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_NO_STATE_PREFETCH_BROWSER_NO_STATE_PREFETCH_MANAGER_DELEGATE_H_
#define COMPONENTS_NO_STATE_PREFETCH_BROWSER_NO_STATE_PREFETCH_MANAGER_DELEGATE_H_
#include "base/memory/scoped_refptr.h"
#include "components/no_state_prefetch/browser/no_state_prefetch_contents_delegate.h"
#include "components/no_state_prefetch/common/prerender_origin.h"
#include "url/gurl.h"
namespace content_settings {
class CookieSettings;
}
namespace prerender {
// NoStatePrefetchManagerDelegate allows content embedders to override
// NoStatePrefetchManager logic.
class NoStatePrefetchManagerDelegate {
public:
NoStatePrefetchManagerDelegate();
virtual ~NoStatePrefetchManagerDelegate() = default;
// Checks whether third party cookies should be blocked.
virtual scoped_refptr<content_settings::CookieSettings>
GetCookieSettings() = 0;
// Perform preconnect, if feasible.
virtual void MaybePreconnect(const GURL& url);
// Get the prerender contents delegate.
virtual std::unique_ptr<NoStatePrefetchContentsDelegate>
GetNoStatePrefetchContentsDelegate() = 0;
// Check whether the user has enabled predictive loading of web pages.
virtual bool IsNetworkPredictionPreferenceEnabled();
// Check whether predictive loading of web pages is disabled due to network.
// TODO(crbug.com/1121970): Remove this condition once we're no longer running
// the experiment "PredictivePrefetchingAllowedOnAllConnectionTypes".
virtual bool IsPredictionDisabledDueToNetwork(Origin origin);
// Gets the reason why predictive loading of web pages was disabld.
virtual std::string GetReasonForDisablingPrediction();
};
} // namespace prerender
#endif // COMPONENTS_NO_STATE_PREFETCH_BROWSER_NO_STATE_PREFETCH_MANAGER_DELEGATE_H_
| 36.865385 | 85 | 0.815858 |
619f750d8f3fba7b39e09ce2f7f7075520e4ea22 | 54,760 | c | C | tests/testgpimage.c | 1996v/libgdiplus | a6b4c3bbf54f8665e967b2e539c8e7a11adb8020 | [
"MIT"
] | 234 | 2015-01-06T09:25:22.000Z | 2022-03-31T09:59:10.000Z | tests/testgpimage.c | 1996v/libgdiplus | a6b4c3bbf54f8665e967b2e539c8e7a11adb8020 | [
"MIT"
] | 520 | 2015-01-14T18:58:34.000Z | 2022-03-08T16:14:53.000Z | tests/testgpimage.c | 1996v/libgdiplus | a6b4c3bbf54f8665e967b2e539c8e7a11adb8020 | [
"MIT"
] | 132 | 2015-01-14T17:56:39.000Z | 2022-03-21T01:29:08.000Z | #ifdef WIN32
#ifndef __cplusplus
#error Please compile with a C++ compiler.
#endif
#endif
#if defined(USE_WINDOWS_GDIPLUS)
#include <Windows.h>
#include <GdiPlus.h>
#pragma comment(lib, "gdiplus.lib")
#else
#include <GdiPlusFlat.h>
#endif
#if defined(USE_WINDOWS_GDIPLUS)
using namespace Gdiplus;
using namespace DllExports;
#endif
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "testhelpers.h"
static GpImage* getImage (const char* fileName) {
GpStatus status;
WCHAR *wFileName = wcharFromChar (fileName);
GpImage *image;
status = GdipLoadImageFromFile (wFileName, &image);
assertEqualInt (status, Ok);
freeWchar (wFileName);
return image;
}
static void test_loadImageFromStream ()
{
GpStatus status;
GpImage *image;
// Negative tests.
status = GdipLoadImageFromStream (NULL, &image);
assertEqualInt (status, InvalidParameter);
#if !defined(USE_WINDOWS_GDIPLUS)
int temp = 0;
status = GdipLoadImageFromStream (&temp, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipLoadImageFromStream (&temp, &image);
assertEqualInt (status, NotImplemented);
#endif
}
static void test_loadImageFromFile ()
{
GpStatus status;
GpImage *image;
WCHAR *noSuchFile = createWchar ("noSuchFile.bmp");
WCHAR *invalidFile = createWchar ("test.ttf");
// Negative tests.
status = GdipLoadImageFromFile (NULL, &image);
assertEqualInt (status, InvalidParameter);
status = GdipLoadImageFromFile (noSuchFile, &image);
assertEqualInt (status, OutOfMemory);
status = GdipLoadImageFromFile (invalidFile, &image);
assertEqualInt (status, OutOfMemory);
status = GdipLoadImageFromFile (noSuchFile, NULL);
assertEqualInt (status, InvalidParameter);
freeWchar (noSuchFile);
freeWchar (invalidFile);
}
static void test_loadImageFromStreamICM ()
{
GpStatus status;
GpImage *image;
// Negative tests.
status = GdipLoadImageFromStreamICM (NULL, &image);
assertEqualInt (status, InvalidParameter);
#if !defined(USE_WINDOWS_GDIPLUS)
int temp = 0;
status = GdipLoadImageFromStreamICM (&temp, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipLoadImageFromStreamICM (&temp, &image);
assertEqualInt (status, NotImplemented);
#endif
}
static void test_loadImageFromFileICM ()
{
GpStatus status;
GpImage *image;
WCHAR *noSuchFile = createWchar ("noSuchFile.bmp");
WCHAR *invalidFile = createWchar ("test.ttf");
// Negative tests.
status = GdipLoadImageFromFileICM (NULL, &image);
assertEqualInt (status, InvalidParameter);
status = GdipLoadImageFromFileICM (noSuchFile, &image);
assertEqualInt (status, OutOfMemory);
status = GdipLoadImageFromFileICM (invalidFile, &image);
assertEqualInt (status, OutOfMemory);
status = GdipLoadImageFromFileICM (noSuchFile, NULL);
assertEqualInt (status, InvalidParameter);
freeWchar (noSuchFile);
freeWchar (invalidFile);
}
static void test_loadImageFromFileTif ()
{
GpImage *image = getImage ("test.tif");
verifyBitmap (image, tifRawFormat, PixelFormat24bppRGB, 100, 68, ImageFlagsColorSpaceRGB | ImageFlagsHasRealDPI | ImageFlagsHasRealPixelSize | ImageFlagsReadOnly, 19, TRUE);
GdipDisposeImage (image);
}
static void test_loadImageFromFileGif ()
{
GpImage *image = getImage ("test.gif");
verifyBitmap (image, gifRawFormat, PixelFormat8bppIndexed, 100, 68, ImageFlagsColorSpaceRGB | ImageFlagsHasRealDPI | ImageFlagsHasRealPixelSize | ImageFlagsReadOnly, 4, TRUE);
GdipDisposeImage (image);
}
static void test_loadImageFromFilePng ()
{
GpImage *image = getImage ("test.png");
verifyBitmap (image, pngRawFormat, PixelFormat24bppRGB, 100, 68, ImageFlagsColorSpaceRGB | ImageFlagsHasRealDPI | ImageFlagsHasRealPixelSize | ImageFlagsReadOnly, 5, TRUE);
GdipDisposeImage (image);
}
static void test_loadImageFromFileJpg ()
{
GpImage *image = getImage ("test.jpg");
verifyBitmap (image, jpegRawFormat, PixelFormat24bppRGB, 100, 68, ImageFlagsColorSpaceRGB | ImageFlagsHasRealPixelSize | ImageFlagsReadOnly, 2, TRUE);
GdipDisposeImage (image);
}
static void test_loadImageFromFileIcon ()
{
GpImage *image = getImage ("test.ico");
verifyBitmap (image, icoRawFormat, PixelFormat32bppARGB, 48, 48, ImageFlagsColorSpaceRGB | ImageFlagsHasRealPixelSize | ImageFlagsHasAlpha | ImageFlagsReadOnly, 0, TRUE);
GdipDisposeImage (image);
}
static void test_loadImageFromFileWmf ()
{
GpImage *image = getImage ("test.wmf");
verifyMetafile (image, wmfRawFormat, -4008, -3378, 8016, 6756, 20360.638672f, 17160.2383f);
GdipDisposeImage (image);
}
static void test_loadImageFromFileEmf ()
{
GpImage *image = getImage ("test.emf");
verifyMetafile (image, emfRawFormat, 0, 0, 100, 100, 1944.444336f, 1888.888794f);
GdipDisposeImage (image);
}
static void test_cloneImage ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *jpgImage = getImage ("test.jpg");
GpImage *metafileImage = getImage ("test.wmf");
GpImage *clonedImage;
// ImageTypeBitmap - bmp.
status = GdipCloneImage (bitmapImage, &clonedImage);
assertEqualInt (status, Ok);
assert (clonedImage && clonedImage != bitmapImage);
verifyBitmap (clonedImage, bmpRawFormat, PixelFormat24bppRGB, 100, 68, ImageFlagsColorSpaceRGB | ImageFlagsHasRealDPI | ImageFlagsHasRealPixelSize | ImageFlagsReadOnly, 0, TRUE);
GdipDisposeImage (clonedImage);
// ImageTypeBitmap - jpg.
status = GdipCloneImage (jpgImage, &clonedImage);
assertEqualInt (status, Ok);
assert (clonedImage && clonedImage != jpgImage);
verifyBitmap (clonedImage, jpegRawFormat, PixelFormat24bppRGB, 100, 68, ImageFlagsColorSpaceRGB | ImageFlagsHasRealPixelSize | ImageFlagsReadOnly, 2, TRUE);
GdipDisposeImage (clonedImage);
// ImageTypeMetafile.
status = GdipCloneImage (metafileImage, &clonedImage);
assertEqualInt (status, Ok);
assert (clonedImage && clonedImage != metafileImage);
verifyMetafile (clonedImage, wmfRawFormat, -4008, -3378, 8016, 6756, 20360.638672f, 17160.238281f);
GdipDisposeImage (clonedImage);
// Negative tests.
status = GdipCloneImage (NULL, &clonedImage);
assertEqualInt (status, InvalidParameter);
status = GdipCloneImage (bitmapImage, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (jpgImage);
GdipDisposeImage (metafileImage);
}
static void test_disposeImage ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
// ImageTypeBitmap.
status = GdipDisposeImage (bitmapImage);
assertEqualInt (status, Ok);
// ImageTypeMetafile.
status = GdipDisposeImage (metafileImage);
assertEqualInt (status, Ok);
// Negative tests.
status = GdipDisposeImage (NULL);
assertEqualInt (status, InvalidParameter);
}
static void test_getImageGraphicsContext ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *gifImage = getImage ("test.gif");
GpImage *metafileImage = getImage ("test.wmf");
GpGraphics *graphics;
// ImageTypeBitmap - PixelFormat24Bpp.
status = GdipGetImageGraphicsContext (bitmapImage, &graphics);
assertEqualInt (status, Ok);
assert (graphics);
GdipDeleteGraphics (graphics);
// FIXME: libgdiplus doesn't support PixelFormat8bppIndexed.
#if defined(USE_WINDOWS_GDIPLUS)
// ImageTypeBitmap - PixelFormat8bppIndexed.
status = GdipGetImageGraphicsContext (gifImage, &graphics);
assertEqualInt (status, Ok);
assert (graphics);
GdipDeleteGraphics (graphics);
#endif
// ImageTypeMetafile - not recording.
status = GdipGetImageGraphicsContext (metafileImage, &graphics);
assertEqualInt (status, OutOfMemory);
// Negative tests.
status = GdipGetImageGraphicsContext (NULL, &graphics);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageGraphicsContext (bitmapImage, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (gifImage);
GdipDisposeImage (metafileImage);
}
static void test_getImageBounds ()
{
GpStatus status;
GpImage *image = getImage ("test.bmp");
GpRectF bounds;
Unit unit;
// Negative tests.
status = GdipGetImageBounds (NULL, &bounds, &unit);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageBounds (image, NULL, &unit);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageBounds (image, &bounds, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (image);
}
static void test_getImageDimension ()
{
GpStatus status;
GpImage *image = getImage ("test.bmp");
REAL dimensionWidth;
REAL dimensionHeight;
// Negative tests.
status = GdipGetImageDimension (NULL, &dimensionWidth, &dimensionHeight);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageDimension (image, NULL, &dimensionHeight);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageDimension (image, &dimensionWidth, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (image);
}
static void test_getImageType ()
{
GpStatus status;
GpImage *image = getImage ("test.bmp");
ImageType type;
// Negative tests.
status = GdipGetImageType (NULL, &type);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageType (image, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (image);
}
static void test_getImageWidth ()
{
GpStatus status;
GpImage *image = getImage ("test.bmp");
UINT width;
// Negative tests.
status = GdipGetImageWidth (NULL, &width);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageWidth (image, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (image);
}
static void test_getImageHeight ()
{
GpStatus status;
GpImage *image = getImage ("test.bmp");
UINT height;
// Negative tests.
status = GdipGetImageHeight (NULL, &height);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageHeight (image, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (image);
}
static void test_getImageHorizontalResolution ()
{
GpStatus status;
GpImage *image = getImage ("test.bmp");
REAL horizontalResolution;
// Negative tests.
status = GdipGetImageHorizontalResolution (NULL, &horizontalResolution);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageHorizontalResolution (image, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (image);
}
static void test_getImageVerticalResolution ()
{
GpStatus status;
GpImage *image = getImage ("test.bmp");
REAL verticalResolution;
// Negative tests.
status = GdipGetImageVerticalResolution (NULL, &verticalResolution);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageVerticalResolution (image, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (image);
}
static void test_getImageFlags ()
{
GpStatus status;
GpImage *image = getImage ("test.bmp");
UINT flags;
// Negative tests.
status = GdipGetImageFlags (NULL, &flags);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageFlags (image, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (image);
}
static void test_getImageRawFormat ()
{
GpStatus status;
GpImage *image = getImage ("test.bmp");
GUID rawFormat;
// Negative tests.
status = GdipGetImageRawFormat (NULL, &rawFormat);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageRawFormat (image, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (image);
}
static void test_getImagePixelFormat ()
{
GpStatus status;
GpImage *image = getImage ("test.bmp");
PixelFormat pixelFormat;
// Negative tests.
status = GdipGetImagePixelFormat (NULL, &pixelFormat);
assertEqualInt (status, InvalidParameter);
status = GdipGetImagePixelFormat (image, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (image);
}
static BOOL callback (void *callbackData) { return TRUE; }
static void test_getImageThumbnail ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *wmfImage = getImage ("test.wmf");
GpImage *emfImage = getImage ("test.emf");
GpImage *thumbImage;
// ImageTypeBitmap - non zero width and height.
status = GdipGetImageThumbnail (bitmapImage, 10, 10, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, Ok);
verifyBitmap (thumbImage, memoryBmpRawFormat, PixelFormat32bppPARGB, 10, 10, ImageFlagsHasAlpha, 0, TRUE);
GdipDisposeImage (thumbImage);
// ImageTypeBitmap - width > height.
status = GdipGetImageThumbnail (bitmapImage, 20, 10, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, Ok);
verifyBitmap (thumbImage, memoryBmpRawFormat, PixelFormat32bppPARGB, 20, 10, ImageFlagsHasAlpha, 0, TRUE);
GdipDisposeImage (thumbImage);
// ImageTypeBitmap - height > width.
status = GdipGetImageThumbnail (bitmapImage, 10, 20, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, Ok);
verifyBitmap (thumbImage, memoryBmpRawFormat, PixelFormat32bppPARGB, 10, 20, ImageFlagsHasAlpha, 0, TRUE);
GdipDisposeImage (thumbImage);
// ImageTypeBitmap - zero width and height.
status = GdipGetImageThumbnail (bitmapImage, 0, 0, &thumbImage, NULL, NULL);
assertEqualInt (status, Ok);
verifyBitmap (thumbImage, memoryBmpRawFormat, PixelFormat32bppPARGB, 120, 120, ImageFlagsHasAlpha, 0, TRUE);
GdipDisposeImage (thumbImage);
// ImageTypeMetafile - non zero width and height.
status = GdipGetImageThumbnail (wmfImage, 10, 10, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, Ok);
verifyBitmap (thumbImage, memoryBmpRawFormat, PixelFormat32bppARGB, 10, 10, ImageFlagsHasAlpha, 0, TRUE);
GdipDisposeImage (thumbImage);
// ImageTypeMetafile - width > height.
status = GdipGetImageThumbnail (wmfImage, 20, 10, &thumbImage, NULL, NULL);
assertEqualInt (status, Ok);
verifyBitmap (thumbImage, memoryBmpRawFormat, PixelFormat32bppARGB, 20, 10, ImageFlagsHasAlpha, 0, TRUE);
GdipDisposeImage (thumbImage);
// ImageTypeMetafile - height > width.
status = GdipGetImageThumbnail (wmfImage, 10, 20, &thumbImage, NULL, NULL);
assertEqualInt (status, Ok);
verifyBitmap (thumbImage, memoryBmpRawFormat, PixelFormat32bppARGB, 10, 20, ImageFlagsHasAlpha, 0, TRUE);
GdipDisposeImage (thumbImage);
// ImageTypeMetafile - non zero width and height.
status = GdipGetImageThumbnail (emfImage, 10, 10, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, Ok);
verifyBitmap (thumbImage, memoryBmpRawFormat, PixelFormat32bppARGB, 10, 10, ImageFlagsHasAlpha, 0, TRUE);
GdipDisposeImage (thumbImage);
// ImageTypeMetafile - width > height.
status = GdipGetImageThumbnail (emfImage, 20, 10, &thumbImage, NULL, NULL);
assertEqualInt (status, Ok);
verifyBitmap (thumbImage, memoryBmpRawFormat, PixelFormat32bppARGB, 20, 10, ImageFlagsHasAlpha, 0, TRUE);
GdipDisposeImage (thumbImage);
// ImageTypeMetafile - height > width.
status = GdipGetImageThumbnail (emfImage, 10, 20, &thumbImage, NULL, NULL);
assertEqualInt (status, Ok);
verifyBitmap (thumbImage, memoryBmpRawFormat, PixelFormat32bppARGB, 10, 20, ImageFlagsHasAlpha, 0, TRUE);
GdipDisposeImage (thumbImage);
// Negative tests.
status = GdipGetImageThumbnail (NULL, 10, 10, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageThumbnail (bitmapImage, 10, 10, NULL, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageThumbnail (bitmapImage, 0, 10, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, OutOfMemory);
status = GdipGetImageThumbnail (wmfImage, 0, 10, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, OutOfMemory);
status = GdipGetImageThumbnail (emfImage, 0, 10, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, OutOfMemory);
status = GdipGetImageThumbnail (NULL, 0, 10, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageThumbnail (bitmapImage, 0, 10, NULL, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageThumbnail (bitmapImage, 10, 0, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, OutOfMemory);
status = GdipGetImageThumbnail (wmfImage, 10, 0, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, OutOfMemory);
status = GdipGetImageThumbnail (emfImage, 10, 0, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, OutOfMemory);
status = GdipGetImageThumbnail (NULL, 10, 0, &thumbImage, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, InvalidParameter);
status = GdipGetImageThumbnail (bitmapImage, 10, 0, NULL, (GetThumbnailImageAbort) callback, (void *) 1);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (wmfImage);
GdipDisposeImage (emfImage);
}
static void test_getEncoderParameterListSize ()
{
GpStatus status;
GpImage *image = getImage ("test.bmp");
UINT size;
status = GdipGetEncoderParameterListSize (image, &bmpEncoderClsid, &size);
assertEqualInt (status, NotImplemented);
status = GdipGetEncoderParameterListSize (image, &tifEncoderClsid, &size);
assertEqualInt (status, Ok);
assertEqualInt (size, (is_32bit() ? 164 : 184));
status = GdipGetEncoderParameterListSize (image, &gifEncoderClsid, &size);
assertEqualInt (status, Ok);
assertEqualInt (size, (is_32bit() ? 64 : 80));
status = GdipGetEncoderParameterListSize (image, &pngEncoderClsid, &size);
assertEqualInt (status, Ok);
assertEqualInt (size, (is_32bit() ? 32 : 40));
status = GdipGetEncoderParameterListSize (image, &jpegEncoderClsid, &size);
assertEqualInt (status, Ok);
assertEqualInt (size, (is_32bit() ? 172 : 200));
status = GdipGetEncoderParameterListSize (image, &icoEncoderClsid, &size);
assertEqualInt (status, FileNotFound);
status = GdipGetEncoderParameterListSize (image, &wmfEncoderClsid, &size);
assertEqualInt (status, FileNotFound);
status = GdipGetEncoderParameterListSize (image, &emfEncoderClsid, &size);
assertEqualInt (status, FileNotFound);
// Negative tests.
status = GdipGetEncoderParameterListSize (NULL, &emfEncoderClsid, &size);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterListSize (image, NULL, &size);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterListSize (image, &emfEncoderClsid, NULL);
assertEqualInt (status, FileNotFound);
status = GdipGetEncoderParameterListSize (image, &jpegEncoderClsid, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (image);
}
static void test_getEncoderParameterList ()
{
GpStatus status;
GpImage *image = getImage ("test.bmp");
UINT tiffSize;
UINT gifSize;
UINT pngSize;
UINT jpegSize;
EncoderParameters buffer;
EncoderParameters *parameters;
GUID compression = {0x0E09D739D, 0x0CCD4, 0x44EE, {0x8E, 0x0BA, 0x3F, 0x0BF, 0x8B, 0x0E4, 0x0FC, 0x58}};
GUID colorDepth = {0x66087055, 0x0AD66, 0x4C7C, {0x9A, 0x18, 0x38, 0x0A2, 0x31, 0x0B, 0x83, 0x37}};
GUID saveFlag = {0x292266FC, 0x0AC40, 0x47BF, {0x8C, 0x0FC, 0x0A8, 0x5B, 0x89, 0x0A6, 0x55, 0x0DE}};
GUID saveAsCMYK = {0x0A219BBC9, 0x0A9D, 0x4005, {0x0A3, 0x0EE, 0x3A, 0x42, 0x1B, 0x8B, 0x0B0, 0x6C}};
GUID imageItems = {0x63875E13, 0x1F1D, 0x45AB, {0x91, 0x95, 0x0A2, 0x9B, 0x60, 0x66, 0x0A6, 0x50}};
GUID transformation = {0x8D0EB2D1, 0x0A58E, 0x4EA8, {0x0AA, 0x14, 0x10, 0x80, 0x74, 0x0B7, 0x0B6, 0x0F9}};
GUID quality = {0x1D5BE4B5, 0x0FA4A, 0x452D, {0x9C, 0x0DD, 0x5D, 0x0B3, 0x51, 0x5, 0x0E7, 0x0EB}};
GUID luminanceTable = {0x0EDB33BCE, 0x266, 0x4A77, {0x0B9, 0x4, 0x27, 0x21, 0x60, 0x99, 0x0E7, 0x17}};
GUID chrominanceTable = {0x0F2E455DC, 0x9B3, 0x4316, {0x82, 0x60, 0x67, 0x6A, 0x0DA, 0x32, 0x48, 0x1C}};
// TIFF encoder.
GdipGetEncoderParameterListSize (image, &tifEncoderClsid, &tiffSize);
parameters = (EncoderParameters *) malloc (tiffSize);
status = GdipGetEncoderParameterList (image, &tifEncoderClsid, tiffSize, parameters);
assertEqualInt (status, Ok);
assertEqualInt (parameters->Count, 4);
assert (memcmp ((void *) ¶meters->Parameter[0].Guid, (void *) &compression, sizeof (GUID)) == 0);
assertEqualInt (parameters->Parameter[0].NumberOfValues, 5);
assertEqualInt (parameters->Parameter[0].Type, EncoderParameterValueTypeLong);
assertEqualInt (((LONG *) parameters->Parameter[0].Value)[0], EncoderValueCompressionLZW);
assertEqualInt (((LONG *) parameters->Parameter[0].Value)[1], EncoderValueCompressionCCITT3);
assertEqualInt (((LONG *) parameters->Parameter[0].Value)[2], EncoderValueCompressionRle);
assertEqualInt (((LONG *) parameters->Parameter[0].Value)[3], EncoderValueCompressionCCITT4);
assertEqualInt (((LONG *) parameters->Parameter[0].Value)[4], EncoderValueCompressionNone);
assert (memcmp ((void *) ¶meters->Parameter[1].Guid, (void *) &colorDepth, sizeof (GUID)) == 0);
assertEqualInt (parameters->Parameter[1].NumberOfValues, 5);
assertEqualInt (parameters->Parameter[1].Type, EncoderParameterValueTypeLong);
assertEqualInt (((LONG *) parameters->Parameter[1].Value)[0], 1);
assertEqualInt (((LONG *) parameters->Parameter[1].Value)[1], 4);
assertEqualInt (((LONG *) parameters->Parameter[1].Value)[2], 8);
assertEqualInt (((LONG *) parameters->Parameter[1].Value)[3], 24);
assertEqualInt (((LONG *) parameters->Parameter[1].Value)[4], 32);
assert (memcmp ((void *) ¶meters->Parameter[2].Guid, (void *) &saveFlag, sizeof (GUID)) == 0);
assertEqualInt (parameters->Parameter[2].NumberOfValues, 1);
assertEqualInt (parameters->Parameter[2].Type, EncoderParameterValueTypeLong);
assertEqualInt (((LONG *) parameters->Parameter[2].Value)[0], EncoderValueMultiFrame);
assert (memcmp ((void *) ¶meters->Parameter[3].Guid, (void *) &saveAsCMYK, sizeof (GUID)) == 0);
assertEqualInt (parameters->Parameter[3].NumberOfValues, 1);
assertEqualInt (parameters->Parameter[3].Type, EncoderParameterValueTypeLong);
assertEqualInt (((LONG *) parameters->Parameter[3].Value)[0], 1);
free (parameters);
// GIF encoder.
GdipGetEncoderParameterListSize (image, &gifEncoderClsid, &gifSize);
parameters = (EncoderParameters *) malloc (gifSize);
status = GdipGetEncoderParameterList (image, &gifEncoderClsid, gifSize, parameters);
assertEqualInt (status, Ok);
assertEqualInt (parameters->Count, 2);
assert (memcmp ((void *) ¶meters->Parameter[0].Guid, (void *) &imageItems, sizeof (GUID)) == 0);
assertEqualInt (parameters->Parameter[0].NumberOfValues, 0);
assertEqualInt (parameters->Parameter[0].Type, (EncoderParameterValueType) 9);
assert (!parameters->Parameter[0].Value);
assert (memcmp ((void *) ¶meters->Parameter[1].Guid, (void *) &saveFlag, sizeof (GUID)) == 0);
assertEqualInt (parameters->Parameter[1].NumberOfValues, 1);
assertEqualInt (parameters->Parameter[1].Type, EncoderParameterValueTypeLong);
assertEqualInt (((LONG *) parameters->Parameter[1].Value)[0], EncoderValueMultiFrame);
free (parameters);
// PNG encoder.
GdipGetEncoderParameterListSize (image, &pngEncoderClsid, &pngSize);
parameters = (EncoderParameters *) malloc (pngSize);
status = GdipGetEncoderParameterList (image, &pngEncoderClsid, pngSize, parameters);
assertEqualInt (status, Ok);
assertEqualInt (parameters->Count, 1);
assert (memcmp ((void *) ¶meters->Parameter[0].Guid, (void *) &imageItems, sizeof (GUID)) == 0);
assertEqualInt (parameters->Parameter[0].NumberOfValues, 0);
assertEqualInt (parameters->Parameter[0].Type, (EncoderParameterValueType) 9);
assert (!parameters->Parameter[0].Value);
free (parameters);
// JPEG encoder.
GdipGetEncoderParameterListSize (image, &jpegEncoderClsid, &jpegSize);
parameters = (EncoderParameters *) malloc (jpegSize);
status = GdipGetEncoderParameterList (image, &jpegEncoderClsid, jpegSize, parameters);
assertEqualInt (status, Ok);
assertEqualInt (parameters->Count, 5);
assert (memcmp ((void *) ¶meters->Parameter[0].Guid, (void *) &transformation, sizeof (GUID)) == 0);
assertEqualInt (parameters->Parameter[0].NumberOfValues, 5);
assertEqualInt (parameters->Parameter[0].Type, EncoderParameterValueTypeLong);
assertEqualInt (((LONG *) parameters->Parameter[0].Value)[0], EncoderValueTransformRotate90);
assertEqualInt (((LONG *) parameters->Parameter[0].Value)[1], EncoderValueTransformRotate180);
assertEqualInt (((LONG *) parameters->Parameter[0].Value)[2], EncoderValueTransformRotate270);
assertEqualInt (((LONG *) parameters->Parameter[0].Value)[3], EncoderValueTransformFlipHorizontal);
assertEqualInt (((LONG *) parameters->Parameter[0].Value)[4], EncoderValueTransformFlipVertical);
assert (memcmp ((void *) ¶meters->Parameter[1].Guid, (void *) &quality, sizeof (GUID)) == 0);
assertEqualInt (parameters->Parameter[1].NumberOfValues, 1);
assertEqualInt (parameters->Parameter[1].Type, EncoderParameterValueTypeLongRange);
assertEqualInt (((LONG *) parameters->Parameter[1].Value)[0], 0);
assertEqualInt (((LONG *) parameters->Parameter[1].Value)[1], 100);
assert (memcmp ((void *) ¶meters->Parameter[2].Guid, (void *) &luminanceTable, sizeof (GUID)) == 0);
assertEqualInt (parameters->Parameter[2].NumberOfValues, 0);
assertEqualInt (parameters->Parameter[2].Type, EncoderParameterValueTypeShort);
assert (!parameters->Parameter[2].Value);
assert (memcmp ((void *) ¶meters->Parameter[3].Guid, (void *) &chrominanceTable, sizeof (GUID)) == 0);
assertEqualInt (parameters->Parameter[3].NumberOfValues, 0);
assertEqualInt (parameters->Parameter[3].Type, EncoderParameterValueTypeShort);
assert (!parameters->Parameter[3].Value);
assert (memcmp ((void *) ¶meters->Parameter[4].Guid, (void *) &imageItems, sizeof (GUID)) == 0);
assertEqualInt (parameters->Parameter[4].NumberOfValues, 0);
assertEqualInt (parameters->Parameter[4].Type, (EncoderParameterValueType) 9);
assert (!parameters->Parameter[4].Value);
free (parameters);
// Negative tests.
status = GdipGetEncoderParameterList (NULL, &emfEncoderClsid, 100, &buffer);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, NULL, 100, &buffer);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &emfEncoderClsid, 100, NULL);
assertEqualInt (status, FileNotFound);
status = GdipGetEncoderParameterList (image, &tifEncoderClsid, 100, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &gifEncoderClsid, 100, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &pngEncoderClsid, 100, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &jpegEncoderClsid, 100, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &jpegEncoderClsid, 0, &buffer);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &jpegEncoderClsid, -1, &buffer);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &tifEncoderClsid, tiffSize - 1, &buffer);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &tifEncoderClsid, tiffSize + 1, &buffer);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &gifEncoderClsid, gifSize - 1, &buffer);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &gifEncoderClsid, gifSize + 1, &buffer);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &pngEncoderClsid, pngSize - 1, &buffer);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &pngEncoderClsid, pngSize + 1, &buffer);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &jpegEncoderClsid, jpegSize - 1, &buffer);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &jpegEncoderClsid, jpegSize + 1, &buffer);
assertEqualInt (status, InvalidParameter);
status = GdipGetEncoderParameterList (image, &bmpEncoderClsid, 0, &buffer);
assertEqualInt (status, NotImplemented);
status = GdipGetEncoderParameterList (image, &icoEncoderClsid, 0, &buffer);
assertEqualInt (status, FileNotFound);
status = GdipGetEncoderParameterList (image, &wmfEncoderClsid, 0, &buffer);
assertEqualInt (status, FileNotFound);
status = GdipGetEncoderParameterList (image, &emfEncoderClsid, 0, &buffer);
assertEqualInt (status, FileNotFound);
GdipDisposeImage (image);
}
static void test_getFrameDimensionsCount ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
UINT count;
status = GdipImageGetFrameDimensionsCount (bitmapImage, &count);
assertEqualInt (status, Ok);
assertEqualInt (count, 1);
status = GdipImageGetFrameDimensionsCount (metafileImage, &count);
assertEqualInt (status, Ok);
assertEqualInt (count, 1);
// Negative tests.
status = GdipImageGetFrameDimensionsCount (NULL, &count);
assertEqualInt (status, InvalidParameter);
status = GdipImageGetFrameDimensionsCount (metafileImage, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_getFrameDimensionsList ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
GUID dimensions[1];
status = GdipImageGetFrameDimensionsList (bitmapImage, dimensions, 1);
assertEqualInt (status, Ok);
// Negative tests.
status = GdipImageGetFrameDimensionsList (NULL, dimensions, 1);
assertEqualInt (status, InvalidParameter);
status = GdipImageGetFrameDimensionsList (bitmapImage, NULL, 1);
assertEqualInt (status, InvalidParameter);
status = GdipImageGetFrameDimensionsList (bitmapImage, dimensions, 0);
assertEqualInt (status, Win32Error);
status = GdipImageGetFrameDimensionsList (metafileImage, dimensions, 0);
assertEqualInt (status, InvalidParameter);
status = GdipImageGetFrameDimensionsList (bitmapImage, dimensions, -1);
assertEqualInt (status, Win32Error);
status = GdipImageGetFrameDimensionsList (metafileImage, dimensions, -1);
assertEqualInt (status, InvalidParameter);
status = GdipImageGetFrameDimensionsList (bitmapImage, dimensions, 2);
assertEqualInt (status, Win32Error);
status = GdipImageGetFrameDimensionsList (metafileImage, dimensions, 2);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_getFrameCount ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
GUID pageDimension = {0x7462dc86, 0x6180, 0x4c7e, {0x8e, 0x3f, 0xee, 0x73, 0x33, 0xa7, 0xa4, 0x83}};
GUID timeDimension = {0x6aedbd6d, 0x3fb5, 0x418a, {0x83, 0xa6, 0x7f, 0x45, 0x22, 0x9d, 0xc8, 0x72}};
UINT count;
// Bitmap - page dimension.
status = GdipImageGetFrameCount (bitmapImage, &pageDimension, &count);
assertEqualInt (status, Ok);
assertEqualInt (count, 1);
// Metafile - null dimension.
count = -1;
status = GdipImageGetFrameCount (metafileImage, NULL, &count);
assertEqualInt (status, Ok);
assertEqualInt (count, 1);
// Metafile - no such dimension.
count = -1;
status = GdipImageGetFrameCount (metafileImage, &emfEncoderClsid, &count);
assertEqualInt (status, Ok);
assertEqualInt (count, 1);
// Negative tests.
status = GdipImageGetFrameCount (NULL, &pageDimension, &count);
assertEqualInt (status, InvalidParameter);
status = GdipImageGetFrameCount (bitmapImage, NULL, &count);
assertEqualInt (status, Win32Error);
status = GdipImageGetFrameCount (bitmapImage, &pageDimension, NULL);
assertEqualInt (status, Win32Error);
status = GdipImageGetFrameCount (metafileImage, &pageDimension, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipImageGetFrameCount (bitmapImage, &timeDimension, &count);
assertEqualInt (status, Win32Error);
status = GdipImageGetFrameCount (bitmapImage, &emfEncoderClsid, &count);
assertEqualInt (status, Win32Error);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_selectActiveFrame ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
GUID pageDimension = {0x7462dc86, 0x6180, 0x4c7e, {0x8e, 0x3f, 0xee, 0x73, 0x33, 0xa7, 0xa4, 0x83}};
GUID timeDimension = {0x6aedbd6d, 0x3fb5, 0x418a, {0x83, 0xa6, 0x7f, 0x45, 0x22, 0x9d, 0xc8, 0x72}};
// Bitmap - page dimension.
status = GdipImageSelectActiveFrame (bitmapImage, &pageDimension, 0);
assertEqualInt (status, Ok);
// Metafile - page dimension.
status = GdipImageSelectActiveFrame (metafileImage, &pageDimension, 100);
assertEqualInt (status, Ok);
// Metafile - time dimension.
status = GdipImageSelectActiveFrame (metafileImage, &timeDimension, 100);
assertEqualInt (status, Ok);
// Negative tests.
status = GdipImageSelectActiveFrame (NULL, &pageDimension, 0);
assertEqualInt (status, InvalidParameter);
status = GdipImageSelectActiveFrame (bitmapImage, NULL, 0);
assertEqualInt (status, InvalidParameter);
status = GdipImageSelectActiveFrame (metafileImage, NULL, 0);
assertEqualInt (status, InvalidParameter);
status = GdipImageSelectActiveFrame (bitmapImage, &pageDimension, 4);
assertEqualInt (status, Win32Error);
status = GdipImageSelectActiveFrame (metafileImage, &pageDimension, 200);
assertEqualInt (status, Ok);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_forceValidation ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
// ImageTypeBitmap.
status = GdipImageForceValidation (bitmapImage);
assertEqualInt (status, Ok);
// ImageTypeMetafile.
status = GdipImageForceValidation (metafileImage);
assertEqualInt (status, Ok);
// Negative tests.
status = GdipImageForceValidation (NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_rotateFlip ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
// RotateNoneFlipNone.
status = GdipImageRotateFlip (bitmapImage, RotateNoneFlipNone);
assertEqualInt (status, Ok);
// Rotate90FlipNone.
status = GdipImageRotateFlip (bitmapImage, Rotate90FlipNone);
assertEqualInt (status, Ok);
// Rotate180FlipNone.
status = GdipImageRotateFlip (bitmapImage, Rotate180FlipNone);
assertEqualInt (status, Ok);
// Rotate270FlipNone.
status = GdipImageRotateFlip (bitmapImage, Rotate270FlipNone);
assertEqualInt (status, Ok);
// RotateNoneFlipX.
status = GdipImageRotateFlip (bitmapImage, RotateNoneFlipX);
assertEqualInt (status, Ok);
// Rotate90FlipX.
status = GdipImageRotateFlip (bitmapImage, Rotate90FlipX);
assertEqualInt (status, Ok);
// Rotate180FlipX.
status = GdipImageRotateFlip (bitmapImage, Rotate180FlipX);
assertEqualInt (status, Ok);
// Rotate270FlipX.
status = GdipImageRotateFlip (bitmapImage, Rotate270FlipX);
assertEqualInt (status, Ok);
// Negative tests.
status = GdipImageRotateFlip (NULL, RotateNoneFlipNone);
assertEqualInt (status, InvalidParameter);
status = GdipImageRotateFlip (metafileImage, Rotate270FlipX);
assertEqualInt (status, NotImplemented);
status = GdipImageRotateFlip (bitmapImage, (RotateFlipType)(RotateNoneFlipNone - 1));
assertEqualInt (status, InvalidParameter);
status = GdipImageRotateFlip (bitmapImage, (RotateFlipType)(Rotate270FlipX + 1));
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_getImagePalette ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
INT size;
BYTE buffer1[1040];
ColorPalette *palette = (ColorPalette *)buffer1;
BYTE buffer2[1040];
ColorPalette *nonEmptyPalette = (ColorPalette *)buffer2;
GdipGetImagePaletteSize (bitmapImage, &size);
// Empty palette - same size.
status = GdipGetImagePalette (bitmapImage, palette, size);
assertEqualInt (status, Ok);
assertEqualInt (palette->Count, 0);
// Empty palette - larger size.
palette->Count = 100;
status = GdipGetImagePalette (bitmapImage, palette, size + 1);
assertEqualInt (status, Ok);
assertEqualInt (palette->Count, 0);
// Empty palette - negative size.
palette->Count = 100;
status = GdipGetImagePalette (bitmapImage, palette, -1);
assertEqualInt (status, Ok);
assertEqualInt (palette->Count, 0);
// Negative tests.
status = GdipGetImagePalette (NULL, palette, size);
assertEqualInt (status, InvalidParameter);
status = GdipGetImagePalette (bitmapImage, NULL, size);
assertEqualInt (status, InvalidParameter);
status = GdipGetImagePalette (metafileImage, NULL, size);
assertEqualInt (status, InvalidParameter);
status = GdipGetImagePalette (metafileImage, palette, size);
assertEqualInt (status, NotImplemented);
status = GdipGetImagePalette (metafileImage, palette, -1);
assertEqualInt (status, NotImplemented);
status = GdipGetImagePalette (bitmapImage, palette, 0);
assertEqualInt (status, InvalidParameter);
status = GdipGetImagePalette (metafileImage, palette, 0);
assertEqualInt (status, NotImplemented);
status = GdipGetImagePalette (bitmapImage, palette, size - 1);
assertEqualInt (status, InvalidParameter);
status = GdipGetImagePalette (metafileImage, palette, size - 1);
assertEqualInt (status, NotImplemented);
// Non empty palette - setup.
nonEmptyPalette->Count = 10;
nonEmptyPalette->Flags = 1;
nonEmptyPalette->Entries[0] = 2;
status = GdipSetImagePalette (bitmapImage, nonEmptyPalette);
assertEqualInt (status, Ok);
GdipGetImagePaletteSize (bitmapImage, &size);
// Non empty palette - same size.
palette->Count = 100;
palette->Flags = 100;
palette->Entries[0] = 100;
status = GdipGetImagePalette (bitmapImage, palette, size);
assertEqualInt (status, Ok);
assertEqualInt (palette->Count, 10);
assertEqualInt (palette->Flags, 1);
assertEqualInt (palette->Entries[0], 2);
// Non empty palette - larger size.
palette->Count = 100;
palette->Flags = 100;
palette->Entries[0] = 100;
status = GdipGetImagePalette (bitmapImage, palette, size + 1);
assertEqualInt (status, InvalidParameter);
status = GdipGetImagePalette (bitmapImage, palette, size - 1);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_setImagePalette ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
INT size;
BYTE buffer1[1040];
ColorPalette *palette = (ColorPalette *)buffer1;
BYTE buffer2[1040];
ColorPalette *resultPalette = (ColorPalette *)buffer2;
GdipGetImagePaletteSize (bitmapImage, &size);
// Set with positive count.
palette->Count = 10;
palette->Flags = 1;
palette->Entries[0] = 2;
status = GdipSetImagePalette (bitmapImage, palette);
assertEqualInt (status, Ok);
status = GdipGetImagePaletteSize (bitmapImage, &size);
assertEqualInt (status, Ok);
assertEqualInt (size, 48);
status = GdipGetImagePalette (bitmapImage, resultPalette, size);
assertEqualInt (status, Ok);
assertEqualInt (resultPalette->Count, 10);
assertEqualInt (resultPalette->Flags, 1);
assertEqualInt (resultPalette->Entries[0], 2);
// Set with large count.
palette->Count = 256;
palette->Flags = 1;
palette->Entries[0] = 20;
status = GdipSetImagePalette (bitmapImage, palette);
assertEqualInt (status, Ok);
status = GdipGetImagePaletteSize (bitmapImage, &size);
assertEqualInt (status, Ok);
assertEqualInt (size, 1032);
status = GdipGetImagePalette (bitmapImage, resultPalette, size);
assertEqualInt (status, Ok);
assertEqualInt (resultPalette->Count, 256);
assertEqualInt (resultPalette->Flags, 1);
assertEqualInt (resultPalette->Entries[0], 20);
// Negative tests.
status = GdipSetImagePalette (NULL, palette);
assertEqualInt (status, InvalidParameter);
palette->Count = 10;
status = GdipSetImagePalette (metafileImage, palette);
assertEqualInt (status, NotImplemented);
palette->Count = 0;
status = GdipSetImagePalette (bitmapImage, palette);
assertEqualInt (status, InvalidParameter);
palette->Count = -1;
status = GdipSetImagePalette (bitmapImage, palette);
assertEqualInt (status, InvalidParameter);
palette->Count = 257;
status = GdipSetImagePalette (bitmapImage, palette);
assertEqualInt (status, InvalidParameter);
status = GdipSetImagePalette (bitmapImage, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipSetImagePalette (metafileImage, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_getImagePaletteSize ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
INT size;
status = GdipGetImagePaletteSize (bitmapImage, &size);
assertEqualInt (status, Ok);
assertEqualInt ((int) sizeof(ColorPalette), 12);
assertEqualInt (size, 12);
// Negative tests.
status = GdipGetImagePaletteSize (NULL, &size);
assertEqualInt (status, InvalidParameter);
status = GdipGetImagePaletteSize (bitmapImage, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipGetImagePaletteSize (metafileImage, &size);
assertEqualInt (status, GenericError);
status = GdipGetImagePaletteSize (metafileImage, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_getPropertyCount ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
UINT count;
// ImageTypeBitmap.
status = GdipGetPropertyCount (bitmapImage, &count);
assertEqualInt (status, Ok);
assertEqualInt (count, 0);
// ImageTypeMetafile.
status = GdipGetPropertyCount (metafileImage, &count);
assertEqualInt (status, Ok);
assertEqualInt (count, 0);
// Negative tests.
status = GdipGetPropertyCount (NULL, &count);
assertEqualInt (status, InvalidParameter);
status = GdipGetPropertyCount (bitmapImage, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_getPropertyIdList ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
PROPID list[2];
// ImageTypeBitmap.
status = GdipGetPropertyIdList (bitmapImage, 0, list);
assertEqualInt (status, Ok);
// Negative tests.
status = GdipGetPropertyIdList (NULL, 0, list);
assertEqualInt (status, InvalidParameter);
status = GdipGetPropertyIdList (metafileImage, 0, list);
assertEqualInt (status, NotImplemented);
status = GdipGetPropertyIdList (bitmapImage, 0, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipGetPropertyIdList (metafileImage, 0, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipGetPropertyIdList (bitmapImage, 1, list);
assertEqualInt (status, InvalidParameter);
status = GdipGetPropertyIdList (metafileImage, 1, list);
assertEqualInt (status, NotImplemented);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_getPropertyItemSize ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
PROPID prop = 100;
UINT size;
// Negative tests.
status = GdipGetPropertyItemSize (NULL, prop, &size);
assertEqualInt (status, InvalidParameter);
status = GdipGetPropertyItemSize (bitmapImage, prop, &size);
assertEqualInt (status, PropertyNotFound);
status = GdipGetPropertyItemSize (metafileImage, prop, &size);
assertEqualInt (status, NotImplemented);
status = GdipGetPropertyItemSize (bitmapImage, prop, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipGetPropertyItemSize (metafileImage, prop, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_getPropertyItem ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
PROPID prop = 100;
PropertyItem propertyItem;
// Negative tests.
status = GdipGetPropertyItem (NULL, prop, 1, &propertyItem);
assertEqualInt (status, InvalidParameter);
status = GdipGetPropertyItem (bitmapImage, prop, 1, &propertyItem);
assertEqualInt (status, PropertyNotFound);
status = GdipGetPropertyItem (metafileImage, prop, 1, &propertyItem);
assertEqualInt (status, NotImplemented);
status = GdipGetPropertyItem (bitmapImage, prop, 1, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipGetPropertyItem (metafileImage, prop, 1, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_getPropertySize ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
UINT totalBufferSize;
UINT numProperties;
status = GdipGetPropertySize (bitmapImage, &totalBufferSize, &numProperties);
assertEqualInt (status, Ok);
assertEqualInt (totalBufferSize, 0);
assertEqualInt (numProperties, 0);
// Negative tests.
status = GdipGetPropertySize (NULL, &totalBufferSize, &numProperties);
assertEqualInt (status, InvalidParameter);
status = GdipGetPropertySize (metafileImage, &totalBufferSize, &numProperties);
assertEqualInt (status, NotImplemented);
status = GdipGetPropertySize (bitmapImage, NULL, &numProperties);
assertEqualInt (status, InvalidParameter);
status = GdipGetPropertySize (metafileImage, NULL, &numProperties);
assertEqualInt (status, InvalidParameter);
status = GdipGetPropertySize (bitmapImage, &totalBufferSize, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipGetPropertySize (metafileImage, &totalBufferSize, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_getAllPropertyItems ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
PropertyItem propertyItems[2];
// Negative tests.
status = GdipGetAllPropertyItems (NULL, 0, 0, propertyItems);
assertEqualInt (status, InvalidParameter);
status = GdipGetAllPropertyItems (bitmapImage, 0, 0, propertyItems);
assertEqualInt (status, GenericError);
status = GdipGetAllPropertyItems (metafileImage, 0, 0, propertyItems);
assertEqualInt (status, NotImplemented);
status = GdipGetAllPropertyItems (bitmapImage, 0, 0, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipGetAllPropertyItems (metafileImage, 0, 0, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipGetAllPropertyItems (bitmapImage, 1, 0, propertyItems);
assertEqualInt (status, InvalidParameter);
status = GdipGetAllPropertyItems (metafileImage, 1, 0, propertyItems);
assertEqualInt (status, NotImplemented);
status = GdipGetAllPropertyItems (bitmapImage, 0, 1, propertyItems);
assertEqualInt (status, InvalidParameter);
status = GdipGetAllPropertyItems (metafileImage, 0, 1, propertyItems);
assertEqualInt (status, NotImplemented);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void test_removePropertyItem ()
{
GpStatus status;
GpImage *bitmapImage = getImage ("test.bmp");
GpImage *metafileImage = getImage ("test.wmf");
PROPID prop = 100;
// Negative tests.
status = GdipRemovePropertyItem (NULL, prop);
assertEqualInt (status, InvalidParameter);
status = GdipRemovePropertyItem (bitmapImage, prop);
assertEqualInt (status, GenericError);
status = GdipRemovePropertyItem (metafileImage, prop);
assertEqualInt (status, NotImplemented);
GdipDisposeImage (bitmapImage);
GdipDisposeImage (metafileImage);
}
static void setPropertyItemForImage (GpImage *image)
{
GpStatus status;
INT temp = 1;
PropertyItem propertyItem1 = {10, 0, 11, &temp};
PropertyItem propertyItem2 = {11, 0, 12, NULL};
PropertyItem propertyItem3 = {10, 0, 9, NULL};
UINT propertySize;
PropertyItem resultPropertyItem;
UINT numProperties;
UINT totalBufferSize;
PROPID propertyIds[2];
// Set new property.
status = GdipSetPropertyItem (image, &propertyItem1);
assertEqualInt (status, Ok);
status = GdipGetPropertyItemSize (image, propertyItem1.id, &propertySize);
assertEqualInt (status, Ok);
assertEqualInt (propertySize, (int) sizeof(PropertyItem));
status = GdipGetPropertyItem (image, propertyItem1.id, propertySize, &resultPropertyItem);
assertEqualInt (status, Ok);
assertEqualInt (resultPropertyItem.id, 10);
assertEqualInt (resultPropertyItem.length, 0);
assertEqualInt (resultPropertyItem.type, 11);
status = GdipGetPropertyCount (image, &numProperties);
assertEqualInt (status, Ok);
assertEqualInt (numProperties, 1);
numProperties = -1;
status = GdipGetPropertySize (image, &totalBufferSize, &numProperties);
assertEqualInt (status, Ok);
assertEqualInt (totalBufferSize, (int) sizeof(PropertyItem));
assertEqualInt (numProperties, 1);
propertyIds[1] = -1;
status = GdipGetPropertyIdList (image, numProperties, propertyIds);
assertEqualInt (status, Ok);
assertEqualInt (propertyIds[0], 10);
assertEqualInt (propertyIds[1], -1);
// Set another new property.
status = GdipSetPropertyItem (image, &propertyItem2);
assertEqualInt (status, Ok);
status = GdipGetPropertyItemSize (image, propertyItem2.id, &propertySize);
assertEqualInt (status, Ok);
assertEqualInt (propertySize, (int) sizeof(PropertyItem));
status = GdipGetPropertyItem (image, propertyItem2.id, propertySize, &resultPropertyItem);
assertEqualInt (status, Ok);
assertEqualInt (resultPropertyItem.id, 11);
assertEqualInt (resultPropertyItem.length, 0);
assertEqualInt (resultPropertyItem.type, 12);
status = GdipGetPropertyCount (image, &numProperties);
assertEqualInt (status, Ok);
assertEqualInt (numProperties, 2);
numProperties = -1;
status = GdipGetPropertySize (image, &totalBufferSize, &numProperties);
assertEqualInt (status, Ok);
assertEqualInt (totalBufferSize, (int) sizeof(PropertyItem) * 2);
assertEqualInt (numProperties, 2);
propertyIds[1] = -1;
status = GdipGetPropertyIdList (image, numProperties, propertyIds);
assertEqualInt (status, Ok);
assertEqualInt (propertyIds[0], 10);
assertEqualInt (propertyIds[1], 11);
// Override an existing property.
status = GdipSetPropertyItem (image, &propertyItem3);
assertEqualInt (status, Ok);
status = GdipGetPropertyItemSize (image, propertyItem3.id, &propertySize);
assertEqualInt (status, Ok);
assertEqualInt (propertySize, (int) sizeof(PropertyItem));
status = GdipGetPropertyItem (image, propertyItem3.id, propertySize, &resultPropertyItem);
assertEqualInt (status, Ok);
assertEqualInt (resultPropertyItem.id, 10);
assertEqualInt (resultPropertyItem.length, 0);
assertEqualInt (resultPropertyItem.type, 9);
status = GdipGetPropertyCount (image, &numProperties);
assertEqualInt (status, Ok);
assertEqualInt (numProperties, 2);
numProperties = -1;
status = GdipGetPropertySize (image, &totalBufferSize, &numProperties);
assertEqualInt (status, Ok);
assertEqualInt (totalBufferSize, (int) sizeof(PropertyItem) * 2);
assertEqualInt (numProperties, 2);
propertyIds[1] = -1;
status = GdipGetPropertyIdList (image, numProperties, propertyIds);
assertEqualInt (status, Ok);
assertEqualInt (propertyIds[0], 10);
assertEqualInt (propertyIds[1], 11);
}
static void test_setPropertyItem()
{
GpStatus status;
GpImage *bmpImage = getImage ("test.bmp");
GpImage *tifImage = getImage ("test.tif");
GpImage *gifImage = getImage ("test.gif");
GpImage *pngImage = getImage ("test.png");
GpImage *jpgImage = getImage ("test.jpg");
GpImage *icoImage = getImage ("test.ico");
GpImage *metafileImage = getImage ("test.wmf");
PropertyItem propertyItem = {10, 0, 11, NULL};
setPropertyItemForImage (bmpImage);
status = GdipSetPropertyItem (tifImage, &propertyItem);
assertEqualInt (status, Ok);
status = GdipSetPropertyItem (gifImage, &propertyItem);
assertEqualInt (status, Ok);
status = GdipSetPropertyItem (pngImage, &propertyItem);
assertEqualInt (status, Ok);
status = GdipSetPropertyItem (jpgImage, &propertyItem);
assertEqualInt (status, Ok);
status = GdipSetPropertyItem (icoImage, &propertyItem);
assertEqualInt (status, Ok);
// Negative tests.
status = GdipSetPropertyItem (NULL, &propertyItem);
assertEqualInt (status, InvalidParameter);
status = GdipSetPropertyItem (metafileImage, &propertyItem);
assertEqualInt (status, NotImplemented);
status = GdipSetPropertyItem (bmpImage, NULL);
assertEqualInt (status, InvalidParameter);
status = GdipSetPropertyItem (metafileImage, NULL);
assertEqualInt (status, InvalidParameter);
GdipDisposeImage (bmpImage);
GdipDisposeImage (tifImage);
GdipDisposeImage (gifImage);
GdipDisposeImage (pngImage);
GdipDisposeImage (jpgImage);
GdipDisposeImage (icoImage);
GdipDisposeImage (metafileImage);
}
int
main (int argc, char**argv)
{
STARTUP;
test_loadImageFromStream ();
test_loadImageFromFile ();
test_loadImageFromStreamICM ();
test_loadImageFromFileICM ();
test_loadImageFromFileTif ();
test_loadImageFromFileGif ();
test_loadImageFromFilePng ();
test_loadImageFromFileJpg ();
test_loadImageFromFileIcon ();
test_loadImageFromFileWmf ();
test_loadImageFromFileEmf ();
test_cloneImage ();
test_disposeImage ();
test_getImageGraphicsContext ();
test_getImageBounds ();
test_getImageDimension ();
test_getImageType ();
test_getImageWidth ();
test_getImageHeight ();
test_getImageHorizontalResolution ();
test_getImageVerticalResolution ();
test_getImageFlags ();
test_getImageRawFormat ();
test_getImagePixelFormat ();
test_getImageThumbnail ();
test_getEncoderParameterListSize ();
test_getEncoderParameterList ();
test_getFrameDimensionsCount ();
test_getFrameDimensionsList ();
test_getFrameCount ();
test_selectActiveFrame ();
test_forceValidation ();
test_rotateFlip ();
test_getImagePalette ();
test_setImagePalette ();
test_getImagePaletteSize ();
test_getPropertyCount ();
test_getPropertyIdList ();
test_getPropertyItemSize ();
test_getPropertyItem ();
test_getPropertySize ();
test_getAllPropertyItems ();
test_removePropertyItem ();
test_setPropertyItem ();
SHUTDOWN;
return 0;
}
| 32.712067 | 179 | 0.761322 |
e849d36208dee7b5a5c8f3ff048fa772a1feb53c | 4,930 | h | C | geas/include/geas/utils/ordered-perm.h | AppleGamer22/FIT2082 | 298459dbfdb158bdd4e6d8428e6c958d186fdb20 | [
"MIT"
] | 3 | 2021-09-29T08:06:31.000Z | 2022-03-25T10:24:54.000Z | geas/include/geas/utils/ordered-perm.h | AppleGamer22/FIT2082 | 298459dbfdb158bdd4e6d8428e6c958d186fdb20 | [
"MIT"
] | null | null | null | geas/include/geas/utils/ordered-perm.h | AppleGamer22/FIT2082 | 298459dbfdb158bdd4e6d8428e6c958d186fdb20 | [
"MIT"
] | null | null | null | #ifndef GEAS__ORDERED_PERM__H
#define GEAS__ORDERED_PERM__H
#include <geas/solver/solver_data.h>
#include <geas/vars/intvar.h>
// For tracking, say, ordered lists of lower/upper bounds.
// Assumes (anti-)monotone
// Traits requires:
// Var : Type
// Val : Type
// is_increasing : bool
// attach : solver_data -> var_t -> watch_fun -> unit
// eval : solver_data -> var_t -> val_t.
namespace geas {
template<class Traits>
class OrderedPerm {
typedef typename Traits::Var var_t;
typedef typename Traits::Val val_t;
typedef OrderedPerm<Traits> T;
struct crossref {
crossref(unsigned int _pos, var_t _v)
: x(_v), pos(_pos), val(0) { }
var_t x;
unsigned int pos;
val_t val;
};
void rebuild(void) {
// Fill in the val parameters.
// fprintf(stderr, "%% Rebuilding\n");
for(crossref& e : elts)
e.val = Traits::eval(s, e.x);
std::sort(perm.begin(), perm.end(), [this](unsigned int p, unsigned int q) { return elts[p].val < elts[q].val; });
for(int ii : irange(perm.size())) {
elts[perm[ii]].pos = ii;
}
}
void percolate_up(int xi) INLINE_ATTR {
val_t v(elts[xi].val);
unsigned int p(elts[xi].pos);
unsigned int e(elts.size()-1);
for(; p < e; ++p) {
unsigned int yi(perm[p+1]);
if(!(Traits::compare(elts[yi].val, v)))
break;
perm[p] = yi;
elts[yi].pos = p;
}
perm[p] = xi;
elts[xi].pos = p;
}
void percolate_down(int xi) INLINE_ATTR {
val_t v(elts[xi].val);
unsigned int p(elts[xi].pos);
for(; p > 0; --p) {
unsigned int yi(perm[p-1]);
if(!(Traits::compare(v, elts[yi].val)))
break;
perm[p] = yi;
elts[yi].pos = p;
}
perm[p] = xi;
elts[xi].pos = p;
}
/*
void percolate(int xi) {
unsigned int p(elts[xi].pos);
val_t v(elts[xi].val);
if(Traits::is_increasing) {
unsigned int e = elts.size()-1;
for(; p < e; ++p) {
unsigned int yi(perm[p+1]);
if(!(Traits::compare(elts[yi].val, v)))
break;
perm[p] = yi;
elts[yi].pos = p;
}
perm[p] = xi;
elts[xi].pos = p;
} else {
for(; p > 0; --p) {
unsigned int yi(perm[p-1]);
if(!Traits::compare(v, elts[yi].val))
break;
perm[p] = yi;
elts[yi].pos = p;
}
perm[p] = xi;
elts[xi].pos = p;
}
}
*/
static watch_result s_wake(void* p, int xi) {
return static_cast<T*>(p)->wake(xi);
}
watch_result wake(int xi) {
// If we haven't re-initialised the permutation,
// don't bother doing anything.
if(!is_consistent)
return Wt_Keep;
// Otherwise, shift xi back to its appropriate location.
val_t old(elts[xi].val);
elts[xi].val = Traits::eval(s, elts[xi].x);
if(Traits::compare(elts[xi].val, old)) {
percolate_down(xi);
} else if(Traits::compare(old, elts[xi].val)) {
percolate_up(xi);
}
return Wt_Keep;
}
public:
OrderedPerm(solver_data* _s)
: s(_s), is_consistent(false) { }
template<class It>
OrderedPerm(solver_data* _s, It b, It e)
: s(_s), is_consistent(false) {
unsigned int ii = 0;
for(; b != e; ++b, ++ii) {
Traits::attach(s, *b, watch_callback(s_wake, this, ii));
perm.push(ii);
elts.push(crossref(ii, *b));
}
}
void add(var_t& x) {
unsigned int pi = perm.size();
perm.push(pi);
elts.push(crossref(pi, x));
wake(pi);
Traits::attach(s, x, watch_callback(s_wake, this, pi));
}
const vec<unsigned int>& get(void) {
if(!is_consistent) {
s->persist.bt_flags.push(&is_consistent);
is_consistent = true;
rebuild();
}
return perm;
}
var_t& operator[](unsigned int xi) { return elts[xi].x; }
const val_t& value(unsigned int xi) const { return elts[xi].val; }
protected:
solver_data* s;
vec<unsigned int> perm;
vec<crossref> elts;
char is_consistent;
};
template<class V>
struct By_LB {
typedef V Var;
typedef typename V::val_t Val;
enum { is_increasing = true };
static void attach(solver_data* s, V& x, watch_callback c) { x.attach(s, E_LB, c); }
static Val eval(solver_data* s, const V& x) { return x.lb(s); }
static bool compare(Val p, Val q) { return p < q; }
};
template<class V>
struct By_UB {
typedef V Var;
typedef typename V::val_t Val;
enum { is_increasing = false };
static void attach(solver_data* s, V& x, watch_callback c) { x.attach(s, E_UB, c); }
static Val eval(solver_data* s, const V& x) { return x.ub(s); }
static bool compare(Val p, Val q) { return p < q; }
};
template<class V>
struct By_InvUB {
typedef V Var;
typedef typename V::val_t Val;
enum { is_increasing = true };
static void attach(solver_data* s, V& x, watch_callback c) { x.attach(s, E_UB, c); }
static Val eval(solver_data* s, const V& x) { return -x.ub(s); }
static bool compare(Val p, Val q) { return q < p; }
};
}
#endif
| 25.811518 | 118 | 0.588235 |
1f3c7009b2ec0797c1960fe0387ffa34287afc29 | 279 | c | C | Userland/SampleCodeModule/StandardLibrary/math.c | atharos1/Leah | b12872f1e69a4f3c1112bec8bca5953563f70ff9 | [
"BSD-3-Clause"
] | 2 | 2020-12-10T21:46:20.000Z | 2021-08-12T03:29:13.000Z | Userland/SampleCodeModule/StandardLibrary/math.c | atharos1/Leah | b12872f1e69a4f3c1112bec8bca5953563f70ff9 | [
"BSD-3-Clause"
] | null | null | null | Userland/SampleCodeModule/StandardLibrary/math.c | atharos1/Leah | b12872f1e69a4f3c1112bec8bca5953563f70ff9 | [
"BSD-3-Clause"
] | null | null | null | int sign(int n) {
return (n < 0 ? -1 : 1);
}
int abs(int n) {
return n * sign(n);
}
long long int pow(int base, int exp) {
if( exp == 0 )
return 1;
int num = base;
for(int i = 2; i <= exp; i++)
num *= base;
return num;
} | 13.95 | 39 | 0.437276 |
50d4b17945892f501cbe5daae9343779b9b82a30 | 167 | h | C | libc/include/sys/io.h | cptaffe/os_v2 | b23706f6b88388aeb54c80fcd87f516ac4e3af5a | [
"MIT"
] | null | null | null | libc/include/sys/io.h | cptaffe/os_v2 | b23706f6b88388aeb54c80fcd87f516ac4e3af5a | [
"MIT"
] | null | null | null | libc/include/sys/io.h | cptaffe/os_v2 | b23706f6b88388aeb54c80fcd87f516ac4e3af5a | [
"MIT"
] | null | null | null |
#ifndef SYS_IO_H
#define SYS_IO_H
void outb(unsigned short port, unsigned char value);
unsigned short inb(unsigned short port);
void io_wait();
#endif // SYS_IO_H
| 15.181818 | 52 | 0.760479 |
319f70b77c78c95afdf32d2607690def0eaa044d | 2,423 | h | C | runtime/helpers/sampler_helpers.h | abhi5658054/compute-runtime | 894060de5010874381fc981cf96a722769e65a76 | [
"MIT"
] | 1 | 2022-03-04T22:47:19.000Z | 2022-03-04T22:47:19.000Z | runtime/helpers/sampler_helpers.h | abhi5658054/compute-runtime | 894060de5010874381fc981cf96a722769e65a76 | [
"MIT"
] | null | null | null | runtime/helpers/sampler_helpers.h | abhi5658054/compute-runtime | 894060de5010874381fc981cf96a722769e65a76 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2017, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "CL/cl.h"
// It's max SSH size per kernel (MAX_BINDING_TABLE_INDEX * 64)
const uint32_t SAMPLER_OBJECT_ID_SHIFT = 253 * 64;
// Sampler Patch Token Enums
enum SAMPLER_PATCH_ENUM {
CLK_DEFAULT_SAMPLER = 0x00,
CLK_ADDRESS_NONE = 0x00,
CLK_ADDRESS_CLAMP = 0x01,
CLK_ADDRESS_CLAMP_TO_EDGE = 0x02,
CLK_ADDRESS_REPEAT = 0x03,
CLK_ADDRESS_MIRRORED_REPEAT = 0x04,
CLK_ADDRESS_MIRRORED_REPEAT_101 = 0x05,
CLK_NORMALIZED_COORDS_FALSE = 0x00,
CLK_NORMALIZED_COORDS_TRUE = 0x08,
CLK_FILTER_NEAREST = 0x00,
CLK_FILTER_LINEAR = 0x00,
};
inline SAMPLER_PATCH_ENUM GetAddrModeEnum(cl_addressing_mode addressingMode) {
switch (addressingMode) {
case CL_ADDRESS_REPEAT:
return CLK_ADDRESS_REPEAT;
case CL_ADDRESS_CLAMP_TO_EDGE:
return CLK_ADDRESS_CLAMP_TO_EDGE;
case CL_ADDRESS_CLAMP:
return CLK_ADDRESS_CLAMP;
case CL_ADDRESS_NONE:
return CLK_ADDRESS_NONE;
case CL_ADDRESS_MIRRORED_REPEAT:
return CLK_ADDRESS_MIRRORED_REPEAT;
}
return CLK_ADDRESS_NONE;
}
inline SAMPLER_PATCH_ENUM GetNormCoordsEnum(cl_bool normalizedCoords) {
if (normalizedCoords == CL_TRUE) {
return CLK_NORMALIZED_COORDS_TRUE;
} else {
return CLK_NORMALIZED_COORDS_FALSE;
}
}
| 35.632353 | 78 | 0.749897 |
e18a1190741719af884e5bdb99f1ff729df3561a | 10,977 | c | C | lib/BSP/src/cs42l51.c | NikLeberg/speki | 253494523f9bc4d59819c9c234acea531bb44d78 | [
"MIT"
] | null | null | null | lib/BSP/src/cs42l51.c | NikLeberg/speki | 253494523f9bc4d59819c9c234acea531bb44d78 | [
"MIT"
] | null | null | null | lib/BSP/src/cs42l51.c | NikLeberg/speki | 253494523f9bc4d59819c9c234acea531bb44d78 | [
"MIT"
] | null | null | null | /**
*****************************************************************************
* @addtogroup CARME
* @{
* @defgroup CARME_Sound Sound
* @brief CARME-M4 Sound controller
* @{
*
* @file cs42l51.c
* @version 1.0
* @date 2013-03-11
* @author rct1
*
* @brief CS42L51 codec support functions.
*
* @todo Activate microphone and line in.
* @todo Test it.
*
*****************************************************************************
* @copyright
* @{
*
* This software can be used by students and other personal of the Bern
* University of Applied Sciences under the terms of the MIT license.
* For other persons this software is under the terms of the GNU General
* Public License version 2.
*
* Copyright © 2013, Bern University of Applied Sciences.
* All rights reserved.
*
*
* ##### MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*
* ##### GNU GENERAL PUBLIC LICENSE
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* @}
*****************************************************************************
*/
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*----- Header-Files -------------------------------------------------------*/
#include <stm32f4xx.h> /* Processor STM32F407IG */
#include <i2c.h> /* CARME I2C definitions */
#include <i2s.h> /* CARME I2S definitions */
#include <cs42l51.h> /* cs42l51 audio codec definitions */
/*----- Macros -------------------------------------------------------------*/
/*----- Data types ---------------------------------------------------------*/
/*----- Function prototypes ------------------------------------------------*/
void CS42L51_CtrlInterface_Init(void);
void CS42L51_AudioInterface_Init(void);
/*----- Data ---------------------------------------------------------------*/
/*----- Implementation -----------------------------------------------------*/
/**
*****************************************************************************
* @brief Write a byte to a register of the cs42l51 codec.
*
* @param[in] reg Register address to write
* @param[in] data Data
* @return None
*****************************************************************************
*/
void CS42L51_WriteReg(uint8_t reg, uint8_t data) {
CARME_I2C_Write(CODEC_I2C, CODEC_ADDRESS, (uint8_t) reg, 0, &data, 1);
}
/**
*****************************************************************************
* @brief Read a byte from a register of the cs42l51 codec.
*
* @param[in] reg Register address to read
* @return Data
*****************************************************************************
*/
uint8_t CS42L51_ReadReg(uint8_t reg) {
uint8_t data;
CARME_I2C_Read(CODEC_I2C, CODEC_ADDRESS, (uint8_t) reg, 0, &data, 1);
return data;
}
/**
*****************************************************************************
* @brief Codec CS42L51 low-layer and register initialization.
*
* @param[in] Volume \ref CS42L51_VolumeOutCtrl.
* @return 1 if no codec is found, else 0.
*****************************************************************************
*/
uint8_t CS42L51_Init(int8_t Volume) {
CS42L51_CtrlInterface_Init();
CS42L51_AudioInterface_Init();
/* Check if the codec is connected */
if (CS42L51_ReadReg(CHIP_ID) != 0xD9) {
return 1;
}
/* Keep Codec powered OFF */
CS42L51_WriteReg(POWER_CONTROL, 0x01);
/**
* Set mic power and speed
* - Select single speed mode (4-50 kHz)
*/
CS42L51_WriteReg(MIC_POWER_AND_SPEED, 0x20);
/**
* Configure the interface
* - DAC and ADC interface is I2S
*/
CS42L51_WriteReg(INTERFACE_CONTROL, 0x0C);
/**
* Set mic control
*/
CS42L51_WriteReg(MIC_CONTROL, 0x60);
/**
* Set ADC control configuration
* - Enable the high-pass filter
*/
CS42L51_WriteReg(ADC_CONTROL, 0xA0);
/**
* Set the ADC configuration
* - Select the line in as source
*/
CS42L51_WriteReg(ADC_CONFIGURE, 0x00);
/**
* Set DAC output configuration
* - HP Gain is 0.6047
*/
CS42L51_WriteReg(DAC_OUTPUT_CONTROL, 0x60);
/**
* Set DAC configuration
* - Data selection is 00 for PCM or 01 for signal processing engine
* - Soft ramp
*/
CS42L51_WriteReg(DAC_CONTROL, 0x42);
/* Set ALCAx and PGAx control */
CS42L51_WriteReg(ALCA_AND_PGAA_CONTROL, 0x00);
CS42L51_WriteReg(ALCB_AND_PGAB_CONTROL, 0x00);
/**
* Set PCMx mixer volume
* - mute the mixer channel
*/
CS42L51_WriteReg(PCMA_MIXER_VOLUME_CONTROL, 0x00);
CS42L51_WriteReg(PCMB_MIXER_VOLUME_CONTROL, 0x00);
/* Set treble and bass */
CS42L51_WriteReg(TONE_CONTROL, 0x88);
/* Set the output volume */
CS42L51_WriteReg(AOUTA_VOLUME_CONTROL, 0x18);
CS42L51_WriteReg(AOUTB_VOLUME_CONTROL, 0x18);
/**
* Set PCM channel mixer
* AOUTA = Channel L
* AOUTB = Channel R
* ADCA = Channel L
* ADCB = Channel R
*/
CS42L51_WriteReg(PCM_CHANNEL_MIXER, 0x00);
/**
* Set limiter threshold
* - Maximum threshold = 0 dB
* - Cushion threshold = 0 dB
*/
CS42L51_WriteReg(LIMITER_THRESHOLD, 0x00);
/**
* Limiter release rate
* - Disabled
* - Both channel
* - slowest release
*/
CS42L51_WriteReg(LIMITER_RELEASE, 0x7F);
/**
* Limiter attack rate
* - fastest attack
*/
CS42L51_WriteReg(LIMITER_ATTACK, 0x00);
/* Power down up after initial configure */
CS42L51_WriteReg(POWER_CONTROL, 0x00);
/**
* Enable periodic beep sound
* - On time: 5.2 s
* - Off time: 5.2 s
* - Frequency: 260.87 Hz (C4)
* - Volume: +12 dB
* - Repeat beep
*/
// CS42L51_WriteReg(BEEP_FREQUENCY_AND_TIMING, 0x0F);
// CS42L51_WriteReg(BEEP_OFF_TIME_AND_VOLUME, 0x66);
// CS42L51_WriteReg(BEEP_AND_TONE_CONFIGURATION, 0xC0);
CS42L51_VolumeOutCtrl(Volume);
return 0;
}
/**
*****************************************************************************
* @brief Codec CS42L51 ctrl line configuration and register
* initialization.
*
* @return None
*****************************************************************************
*/
void CS42L51_CtrlInterface_Init(void) {
CARME_I2C_Init(CODEC_I2C);
}
/**
*****************************************************************************
* @brief Codec CS42L51 audio line configuration.
*
* @return None
*****************************************************************************
*/
void CS42L51_AudioInterface_Init(void) {
I2S_InitTypeDef I2S_InitStruct;
/* Enable the peripheral clock */
RCC_APB1PeriphClockCmd(CODEC_I2S_CLK, ENABLE);
/* GPIO configuration */
CARME_I2S_GPIO_Init();
/* Deinitialize and disable the I2S and SPI hardware */
SPI_Cmd(CODEC_I2S, DISABLE);
I2S_Cmd(CODEC_I2S, DISABLE);
I2S_Cmd(CODEC_I2S_EXT, DISABLE);
SPI_I2S_DeInit(CODEC_I2S);
/* CODEC_I2S peripheral configuration */
I2S_InitStruct.I2S_AudioFreq = I2S_AudioFreq_48k;
I2S_InitStruct.I2S_Standard = I2S_Standard_Phillips;
I2S_InitStruct.I2S_DataFormat = I2S_DataFormat_16b;
I2S_InitStruct.I2S_CPOL = I2S_CPOL_Low;
I2S_InitStruct.I2S_Mode = I2S_Mode_MasterTx;
I2S_InitStruct.I2S_MCLKOutput = I2S_MCLKOutput_Enable;
/* Configure the I2S */
I2S_Init(CODEC_I2S, &I2S_InitStruct);
/* Initialize the I2S extended channel for RX */
I2S_FullDuplexConfig(CODEC_I2S_EXT, &I2S_InitStruct);
I2S_Cmd(CODEC_I2S, ENABLE);
I2S_Cmd(CODEC_I2S_EXT, ENABLE);
}
/**
*****************************************************************************
* @brief Get the status of the cs42l51 codec.
*
* @return Status register
*****************************************************************************
*/
uint8_t CS42L51_Status(void) {
return CS42L51_ReadReg(STATUS_REGISTER);
}
/**
*****************************************************************************
* @brief Codec CS42L51 output volume control.
*
* @param[in] Volume Binary code volume setting\n
* 0001 1000 +12.0 dB\n
* ... ... \n
* 0000 0000 0.0 dB\n
* 1111 1111 -0.5 dB\n
* 1111 1110 -1.0 dB\n
* ... ... \n
* 0011 0100 -102 dB\n
* ... ... \n
* 0001 1001 -102 dB\n
* @return None
*****************************************************************************
*/
void CS42L51_VolumeOutCtrl(int8_t Volume) {
// uint8_t reg;
//
// Volume &= 0x07;
// Volume <<= 5;
// reg = CS42L51_ReadReg(DAC_OUTPUT_CONTROL);
// reg &= 0x1F;
// reg |= Volume;
//
// CS42L51_WriteReg(DAC_OUTPUT_CONTROL, reg);
if (Volume > 0xE6) {
/* Set the Master volume */
CS42L51_WriteReg(AOUTA_VOLUME_CONTROL, Volume - 0xE7);
CS42L51_WriteReg(AOUTB_VOLUME_CONTROL, Volume - 0xE7);
}
else {
/* Set the Master volume */
CS42L51_WriteReg(AOUTA_VOLUME_CONTROL, Volume + 0x19);
CS42L51_WriteReg(AOUTB_VOLUME_CONTROL, Volume + 0x19);
}
}
/**
*****************************************************************************
* @brief Mute the CS42L51 output.
*
* @param[in] on if 0 the codec will unmute the output, else it will
* mute it.
* @return None
*****************************************************************************
*/
void CS42L51_Mute(uint8_t on) {
uint8_t reg;
reg = CS42L51_ReadReg(DAC_OUTPUT_CONTROL);
if (on) {
reg |= 0x03;
}
else {
reg &= ~0x03;
}
CS42L51_WriteReg(DAC_OUTPUT_CONTROL, reg);
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
/**
* @}
* @}
*/
| 27.931298 | 78 | 0.575931 |
dc849870b68d85ae2235d018945f7161960a5951 | 1,393 | h | C | orttraining/orttraining/training_ops/cuda/optimizer/adamw/adamw.h | jamill/onnxruntime | 0565fecf46c4dd711c01a4106641946963bf7ff0 | [
"MIT"
] | 669 | 2018-12-03T22:00:31.000Z | 2019-05-06T19:42:49.000Z | orttraining/orttraining/training_ops/cuda/optimizer/adamw/adamw.h | jamill/onnxruntime | 0565fecf46c4dd711c01a4106641946963bf7ff0 | [
"MIT"
] | 440 | 2018-12-03T21:09:56.000Z | 2019-05-06T20:47:23.000Z | orttraining/orttraining/training_ops/cuda/optimizer/adamw/adamw.h | jamill/onnxruntime | 0565fecf46c4dd711c01a4106641946963bf7ff0 | [
"MIT"
] | 140 | 2018-12-03T21:15:28.000Z | 2019-05-06T18:02:36.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include <vector>
#include "core/common/common.h"
#include "core/providers/cuda/cuda_kernel.h"
namespace onnxruntime {
namespace cuda {
class AdamWOptimizer final : public CudaKernel {
public:
AdamWOptimizer(const OpKernelInfo& info) : CudaKernel(info) {
info.GetAttrOrDefault("alpha", &alpha_, 0.9f);
info.GetAttrOrDefault("beta", &beta_, 0.999f);
info.GetAttrOrDefault("epsilon", &epsilon_, 1e-8f);
info.GetAttrOrDefault("weight_decay", &weight_decay_, 0.f);
info.GetAttrOrDefault("adam_mode", &adam_mode_, static_cast<int64_t>(0));
info.GetAttrOrDefault("correct_bias", &correct_bias_, static_cast<int64_t>(1));
ORT_ENFORCE(adam_mode_ == 0 || adam_mode_ == 1, "The value of adam_mode is invalid.");
ORT_ENFORCE(correct_bias_ == 0 || correct_bias_ == 1, "The value of correct_bias is invalid.");
// To have torch adamw equivalence, correct_bias must be 1 for adam_mode=0.
ORT_ENFORCE(adam_mode_ != 0 || correct_bias_ == 1, "The correct_bias should be 1 for adam_mode = 0.");
}
Status ComputeInternal(OpKernelContext* context) const override;
private:
float alpha_;
float beta_;
float epsilon_;
float weight_decay_;
int64_t adam_mode_;
int64_t correct_bias_;
};
} // namespace cuda
} // namespace onnxruntime
| 30.282609 | 106 | 0.723618 |
09f1f6b38504209709a99934b3953d542736a9f5 | 909 | c | C | 0x17-doubly_linked_lists/8-delete_dnodeint.c | JRodriguez9510/holbertonschool-low_level_programming | 3a0343f948a0586f5834f3e92f203aaa2a8a4757 | [
"MIT"
] | 1 | 2021-01-27T03:13:38.000Z | 2021-01-27T03:13:38.000Z | 0x17-doubly_linked_lists/8-delete_dnodeint.c | JRodriguez9510/holbertonschool-low_level_programming | 3a0343f948a0586f5834f3e92f203aaa2a8a4757 | [
"MIT"
] | null | null | null | 0x17-doubly_linked_lists/8-delete_dnodeint.c | JRodriguez9510/holbertonschool-low_level_programming | 3a0343f948a0586f5834f3e92f203aaa2a8a4757 | [
"MIT"
] | 1 | 2020-10-22T04:55:08.000Z | 2020-10-22T04:55:08.000Z | #include "lists.h"
/**
* delete_dnodeint_at_index - Removes a node at a given position
* @head: Pointer to pointer to the head of the list
* @index: The position where the node has to be inserted
*
* Return: 1 if success or -1 if fail.
*/
int delete_dnodeint_at_index(dlistint_t **head, unsigned int index)
{
dlistint_t *inxd_node, *tmp_node = *head, *listnd = *head;
unsigned int idx = 0, listlng = 0;
if (!head || !(*head))
return (-1);
while (listnd)
{
listnd = listnd->next;
listlng++;
}
if (index > (listlng - 1))
return (-1);
if (tmp_node && (index == 0))
{
*head = tmp_node->next;
(*head)->prev = NULL;
free(tmp_node);
return (1);
}
while (tmp_node)
{
if (idx + 1 == index)
{
inxd_node = tmp_node->next;
if (inxd_node)
{
tmp_node->next = inxd_node->next;
if (inxd_node->next)
inxd_node->next->prev = tmp_node;
free(inxd_node);
return (1);
}
}
tmp_node = tmp_node->next;
idx++;
}
return (-1);
}
| 18.18 | 67 | 0.658966 |
67092f92c3b3f2de6741236530fed5c9286a8b4d | 212 | h | C | source/main/syscall_holotape_handlers.h | skwirl42/robco-processor | eb92ee0d2402403b36b9b796f80c3d46aaed1442 | [
"MIT"
] | null | null | null | source/main/syscall_holotape_handlers.h | skwirl42/robco-processor | eb92ee0d2402403b36b9b796f80c3d46aaed1442 | [
"MIT"
] | 30 | 2020-12-29T13:25:25.000Z | 2021-09-28T12:03:35.000Z | source/main/syscall_holotape_handlers.h | skwirl42/robco-processor | eb92ee0d2402403b36b9b796f80c3d46aaed1442 | [
"MIT"
] | null | null | null | #pragma once
#include "emulator.h"
void handle_holotape_syscall(emulator &emulator);
void insert_holotape(const char *holotape_file);
void eject_holotape();
bool holotape_initialized();
void dispose_holotape(); | 23.555556 | 49 | 0.811321 |
bcc177f721960a8a6bc8165d123a12914d1c68fc | 2,937 | h | C | Engine/Source/Editor/EditorWidgets/Private/SAssetDiscoveryIndicator.h | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Editor/EditorWidgets/Private/SAssetDiscoveryIndicator.h | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Editor/EditorWidgets/Private/SAssetDiscoveryIndicator.h | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Layout/Visibility.h"
#include "Layout/Margin.h"
#include "Animation/CurveHandle.h"
#include "Animation/CurveSequence.h"
#include "Styling/SlateColor.h"
#include "Widgets/DeclarativeSyntaxSupport.h"
#include "Widgets/SCompoundWidget.h"
#include "AssetDiscoveryIndicator.h"
#include "IAssetRegistry.h"
/** An indicator for the progress of the asset registry background search */
class SAssetDiscoveryIndicator : public SCompoundWidget
{
public:
SLATE_BEGIN_ARGS( SAssetDiscoveryIndicator )
: _ScaleMode(EAssetDiscoveryIndicatorScaleMode::Scale_None)
, _FadeIn(true)
{}
/** The way the indicator will scale out when done displaying progress */
SLATE_ARGUMENT( EAssetDiscoveryIndicatorScaleMode::Type, ScaleMode )
/** The padding to apply to the background of the indicator */
SLATE_ARGUMENT( FMargin, Padding )
/** If true, this widget will fade in after a short delay */
SLATE_ARGUMENT( bool, FadeIn )
SLATE_END_ARGS()
/** Destructor */
virtual ~SAssetDiscoveryIndicator();
/** Constructs this widget with InArgs */
void Construct( const FArguments& InArgs );
// SCompoundWidget interface
virtual void Tick( const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime ) override;
/** Handles updating the progress from the asset registry */
void OnAssetRegistryFileLoadProgress(const IAssetRegistry::FFileLoadProgressUpdateData& ProgressUpdateData);
/** Handles updating the progress from the asset registry */
void OnAssetRegistryFilesLoaded();
/** Gets the main status text */
FText GetMainStatusText() const;
/** Gets the sub status text */
FText GetSubStatusText() const;
/** Gets the progress bar fraction */
TOptional<float> GetProgress() const;
/** Gets the sub status text visbility */
EVisibility GetSubStatusTextVisibility() const;
/** Get the current wrap point for the status text */
float GetStatusTextWrapWidth() const;
/** Gets the background's opacity */
FSlateColor GetBorderBackgroundColor() const;
/** Gets the whole widget's opacity */
FLinearColor GetIndicatorColorAndOpacity() const;
/** Gets the whole widget's opacity */
FVector2D GetIndicatorDesiredSizeScale() const;
/** Gets the whole widget's visibility */
EVisibility GetIndicatorVisibility() const;
private:
/** The main status text */
FText MainStatusText;
/** The sub status text (if any) */
FText SubStatusText;
/** The asset registry's asset discovery progress as a percentage */
TOptional<float> Progress;
/** The current wrap point for the status text */
float StatusTextWrapWidth;
/** The way the indicator will scale in/out before/after displaying progress */
EAssetDiscoveryIndicatorScaleMode::Type ScaleMode;
/** The fade in/out animation */
FCurveSequence FadeAnimation;
FCurveHandle FadeCurve;
FCurveHandle ScaleCurve;
};
| 29.666667 | 118 | 0.760981 |
87e2ee655f196e63b01ab26c270367ba669aa7bb | 266 | h | C | attacker/SSL/momo.h | satadriver/attacker | 24e4434d8a836e040e48df195f2ca8919ab52609 | [
"Apache-2.0"
] | null | null | null | attacker/SSL/momo.h | satadriver/attacker | 24e4434d8a836e040e48df195f2ca8919ab52609 | [
"Apache-2.0"
] | null | null | null | attacker/SSL/momo.h | satadriver/attacker | 24e4434d8a836e040e48df195f2ca8919ab52609 | [
"Apache-2.0"
] | 1 | 2022-03-20T03:21:00.000Z | 2022-03-20T03:21:00.000Z | #pragma once
#include <windows.h>
#include <iostream>
#include "sslPublic.h"
using namespace std;
class Momo {
public:
static int isMomoDns(string url, string host);
static int makeMomoDns(char*recvBuffer, int len, int buflimit, LPHTTPPROXYPARAM http);
};
| 14 | 87 | 0.740602 |
0ce98e959c615efcd274c9a869cc7c09dec307cd | 986 | h | C | TAO/examples/Borland/ReceiverImpl.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/examples/Borland/ReceiverImpl.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/examples/Borland/ReceiverImpl.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // $Id: ReceiverImpl.h 78897 2007-07-15 01:45:47Z sowayaa $
//---------------------------------------------------------------------------
#ifndef ReceiverImplH
#define ReceiverImplH
//---------------------------------------------------------------------------
#include "ReceiverS.h"
//---------------------------------------------------------------------------
class TReceiverImplementation : public POA_Receiver
{
public:
// = Initialization and termination methods.
TReceiverImplementation (void);
// Constructor.
~TReceiverImplementation (void);
// Destructor.
virtual void message (const char* msg);
virtual void shutdown (void);
// Called when the chat server is going away. The client
// implementation should shutdown the chat client in response to
// this.
void orb (CORBA::ORB_ptr o);
// Set the ORB pointer.
private:
CORBA::ORB_var orb_;
// ORB pointer.
};
//---------------------------------------------------------------------------
#endif
| 29 | 77 | 0.492901 |
e8669ad3c65499404a360a10d9535acdf122064e | 566 | h | C | System/Library/PrivateFrameworks/AXSpringBoardServerInstance.framework/AXViewServiceHandler.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | 1 | 2020-11-04T15:43:01.000Z | 2020-11-04T15:43:01.000Z | System/Library/PrivateFrameworks/AXSpringBoardServerInstance.framework/AXViewServiceHandler.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/AXSpringBoardServerInstance.framework/AXViewServiceHandler.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:53:41 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/AXSpringBoardServerInstance.framework/AXSpringBoardServerInstance
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
@protocol AXViewServiceHandler <NSObject>
@required
-(void)hideAXUIViewService:(id)arg1;
-(void)showAXUIViewService:(id)arg1 withData:(id)arg2;
-(BOOL)isShowingAXUIViewService:(id)arg1;
@end
| 31.444444 | 115 | 0.791519 |
e88c4841bc53ac38bc31c0fb1544da3a320f8c4f | 150 | h | C | include/graph_algorithms.h | calderov/slimgraph | 1c09b517b0e0b974d640bd4436f71820bbe7ba56 | [
"MIT"
] | 1 | 2021-05-23T02:10:06.000Z | 2021-05-23T02:10:06.000Z | include/graph_algorithms.h | calderov/slimgraph | 1c09b517b0e0b974d640bd4436f71820bbe7ba56 | [
"MIT"
] | 2 | 2016-05-03T06:58:00.000Z | 2016-06-10T05:06:24.000Z | include/graph_algorithms.h | calderov/slimgraph | 1c09b517b0e0b974d640bd4436f71820bbe7ba56 | [
"MIT"
] | null | null | null | #pragma once
/**
* This file is intended to enlist all the graph algorithms available in this humble library.
*/
#include "dfs.h"
#include "bfs.h" | 18.75 | 93 | 0.713333 |
954fa3a4b9b85a00cee355ff79b2cd4b0717bc50 | 3,091 | c | C | cluster.c | Louis-MG/MNHN-Tree-Tools | b2ecbefe68c33f33d38c40c03290ac3abf5a8f58 | [
"Zlib"
] | null | null | null | cluster.c | Louis-MG/MNHN-Tree-Tools | b2ecbefe68c33f33d38c40c03290ac3abf5a8f58 | [
"Zlib"
] | null | null | null | cluster.c | Louis-MG/MNHN-Tree-Tools | b2ecbefe68c33f33d38c40c03290ac3abf5a8f58 | [
"Zlib"
] | 1 | 2021-09-06T08:27:18.000Z | 2021-09-06T08:27:18.000Z | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#include"dbscan.h"
dataset dataset_from_fasta(FILE* in) {
char* line = NULL;
size_t line_size = 0;
int sequences = 0;
dataset ds;
char linebuffer[2000];
size_t linebuffer_length;
size_t sequence_length;
int i;
rewind(in);
while ( -1 != getline(&line, &line_size, in) ) {
if( line[0] == '>' ) sequences++;
}
rewind(in);
ds.sequences = (char**)malloc(sizeof(char*)*sequences);
ds.n_values = sequences;
sequences = -1;
while ( -1 != getline(&line, &line_size, in) ) {
if ( line[0] == '>') {
sequences++;
ds.sequences[sequences] = (char*)malloc(sizeof(char)*1001);
ds.sequences[sequences][0] = 0;
sequence_length = 0;
} else {
sscanf(line,"%s",linebuffer);
linebuffer_length = strlen(linebuffer);
sequence_length += linebuffer_length;
if(sequence_length > 1000) {
ds.sequences[sequences] =
(char*)realloc(ds.sequences[sequences],
sizeof(char)*(sequence_length+1));
}
for(i=0; i < linebuffer_length; i++) {
linebuffer[i] = toupper(linebuffer[i]);
}
strcat(ds.sequences[sequences],linebuffer);
}
}
return(ds);
}
void create_cluster_files(char* prefix, split_set s, dataset ds) {
int i,j,k;
FILE* cur_file;
char file_name[256];
char i_buffer[4];
for ( i = 0; i< s.n_clusters; i++) {
file_name[0] = 0;
strcat(file_name, prefix);
strcat(file_name, "-");
sprintf(i_buffer,"%03d", i);
strcat(file_name, i_buffer);
cur_file = fopen(file_name, "w");
for (j = 0; j< s.clusters[i].n_members; j++) {
fprintf(cur_file,">sequence_%i\n",s.clusters[i].members[j]);
for ( k = 0;
k < (strlen(ds.sequences[s.clusters[i].members[j]])-1);
k++) {
if( k != 0 && k%50 == 0 ) {
fprintf(cur_file, "\n");
fputc(ds.sequences[s.clusters[i].members[j]][k],cur_file);
} else {
fputc(ds.sequences[s.clusters[i].members[j]][k],cur_file);
}
}
if ( (strlen(ds.sequences[s.clusters[i].members[j]])-1) != 0 &&
(strlen(ds.sequences[s.clusters[i].members[j]])-1) %50 == 0 ) {
fprintf(cur_file, "\n");
fputc(ds.sequences[s.clusters[i].members[j]][k],cur_file);
} else {
fputc(ds.sequences[s.clusters[i].members[j]][k],cur_file);
}
fprintf(cur_file, "\n");
}
fclose(cur_file);
}
}
int main(int argc, char** argv) {
dataset ds;
size_t dimensions;
float epsilon;
int minpts;
FILE* input = fopen(argv[1], "r");
split_set set_of_clusters;
if(argc < 4) {
printf("Arguments are: \n"
" Sequences in FASTA \n"
" Epsilon \n"
" minPoints \n"
" output-files prefix \n" );
return(1);
}
sscanf(argv[2], "%f", &epsilon);
sscanf(argv[3], "%i", &minpts);
ds = dataset_from_fasta(input);
set_of_clusters = dbscan(ds, epsilon, minpts);
printf("%u clusters obtained \n", set_of_clusters.n_clusters);
if (set_of_clusters.n_clusters < 500) {
create_cluster_files(argv[4], set_of_clusters, ds);
}
fclose(input);
}
| 22.078571 | 69 | 0.599806 |
1984afb071d06b63e101f3bf16e60b34f3e5ae05 | 10,183 | c | C | feeds/ipq807x/qca-nss-drv/src/nss_tstamp.c | ArthurSu0211/wlan-ap | 5bf882b0e0225d49860b88d25c9b9ff9bc354516 | [
"BSD-3-Clause"
] | 2 | 2021-05-17T02:47:24.000Z | 2021-05-17T02:48:01.000Z | feeds/ipq807x/qca-nss-drv/src/nss_tstamp.c | ArthurSu0211/wlan-ap | 5bf882b0e0225d49860b88d25c9b9ff9bc354516 | [
"BSD-3-Clause"
] | 1 | 2021-01-14T18:40:50.000Z | 2021-01-14T18:40:50.000Z | feeds/ipq807x/qca-nss-drv/src/nss_tstamp.c | ArthurSu0211/wlan-ap | 5bf882b0e0225d49860b88d25c9b9ff9bc354516 | [
"BSD-3-Clause"
] | 3 | 2021-02-22T04:54:20.000Z | 2021-04-13T01:54:40.000Z | /*
**************************************************************************
* Copyright (c) 2015-2020, The Linux Foundation. All rights reserved.
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all copies.
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, 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.
**************************************************************************
*/
/*
* nss_tstamp.c
* NSS Tstamp APIs
*/
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/etherdevice.h>
#include <linux/netdevice.h>
#include <net/route.h>
#include <net/ip6_route.h>
#include "nss_tx_rx_common.h"
#include "nss_tstamp.h"
#include "nss_tstamp_stats.h"
#define NSS_TSTAMP_HEADER_SIZE max(sizeof(struct nss_tstamp_h2n_pre_hdr), sizeof(struct nss_tstamp_n2h_pre_hdr))
/*
* Notify data structure
*/
struct nss_tstamp_notify_data {
nss_tstamp_msg_callback_t tstamp_callback;
void *app_data;
};
static struct nss_tstamp_notify_data nss_tstamp_notify = {
.tstamp_callback = NULL,
.app_data = NULL,
};
static struct net_device_stats *nss_tstamp_ndev_stats(struct net_device *ndev);
/*
* dummy netdevice ops
*/
static const struct net_device_ops nss_tstamp_ndev_ops = {
.ndo_get_stats = nss_tstamp_ndev_stats,
};
/*
* nss_tstamp_ndev_setup()
* Dummy setup for net_device handler
*/
static void nss_tstamp_ndev_setup(struct net_device *ndev)
{
return;
}
/*
* nss_tstamp_ndev_stats()
* Return net device stats
*/
static struct net_device_stats *nss_tstamp_ndev_stats(struct net_device *ndev)
{
return &ndev->stats;
}
/*
* nss_tstamp_verify_if_num()
* Verify if_num passed to us.
*/
static bool nss_tstamp_verify_if_num(uint32_t if_num)
{
return (if_num == NSS_TSTAMP_TX_INTERFACE) || (if_num == NSS_TSTAMP_RX_INTERFACE);
}
/*
* nss_tstamp_interface_handler()
* Handle NSS -> HLOS messages for TSTAMP Statistics
*/
static void nss_tstamp_interface_handler(struct nss_ctx_instance *nss_ctx,
struct nss_cmn_msg *ncm, __attribute__((unused))void *app_data)
{
struct nss_tstamp_msg *ntm = (struct nss_tstamp_msg *)ncm;
nss_tstamp_msg_callback_t cb;
if (!nss_tstamp_verify_if_num(ncm->interface)) {
nss_warning("%px: invalid interface %d for tstamp_tx", nss_ctx, ncm->interface);
return;
}
/*
* Is this a valid request/response packet?
*/
if (ncm->type >= NSS_TSTAMP_MSG_TYPE_MAX) {
nss_warning("%px: received invalid message %d for tstamp", nss_ctx, ncm->type);
return;
}
if (nss_cmn_get_msg_len(ncm) > sizeof(struct nss_tstamp_msg)) {
nss_warning("%px: Length of message is greater than required: %d", nss_ctx, nss_cmn_get_msg_len(ncm));
return;
}
/*
* Log failures
*/
nss_core_log_msg_failures(nss_ctx, ncm);
switch (ntm->cm.type) {
case NSS_TSTAMP_MSG_TYPE_SYNC_STATS:
nss_tstamp_stats_sync(nss_ctx, &ntm->msg.stats, ncm->interface);
break;
default:
nss_warning("%px: Unknown message type %d",
nss_ctx, ncm->type);
return;
}
/*
* Update the callback and app_data for NOTIFY messages
*/
if (ncm->response == NSS_CMN_RESPONSE_NOTIFY) {
ncm->cb = (nss_ptr_t)nss_tstamp_notify.tstamp_callback;
ncm->app_data = (nss_ptr_t)nss_tstamp_notify.app_data;
}
/*
* Do we have a callback?
*/
if (!ncm->cb) {
return;
}
/*
* callback
*/
cb = (nss_tstamp_msg_callback_t)ncm->cb;
cb((void *)ncm->app_data, ntm);
}
/*
* nss_tstamp_copy_data()
* Copy timestamps from received nss frame into skb
*/
static void nss_tstamp_copy_data(struct nss_tstamp_n2h_pre_hdr *ntm, struct sk_buff *skb)
{
struct skb_shared_hwtstamps *tstamp;
tstamp = skb_hwtstamps(skb);
tstamp->hwtstamp = ktime_set(ntm->ts_data_hi, ntm->ts_data_lo);
#if (LINUX_VERSION_CODE <= KERNEL_VERSION(3, 16, 0))
tstamp->syststamp = ktime_set(ntm->ts_data_hi, ntm->ts_data_lo);
#endif
}
/*
* nss_tstamp_get_dev()
* Get the net_device associated with the packet.
*/
static struct net_device *nss_tstamp_get_dev(struct sk_buff *skb)
{
struct dst_entry *dst;
struct net_device *dev;
struct rtable *rt;
struct flowi6 fl6;
uint32_t ip_addr;
/*
* It seems like the data came over IPsec, hence indicate
* it to the Linux over this interface
*/
skb_reset_network_header(skb);
skb_reset_mac_header(skb);
skb->pkt_type = PACKET_HOST;
switch (ip_hdr(skb)->version) {
case IPVERSION:
ip_addr = ip_hdr(skb)->saddr;
rt = ip_route_output(&init_net, ip_addr, 0, 0, 0);
if (IS_ERR(rt)) {
return NULL;
}
dst = (struct dst_entry *)rt;
skb->protocol = cpu_to_be16(ETH_P_IP);
break;
case 6:
memset(&fl6, 0, sizeof(fl6));
memcpy(&fl6.daddr, &ipv6_hdr(skb)->saddr, sizeof(fl6.daddr));
dst = ip6_route_output(&init_net, NULL, &fl6);
if (IS_ERR(dst)) {
return NULL;
}
skb->protocol = cpu_to_be16(ETH_P_IPV6);
break;
default:
nss_warning("%px:could not get dev for the skb\n", skb);
return NULL;
}
dev = dst->dev;
dev_hold(dev);
dst_release(dst);
return dev;
}
/*
* nss_tstamp_buf_receive()
* Receive nss exception packets.
*/
static void nss_tstamp_buf_receive(struct net_device *ndev, struct sk_buff *skb, struct napi_struct *napi)
{
struct nss_tstamp_n2h_pre_hdr *n2h_hdr = (struct nss_tstamp_n2h_pre_hdr *)skb->data;
struct nss_ctx_instance *nss_ctx;
struct net_device *dev;
uint32_t tstamp_sz;
BUG_ON(!n2h_hdr);
tstamp_sz = n2h_hdr->ts_hdr_sz;
if (tstamp_sz > (NSS_TSTAMP_HEADER_SIZE)) {
goto free;
}
nss_ctx = &nss_top_main.nss[nss_top_main.tstamp_handler_id];
BUG_ON(!nss_ctx);
skb_pull_inline(skb, tstamp_sz);
/*
* copy the time stamp and convert into ktime_t
*/
nss_tstamp_copy_data(n2h_hdr, skb);
if (unlikely(n2h_hdr->ts_tx)) {
/*
* We are in TX Path
*/
skb_tstamp_tx(skb, skb_hwtstamps(skb));
ndev->stats.tx_packets++;
ndev->stats.tx_bytes += skb->len;
goto free;
}
/*
* We are in RX path.
*/
dev = nss_cmn_get_interface_dev(nss_ctx, n2h_hdr->ts_ifnum);
if (!dev) {
ndev->stats.rx_dropped++;
goto free;
}
/*
* Hold the dev until we finish
*/
dev_hold(dev);
switch(dev->type) {
case NSS_IPSEC_ARPHRD_IPSEC:
/*
* Release the prev dev reference
*/
dev_put(dev);
/*
* find the actual IPsec tunnel device
*/
dev = nss_tstamp_get_dev(skb);
break;
default:
/*
* This is a plain non-encrypted data packet.
*/
skb->protocol = eth_type_trans(skb, dev);
break;
}
skb->skb_iif = dev->ifindex;
skb->dev = dev;
ndev->stats.rx_packets++;
ndev->stats.rx_bytes += skb->len;
netif_receive_skb(skb);
/*
* release the device as we are done
*/
dev_put(dev);
return;
free:
dev_kfree_skb_any(skb);
return;
}
/*
* nss_tstamp_tx_buf()
* Send data packet for tstamp processing
*/
nss_tx_status_t nss_tstamp_tx_buf(struct nss_ctx_instance *nss_ctx, struct sk_buff *skb, uint32_t if_num)
{
struct nss_tstamp_h2n_pre_hdr *h2n_hdr;
int extra_head;
int extra_tail = 0;
char *align_data;
uint32_t hdr_sz;
nss_trace("%px: Tstamp If Tx packet, id:%d, data=%px", nss_ctx, NSS_TSTAMP_RX_INTERFACE, skb->data);
/*
* header size + alignment size
*/
hdr_sz = NSS_TSTAMP_HEADER_SIZE;
extra_head = hdr_sz - skb_headroom(skb);
/*
* Expand the head for h2n_hdr
*/
if (extra_head > 0) {
/*
* Try to accommodate using available tailroom.
*/
if (skb->end - skb->tail >= extra_head)
extra_tail = -extra_head;
if (pskb_expand_head(skb, extra_head, extra_tail, GFP_KERNEL)) {
nss_trace("%px: expand head room failed", nss_ctx);
return NSS_TX_FAILURE;
}
}
align_data = PTR_ALIGN((skb->data - hdr_sz), sizeof(uint32_t));
hdr_sz = (nss_ptr_t)skb->data - (nss_ptr_t)align_data;
h2n_hdr = (struct nss_tstamp_h2n_pre_hdr *)skb_push(skb, hdr_sz);
h2n_hdr->ts_ifnum = if_num;
h2n_hdr->ts_tx_hdr_sz = hdr_sz;
return nss_core_send_packet(nss_ctx, skb, NSS_TSTAMP_RX_INTERFACE, H2N_BIT_FLAG_VIRTUAL_BUFFER | H2N_BIT_FLAG_BUFFER_REUSABLE);
}
EXPORT_SYMBOL(nss_tstamp_tx_buf);
/*
* nss_tstamp_register_netdev()
* register dummy netdevice for tstamp interface
*/
struct net_device *nss_tstamp_register_netdev(void)
{
struct net_device *ndev;
uint32_t err = 0;
#if (LINUX_VERSION_CODE <= KERNEL_VERSION(3, 16, 0))
ndev = alloc_netdev(sizeof(struct netdev_priv_instance), "qca-nss-tstamp", nss_tstamp_ndev_setup);
#else
ndev = alloc_netdev(sizeof(struct netdev_priv_instance), "qca-nss-tstamp", NET_NAME_ENUM, nss_tstamp_ndev_setup);
#endif
if (!ndev) {
nss_warning("Tstamp: Could not allocate tstamp net_device ");
return NULL;
}
ndev->netdev_ops = &nss_tstamp_ndev_ops;
err = register_netdev(ndev);
if (err) {
nss_warning("Tstamp: Could not register tstamp net_device ");
free_netdev(ndev);
return NULL;
}
return ndev;
}
/*
* nss_tstamp_notify_register()
* Register to receive tstamp notify messages.
*/
struct nss_ctx_instance *nss_tstamp_notify_register(nss_tstamp_msg_callback_t cb, void *app_data)
{
struct nss_ctx_instance *nss_ctx;
nss_ctx = &nss_top_main.nss[nss_top_main.tstamp_handler_id];
nss_tstamp_notify.tstamp_callback = cb;
nss_tstamp_notify.app_data = app_data;
return nss_ctx;
}
EXPORT_SYMBOL(nss_tstamp_notify_register);
/*
* nss_tstamp_register_handler()
*/
void nss_tstamp_register_handler(struct net_device *ndev)
{
uint32_t features = 0;
struct nss_ctx_instance *nss_ctx;
nss_ctx = &nss_top_main.nss[nss_top_main.tstamp_handler_id];
nss_core_register_subsys_dp(nss_ctx, NSS_TSTAMP_TX_INTERFACE, nss_tstamp_buf_receive, NULL, NULL, ndev, features);
nss_core_register_handler(nss_ctx, NSS_TSTAMP_TX_INTERFACE, nss_tstamp_interface_handler, NULL);
nss_core_register_handler(nss_ctx, NSS_TSTAMP_RX_INTERFACE, nss_tstamp_interface_handler, NULL);
nss_tstamp_stats_dentry_create();
}
| 24.016509 | 128 | 0.720907 |
a7933e9ed59fffa045362882f54c0c5b74603822 | 650 | h | C | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/APMVideoUtils.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-03-29T12:08:37.000Z | 2021-05-26T05:20:11.000Z | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/APMVideoUtils.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | null | null | null | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/APMVideoUtils.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-04-17T03:24:04.000Z | 2022-03-30T05:42:17.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
@interface APMVideoUtils : NSObject
{
}
+ (id)defaultAudioOuputSetting;
+ (void)requestDevicePermission:(unsigned long long)arg1 checked:(unsigned long long)arg2 mediaType:(id)arg3 errorCode:(unsigned long long)arg4 authorized:(_Bool *)arg5 completion:(CDUnknownBlockType)arg6;
+ (void)requestDevicePermission:(unsigned long long)arg1 completion:(CDUnknownBlockType)arg2;
+ (void)requestCameraPermission:(CDUnknownBlockType)arg1;
@end
| 32.5 | 205 | 0.761538 |
80b78365f00cd16b17cd679489ede5eac9ac047c | 3,331 | h | C | Programa/RDS_Con_LCD_EEPROM/Si4703.h | NacioSystems/DESCODIFICADOR-RDS | 57e594d2ddae82364f9b7f4e46a391264d27f023 | [
"CC-BY-4.0"
] | null | null | null | Programa/RDS_Con_LCD_EEPROM/Si4703.h | NacioSystems/DESCODIFICADOR-RDS | 57e594d2ddae82364f9b7f4e46a391264d27f023 | [
"CC-BY-4.0"
] | null | null | null | Programa/RDS_Con_LCD_EEPROM/Si4703.h | NacioSystems/DESCODIFICADOR-RDS | 57e594d2ddae82364f9b7f4e46a391264d27f023 | [
"CC-BY-4.0"
] | null | null | null | /*
* Librería realizada por Ignacio Otero en 2018 a partir
* del ejemplo de SparkFun Si4703 de 2011, de Nathan Seidie
*
* Entre las modificaciones especiales está la utilizacion
* de las interrupciones para la lectura del RDS, por ese
* motivo se cambia la configuración de inicio del Si4703
*
*/
#ifndef Si4703_h
#define Si4703_h
#include "Arduino.h"
class Si4703
{
public:
Si4703(int resetPin, int sdioPin, int sclkPin, int intPin);
uint16_t Registers[16];
void Init();
int seek(byte seekDirection);
int readChannel();
void gotoChannel(int newChannel);
void setVolume(int volume, boolean nomute);
//Nombres de registros Si4703
#define STATUSRSSI 0x0A
#define RDSA 0x0C
#define RDSB 0x0D
#define RDSC 0x0E
#define RDSD 0x0F
//Register 0x06 - SYSCONFIG3
#define VOLEXT 8 // el bit 0x00010000 a 1 pone el volumen a -28dBs
//Register 0x02 - POWERCFG
#define DMUTE 14 // bit desactivación Mute
//Direction used for seeking. Default is down
#define SEEK_DOWN 0
#define SEEK_UP 1
private:
int _resetPin;
int _sdioPin;
int _sclkPin;
int _intPin;
byte updateRegisters(void);
void readRegisters(void);
//void printRegisters(void)
#define FAIL 0
#define SUCCESS 1
//Nombres de registros Si4703
#define DEVICEID 0x00
#define CHIPID 0x01
#define POWERCFG 0x02
#define CHANNEL 0x03
#define SYSCONFIG1 0x04
#define SYSCONFIG2 0x05
#define SYSCONFIG3 0x06
#define READCHAN 0x0B
// Address de Si4703 en I2C
#define SI4703 0x10 //0b._001.0000 = I2C address of Si4703 - note that the Wire function assumes non-left-shifted I2C address, not 0b.0010.000W
#define I2C_FAIL_MAX 10 //This is the number of attempts we will try to contact the device before erroring out
//Register 0x02 - POWERCFG
#define SMUTE 15 // bit desactivación Soft Mute
//static const uint8_t DMUTE = 14; // bit desactivación Mute
#define RDSM 11 // bit de modo RDS 1=Verbose
#define SKMODE 10 // bit Seek Mode, continuo o parada
#define SEEKUP 9 // bit modo Seek, 1 Seek up
#define SEEK 8 // bit activación Seek
#define SEEK_DOWN 0 //Direction used for seeking. Default is down
#define SEEK_UP 1
//Register 0x03 - CHANNEL
#define TUNE 15 // bit activación Tune
//Register 0x04 - SYSCONFIG1
#define RDSIEN 15 // Activa si es 1 las interrupciones cuando hay RDS por GPIO2
#define STCIEN 14 // Activa las interrupciones cuando completa Seek Tune GPIO2
#define RDS 12 // bit activación RDS
#define DE 11 // bit aconfiguración denfasis, EurOpa 1 50us
#define GPIO2b1 2 // GPIO[1:0]=01
//Register 0x05 - SYSCONFIG2
#define SPACE1 5 // bits [5:4] de ajusta banda
#define SPACE0 4 // Europa 50KHz, 01
//Register 0x0A - STATUSRSSI // Por ahora se ven fuera
#define RDSR 15 // bit RDS Ready
#define STC 14 // bit Seek Tone Complete
#define SFBL 13 // bit Seek Fail Band Limit
#define AFCRL 12 // bit validadción canal
#define RDSS 11 // bit RDS sincronizado
#define ST 8 // bit indicador Stereo
};
#endif
| 30.842593 | 150 | 0.653257 |
b95a05ca78006871f634156c0bcea3e56ab91720 | 10,770 | c | C | components/panics/src/memfault_fault_handling_arm.c | ExploramedNC7/memfault-firmware-sdk | 4c418795e5de9f97b87e5966751dc35027238d65 | [
"BSD-3-Clause"
] | null | null | null | components/panics/src/memfault_fault_handling_arm.c | ExploramedNC7/memfault-firmware-sdk | 4c418795e5de9f97b87e5966751dc35027238d65 | [
"BSD-3-Clause"
] | null | null | null | components/panics/src/memfault_fault_handling_arm.c | ExploramedNC7/memfault-firmware-sdk | 4c418795e5de9f97b87e5966751dc35027238d65 | [
"BSD-3-Clause"
] | null | null | null | //! @file
//!
//! Copyright (c) 2019-Present Memfault, Inc.
//! See License.txt for details
//!
//! @brief
//! Fault handling for Cortex M based devices
#include "memfault/panics/fault_handling.h"
#include "memfault/core/platform/core.h"
#include "memfault/panics/arch/arm/cortex_m.h"
#include "memfault/panics/coredump.h"
#include "memfault/panics/coredump_impl.h"
#include "memfault_reboot_tracking_private.h"
static eMfltResetReason s_crash_reason = kMfltRebootReason_Unknown;
typedef MEMFAULT_PACKED_STRUCT MfltCortexMRegs {
uint32_t r0;
uint32_t r1;
uint32_t r2;
uint32_t r3;
uint32_t r4;
uint32_t r5;
uint32_t r6;
uint32_t r7;
uint32_t r8;
uint32_t r9;
uint32_t r10;
uint32_t r11;
uint32_t r12;
uint32_t sp;
uint32_t lr;
uint32_t pc;
uint32_t psr;
uint32_t msp;
uint32_t psp;
} sMfltCortexMRegs;
size_t memfault_coredump_storage_compute_size_required(void) {
// actual values don't matter since we are just computing the size
sMfltCortexMRegs core_regs = { 0 };
sMemfaultCoredumpSaveInfo save_info = {
.regs = &core_regs,
.regs_size = sizeof(core_regs),
.trace_reason = kMfltRebootReason_UnknownError,
};
sCoredumpCrashInfo info = {
// we'll just pass the current stack pointer, value shouldn't matter
.stack_address = (void *)&core_regs,
.trace_reason = save_info.trace_reason,
};
save_info.regions = memfault_platform_coredump_get_regions(&info, &save_info.num_regions);
return memfault_coredump_get_save_size(&save_info);
}
#if defined(__CC_ARM)
static uint32_t prv_read_psp_reg(void) {
register uint32_t reg_val __asm("psp");
return reg_val;
}
static uint32_t prv_read_msp_reg(void) {
register uint32_t reg_val __asm("msp");
return reg_val;
}
#elif defined(__GNUC__) || defined(__clang__)
static uint32_t prv_read_psp_reg(void) {
uint32_t reg_val;
__asm volatile ("mrs %0, psp" : "=r" (reg_val));
return reg_val;
}
static uint32_t prv_read_msp_reg(void) {
uint32_t reg_val;
__asm volatile ("mrs %0, msp" : "=r" (reg_val));
return reg_val;
}
#else
# error "New compiler to add support for!"
#endif
void memfault_fault_handler(const sMfltRegState *regs, eMfltResetReason reason) {
if (s_crash_reason == kMfltRebootReason_Unknown) {
sMfltRebootTrackingRegInfo info = {
.pc = regs->exception_frame->pc,
.lr = regs->exception_frame->lr,
};
memfault_reboot_tracking_mark_reset_imminent(reason, &info);
s_crash_reason = reason;
}
const bool fpu_stack_space_rsvd = ((regs->exc_return & (1 << 4)) == 0);
const bool stack_alignment_forced = ((regs->exception_frame->xpsr & (1 << 9)) != 0);
uint32_t sp_prior_to_exception =
(uint32_t)regs->exception_frame + (fpu_stack_space_rsvd ? 0x68 : 0x20);
if (stack_alignment_forced) {
sp_prior_to_exception += 0x4;
}
const bool msp_was_active = (regs->exc_return & (1 << 3)) == 0;
sMfltCortexMRegs core_regs = {
.r0 = regs->exception_frame->r0,
.r1 = regs->exception_frame->r1,
.r2 = regs->exception_frame->r2,
.r3 = regs->exception_frame->r3,
.r4 = regs->r4,
.r5 = regs->r5,
.r6 = regs->r6,
.r7 = regs->r7,
.r8 = regs->r8,
.r9 = regs->r9,
.r10 = regs->r10,
.r11 = regs->r11,
.r12 = regs->exception_frame->r12,
.sp = sp_prior_to_exception,
.lr = regs->exception_frame->lr,
.pc = regs->exception_frame->pc,
.psr = regs->exception_frame->xpsr,
.msp = msp_was_active ? sp_prior_to_exception : prv_read_msp_reg(),
.psp = !msp_was_active ? sp_prior_to_exception : prv_read_psp_reg(),
};
sMemfaultCoredumpSaveInfo save_info = {
.regs = &core_regs,
.regs_size = sizeof(core_regs),
.trace_reason = s_crash_reason,
};
sCoredumpCrashInfo info = {
.stack_address = (void *)sp_prior_to_exception,
.trace_reason = save_info.trace_reason,
};
save_info.regions = memfault_platform_coredump_get_regions(&info, &save_info.num_regions);
const bool coredump_saved = memfault_coredump_save(&save_info);
if (coredump_saved) {
memfault_reboot_tracking_mark_coredump_saved();
}
memfault_platform_reboot();
MEMFAULT_UNREACHABLE;
}
// By default, exception handlers use CMSIS naming conventions.
// However, if needed, each handler can be renamed using the following
// preprocessor defines:
#ifndef MEMFAULT_EXC_HANDLER_HARD_FAULT
# define MEMFAULT_EXC_HANDLER_HARD_FAULT HardFault_Handler
#endif
#ifndef MEMFAULT_EXC_HANDLER_MEMORY_MANAGEMENT
# define MEMFAULT_EXC_HANDLER_MEMORY_MANAGEMENT MemoryManagement_Handler
#endif
#ifndef MEMFAULT_EXC_HANDLER_BUS_FAULT
# define MEMFAULT_EXC_HANDLER_BUS_FAULT BusFault_Handler
#endif
#ifndef MEMFAULT_EXC_HANDLER_USAGE_FAULT
# define MEMFAULT_EXC_HANDLER_USAGE_FAULT UsageFault_Handler
#endif
#ifndef MEMFAULT_EXC_HANDLER_NMI
# define MEMFAULT_EXC_HANDLER_NMI NMI_Handler
#endif
// The fault handling shims below figure out what stack was being used leading up to the exception,
// build the sMfltRegState argument and pass that as well as the reboot reason to memfault_fault_handler
#if defined(__CC_ARM)
// armcc emits a define for the CPU target. Use that information to decide whether or not to pick
// up the ARMV6M port by default
#if defined(__TARGET_CPU_CORTEX_M0)
#define MEMFAULT_USE_ARMV6M_FAULT_HANDLER 1
#endif
#if !defined(MEMFAULT_USE_ARMV6M_FAULT_HANDLER)
__asm __forceinline void memfault_fault_handling_shim(int reason) {
extern memfault_fault_handler;
tst lr, #4
ite eq
mrseq r3, msp
mrsne r3, psp
push {r3-r11, lr}
mov r1, r0
mov r0, sp
b memfault_fault_handler
ALIGN
}
#else
__asm __forceinline void memfault_fault_handling_shim(int reason) {
extern memfault_fault_handler;
PRESERVE8
mov r1, lr
movs r2, #4
tst r1,r2
mrs r12, msp
beq msp_active_at_crash
mrs r12, psp
msp_active_at_crash mov r3, r11
mov r2, r10
mov r1, r9
mov r9, r0
mov r0, r8
push {r0-r3, lr}
mov r3, r12
push {r3-r7}
mov r0, sp
mov r1, r9
ldr r2, =memfault_fault_handler
bx r2
ALIGN
}
#endif
MEMFAULT_NAKED_FUNC
void MEMFAULT_EXC_HANDLER_HARD_FAULT(void) {
ldr r0, =0x9400 // kMfltRebootReason_HardFault
ldr r1, =memfault_fault_handling_shim
bx r1
ALIGN
}
MEMFAULT_NAKED_FUNC
void MEMFAULT_EXC_HANDLER_MEMORY_MANAGEMENT(void) {
ldr r0, =0x9200 // kMfltRebootReason_MemFault
ldr r1, =memfault_fault_handling_shim
bx r1
ALIGN
}
MEMFAULT_NAKED_FUNC
void MEMFAULT_EXC_HANDLER_BUS_FAULT(void) {
ldr r0, =0x9100 // kMfltRebootReason_BusFault
ldr r1, =memfault_fault_handling_shim
bx r1
ALIGN
}
MEMFAULT_NAKED_FUNC
void MEMFAULT_EXC_HANDLER_USAGE_FAULT(void) {
ldr r0, =0x8002 // kMfltRebootReason_UsageFault
ldr r1, =memfault_fault_handling_shim
bx r1
ALIGN
}
MEMFAULT_NAKED_FUNC
void MEMFAULT_EXC_HANDLER_NMI(void) {
ldr r0, =0x8001 // kMfltRebootReason_Assert
ldr r1, =memfault_fault_handling_shim
bx r1
ALIGN
}
#elif defined(__GNUC__) || defined(__clang__)
#if defined(__ARM_ARCH) && (__ARM_ARCH == 6)
#define MEMFAULT_USE_ARMV6M_FAULT_HANDLER 1
#endif
#if !defined(MEMFAULT_USE_ARMV6M_FAULT_HANDLER)
#define MEMFAULT_HARDFAULT_HANDLING_ASM(_x) \
__asm volatile( \
"tst lr, #4 \n" \
"ite eq \n" \
"mrseq r3, msp \n" \
"mrsne r3, psp \n" \
"push {r3-r11, lr} \n" \
"mov r0, sp \n" \
"ldr r1, =%0 \n" \
"b memfault_fault_handler \n" \
: \
: "i" (_x) \
)
#else
#define MEMFAULT_HARDFAULT_HANDLING_ASM(_x) \
__asm volatile( \
"mov r0, lr \n" \
"movs r1, #4 \n" \
"tst r0,r1 \n" \
"mrs r12, msp \n" \
"beq msp_active_at_crash_%= \n" \
"mrs r12, psp \n" \
"msp_active_at_crash_%=: \n" \
"mov r0, r8 \n" \
"mov r1, r9 \n" \
"mov r2, r10 \n" \
"mov r3, r11 \n" \
"push {r0-r3, lr} \n" \
"mov r3, r12 \n" \
"push {r3-r7} \n" \
"mov r0, sp \n" \
"ldr r1, =%0 \n" \
"b memfault_fault_handler \n" \
: \
: "i" (_x) \
)
#endif
MEMFAULT_NAKED_FUNC
void MEMFAULT_EXC_HANDLER_HARD_FAULT(void) {
MEMFAULT_HARDFAULT_HANDLING_ASM(kMfltRebootReason_HardFault);
}
MEMFAULT_NAKED_FUNC
void MEMFAULT_EXC_HANDLER_MEMORY_MANAGEMENT(void) {
MEMFAULT_HARDFAULT_HANDLING_ASM(kMfltRebootReason_MemFault);
}
MEMFAULT_NAKED_FUNC
void MEMFAULT_EXC_HANDLER_BUS_FAULT(void) {
MEMFAULT_HARDFAULT_HANDLING_ASM(kMfltRebootReason_BusFault);
}
MEMFAULT_NAKED_FUNC
void MEMFAULT_EXC_HANDLER_USAGE_FAULT(void) {
MEMFAULT_HARDFAULT_HANDLING_ASM(kMfltRebootReason_UsageFault);
}
MEMFAULT_NAKED_FUNC
void MEMFAULT_EXC_HANDLER_NMI(void) {
MEMFAULT_HARDFAULT_HANDLING_ASM(kMfltRebootReason_Assert);
}
#else
# error "New compiler to add support for!"
#endif
void memfault_fault_handling_assert(void *pc, void *lr, uint32_t extra) {
sMfltRebootTrackingRegInfo info = {
.pc = (uint32_t)pc,
.lr = (uint32_t)lr,
};
s_crash_reason = kMfltRebootReason_Assert;
memfault_reboot_tracking_mark_reset_imminent(s_crash_reason, &info);
memfault_platform_halt_if_debugging();
// NOTE: Address of NMIPENDSET is a standard (please see
// the "Interrupt Control and State Register" section of the ARMV7-M reference manual)
// Run coredump collection handler from NMI handler
// Benefits:
// At that priority level, we can't get interrupted
// We can leverage the arm architecture to auto-capture register state for us
// If the user is using psp/msp, we start execution from a more predictable stack location
const uint32_t nmipendset_mask = 0x1u << 31;
volatile uint32_t *icsr = (uint32_t *)0xE000ED04;
*icsr |= nmipendset_mask;
__asm("isb");
// We just pend'd a NMI interrupt which is higher priority than any other interrupt and so we
// should not get here unless the this gets called while fault handling is _already_ in progress
// and the NMI is running. In this situation, the best thing that can be done is rebooting the
// system to recover it
memfault_platform_reboot();
}
| 28.567639 | 104 | 0.668988 |
7df6d978f6ae8f12a43ac8b6c7ef2237c3571827 | 20,942 | c | C | crypto777/hmac_sha512.c | who-biz/lightning | 1eea5d935c623e26a085129e967298113c337feb | [
"MIT"
] | 5 | 2017-12-30T19:20:16.000Z | 2019-06-02T04:47:56.000Z | crypto777/hmac_sha512.c | who-biz/lightning | 1eea5d935c623e26a085129e967298113c337feb | [
"MIT"
] | 5 | 2021-02-20T02:41:55.000Z | 2021-06-01T20:04:08.000Z | crypto777/hmac_sha512.c | who-biz/lightning | 1eea5d935c623e26a085129e967298113c337feb | [
"MIT"
] | 7 | 2017-08-25T01:32:54.000Z | 2019-01-02T20:40:42.000Z | /*
* FIPS 180-2 SHA-224/256/384/512 implementation
* Last update: 02/02/2007
* Issue date: 04/30/2005
*
* Copyright (C) 2005, 2007 Olivier Gay <olivier.gay@a3.epfl.ch>
* 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.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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.
*/
#define SHA512_DIGEST_SIZE (512 / 8)
#include <string.h>
#include <stdint.h>
#define SHA512_BLOCK_SIZE (1024 / 8)
typedef struct {
unsigned int tot_len;
unsigned int len;
unsigned char block[2 * SHA512_BLOCK_SIZE];
unsigned long long h[8];
} sha512_ctx;
typedef struct {
sha512_ctx ctx_inside;
sha512_ctx ctx_outside;
/* for hmac_reinit */
sha512_ctx ctx_inside_reinit;
sha512_ctx ctx_outside_reinit;
unsigned char block_ipad[SHA512_BLOCK_SIZE];
unsigned char block_opad[SHA512_BLOCK_SIZE];
} hmac_sha512_ctx;
#define SHFR(x, n) (x >> n)
#define ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n)))
#define CH(x, y, z) ((x & y) ^ (~x & z))
#define MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z))
#define SHA512_F1(x) (ROTR(x, 28) ^ ROTR(x, 34) ^ ROTR(x, 39))
#define SHA512_F2(x) (ROTR(x, 14) ^ ROTR(x, 18) ^ ROTR(x, 41))
#define SHA512_F3(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHFR(x, 7))
#define SHA512_F4(x) (ROTR(x, 19) ^ ROTR(x, 61) ^ SHFR(x, 6))
#define UNPACK32(x, str) \
{ \
*((str) + 3) = (unsigned char) ((x) ); \
*((str) + 2) = (unsigned char) ((x) >> 8); \
*((str) + 1) = (unsigned char) ((x) >> 16); \
*((str) + 0) = (unsigned char) ((x) >> 24); \
}
#define UNPACK64(x, str) \
{ \
*((str) + 7) = (unsigned char) ((x) ); \
*((str) + 6) = (unsigned char) ((x) >> 8); \
*((str) + 5) = (unsigned char) ((x) >> 16); \
*((str) + 4) = (unsigned char) ((x) >> 24); \
*((str) + 3) = (unsigned char) ((x) >> 32); \
*((str) + 2) = (unsigned char) ((x) >> 40); \
*((str) + 1) = (unsigned char) ((x) >> 48); \
*((str) + 0) = (unsigned char) ((x) >> 56); \
}
#define PACK64(str, x) \
{ \
*(x) = ((unsigned long long) *((str) + 7) ) \
| ((unsigned long long) *((str) + 6) << 8) \
| ((unsigned long long) *((str) + 5) << 16) \
| ((unsigned long long) *((str) + 4) << 24) \
| ((unsigned long long) *((str) + 3) << 32) \
| ((unsigned long long) *((str) + 2) << 40) \
| ((unsigned long long) *((str) + 1) << 48) \
| ((unsigned long long) *((str) + 0) << 56); \
}
/* Macros used for loops unrolling */
#define SHA512_SCR(i) \
{ \
w[i] = SHA512_F4(w[i - 2]) + w[i - 7] \
+ SHA512_F3(w[i - 15]) + w[i - 16]; \
}
#define SHA512_EXP(a, b, c, d, e, f, g ,h, j) \
{ \
t1 = wv[h] + SHA512_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) \
+ sha512_k[j] + w[j]; \
t2 = SHA512_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \
wv[d] += t1; \
wv[h] = t1 + t2; \
}
static unsigned long long sha512_h0[8] = {
0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL,
0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL,
0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL
};
static unsigned long long sha512_k[80] = {
0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL
};
static void sha512_transf(sha512_ctx * ctx, const unsigned char *message,
unsigned int block_nb)
{
unsigned long long w[80];
unsigned long long wv[8];
unsigned long long t1, t2;
const unsigned char *sub_block;
int i, j;
for (i = 0; i < (int)block_nb; i++) {
sub_block = message + (i << 7);
PACK64(&sub_block[0], &w[0]);
PACK64(&sub_block[8], &w[1]);
PACK64(&sub_block[16], &w[2]);
PACK64(&sub_block[24], &w[3]);
PACK64(&sub_block[32], &w[4]);
PACK64(&sub_block[40], &w[5]);
PACK64(&sub_block[48], &w[6]);
PACK64(&sub_block[56], &w[7]);
PACK64(&sub_block[64], &w[8]);
PACK64(&sub_block[72], &w[9]);
PACK64(&sub_block[80], &w[10]);
PACK64(&sub_block[88], &w[11]);
PACK64(&sub_block[96], &w[12]);
PACK64(&sub_block[104], &w[13]);
PACK64(&sub_block[112], &w[14]);
PACK64(&sub_block[120], &w[15]);
SHA512_SCR(16);
SHA512_SCR(17);
SHA512_SCR(18);
SHA512_SCR(19);
SHA512_SCR(20);
SHA512_SCR(21);
SHA512_SCR(22);
SHA512_SCR(23);
SHA512_SCR(24);
SHA512_SCR(25);
SHA512_SCR(26);
SHA512_SCR(27);
SHA512_SCR(28);
SHA512_SCR(29);
SHA512_SCR(30);
SHA512_SCR(31);
SHA512_SCR(32);
SHA512_SCR(33);
SHA512_SCR(34);
SHA512_SCR(35);
SHA512_SCR(36);
SHA512_SCR(37);
SHA512_SCR(38);
SHA512_SCR(39);
SHA512_SCR(40);
SHA512_SCR(41);
SHA512_SCR(42);
SHA512_SCR(43);
SHA512_SCR(44);
SHA512_SCR(45);
SHA512_SCR(46);
SHA512_SCR(47);
SHA512_SCR(48);
SHA512_SCR(49);
SHA512_SCR(50);
SHA512_SCR(51);
SHA512_SCR(52);
SHA512_SCR(53);
SHA512_SCR(54);
SHA512_SCR(55);
SHA512_SCR(56);
SHA512_SCR(57);
SHA512_SCR(58);
SHA512_SCR(59);
SHA512_SCR(60);
SHA512_SCR(61);
SHA512_SCR(62);
SHA512_SCR(63);
SHA512_SCR(64);
SHA512_SCR(65);
SHA512_SCR(66);
SHA512_SCR(67);
SHA512_SCR(68);
SHA512_SCR(69);
SHA512_SCR(70);
SHA512_SCR(71);
SHA512_SCR(72);
SHA512_SCR(73);
SHA512_SCR(74);
SHA512_SCR(75);
SHA512_SCR(76);
SHA512_SCR(77);
SHA512_SCR(78);
SHA512_SCR(79);
wv[0] = ctx->h[0];
wv[1] = ctx->h[1];
wv[2] = ctx->h[2];
wv[3] = ctx->h[3];
wv[4] = ctx->h[4];
wv[5] = ctx->h[5];
wv[6] = ctx->h[6];
wv[7] = ctx->h[7];
j = 0;
do {
SHA512_EXP(0, 1, 2, 3, 4, 5, 6, 7, j);
j++;
SHA512_EXP(7, 0, 1, 2, 3, 4, 5, 6, j);
j++;
SHA512_EXP(6, 7, 0, 1, 2, 3, 4, 5, j);
j++;
SHA512_EXP(5, 6, 7, 0, 1, 2, 3, 4, j);
j++;
SHA512_EXP(4, 5, 6, 7, 0, 1, 2, 3, j);
j++;
SHA512_EXP(3, 4, 5, 6, 7, 0, 1, 2, j);
j++;
SHA512_EXP(2, 3, 4, 5, 6, 7, 0, 1, j);
j++;
SHA512_EXP(1, 2, 3, 4, 5, 6, 7, 0, j);
j++;
} while (j < 80);
ctx->h[0] += wv[0];
ctx->h[1] += wv[1];
ctx->h[2] += wv[2];
ctx->h[3] += wv[3];
ctx->h[4] += wv[4];
ctx->h[5] += wv[5];
ctx->h[6] += wv[6];
ctx->h[7] += wv[7];
}
}
static void _sha512_init(sha512_ctx * ctx)
{
ctx->h[0] = sha512_h0[0];
ctx->h[1] = sha512_h0[1];
ctx->h[2] = sha512_h0[2];
ctx->h[3] = sha512_h0[3];
ctx->h[4] = sha512_h0[4];
ctx->h[5] = sha512_h0[5];
ctx->h[6] = sha512_h0[6];
ctx->h[7] = sha512_h0[7];
ctx->len = 0;
ctx->tot_len = 0;
}
static void sha512_update(sha512_ctx * ctx, const unsigned char *message,
unsigned int len)
{
unsigned int block_nb;
unsigned int new_len, rem_len, tmp_len;
const unsigned char *shifted_message;
tmp_len = SHA512_BLOCK_SIZE - ctx->len;
rem_len = len < tmp_len ? len : tmp_len;
memcpy(&ctx->block[ctx->len], message, rem_len);
if (ctx->len + len < SHA512_BLOCK_SIZE) {
ctx->len += len;
return;
}
new_len = len - rem_len;
block_nb = new_len / SHA512_BLOCK_SIZE;
shifted_message = message + rem_len;
sha512_transf(ctx, ctx->block, 1);
sha512_transf(ctx, shifted_message, block_nb);
rem_len = new_len % SHA512_BLOCK_SIZE;
memcpy(ctx->block, &shifted_message[block_nb << 7], rem_len);
ctx->len = rem_len;
ctx->tot_len += (block_nb + 1) << 7;
}
static void sha512_final(sha512_ctx * ctx, unsigned char *digest)
{
unsigned int block_nb;
unsigned int pm_len;
unsigned int len_b;
block_nb = 1 + ((SHA512_BLOCK_SIZE - 17)
< (ctx->len % SHA512_BLOCK_SIZE));
len_b = (ctx->tot_len + ctx->len) << 3;
pm_len = block_nb << 7;
memset(ctx->block + ctx->len, 0, pm_len - ctx->len);
ctx->block[ctx->len] = 0x80;
UNPACK32(len_b, ctx->block + pm_len - 4);
sha512_transf(ctx, ctx->block, block_nb);
UNPACK64(ctx->h[0], &digest[0]);
UNPACK64(ctx->h[1], &digest[8]);
UNPACK64(ctx->h[2], &digest[16]);
UNPACK64(ctx->h[3], &digest[24]);
UNPACK64(ctx->h[4], &digest[32]);
UNPACK64(ctx->h[5], &digest[40]);
UNPACK64(ctx->h[6], &digest[48]);
UNPACK64(ctx->h[7], &digest[56]);
}
void sha512(const unsigned char *message, unsigned int len,unsigned char *digest)
{
sha512_ctx ctx;
_sha512_init(&ctx);
sha512_update(&ctx, message, len);
sha512_final(&ctx, digest);
}
int32_t init_hexbytes_noT(char *hexbytes,uint8_t *message,long len);
void calc_sha512(char *str,uint8_t *digest,uint8_t *message,int32_t len)
{
sha512_ctx ctx;
_sha512_init(&ctx);
sha512_update(&ctx, message, len);
sha512_final(&ctx, digest);
if ( str != 0 )
init_hexbytes_noT(str,digest,512>>3);
}
static void hmac_sha512_init(hmac_sha512_ctx * ctx, const unsigned char *key,unsigned int key_size)
{
unsigned int fill;
unsigned int num;
const unsigned char *key_used;
unsigned char key_temp[SHA512_DIGEST_SIZE];
int i;
if (key_size == SHA512_BLOCK_SIZE) {
key_used = key;
num = SHA512_BLOCK_SIZE;
} else {
if (key_size > SHA512_BLOCK_SIZE) {
num = SHA512_DIGEST_SIZE;
sha512(key, key_size, key_temp);
key_used = key_temp;
} else { /* key_size > SHA512_BLOCK_SIZE */
key_used = key;
num = key_size;
}
fill = SHA512_BLOCK_SIZE - num;
memset(ctx->block_ipad + num, 0x36, fill);
memset(ctx->block_opad + num, 0x5c, fill);
}
for (i = 0; i < (int)num; i++) {
ctx->block_ipad[i] = key_used[i] ^ 0x36;
ctx->block_opad[i] = key_used[i] ^ 0x5c;
}
_sha512_init(&ctx->ctx_inside);
sha512_update(&ctx->ctx_inside, ctx->block_ipad, SHA512_BLOCK_SIZE);
_sha512_init(&ctx->ctx_outside);
sha512_update(&ctx->ctx_outside, ctx->block_opad, SHA512_BLOCK_SIZE);
/* for hmac_reinit */
memcpy(&ctx->ctx_inside_reinit, &ctx->ctx_inside, sizeof(sha512_ctx));
memcpy(&ctx->ctx_outside_reinit, &ctx->ctx_outside, sizeof(sha512_ctx));
}
static void hmac_sha512_update(hmac_sha512_ctx * ctx, const unsigned char *message,
unsigned int message_len)
{
sha512_update(&ctx->ctx_inside, message, message_len);
}
static void hmac_sha512_final(hmac_sha512_ctx * ctx, unsigned char *mac,
unsigned int mac_size)
{
unsigned char digest_inside[SHA512_DIGEST_SIZE];
unsigned char mac_temp[SHA512_DIGEST_SIZE];
sha512_final(&ctx->ctx_inside, digest_inside);
sha512_update(&ctx->ctx_outside, digest_inside, SHA512_DIGEST_SIZE);
sha512_final(&ctx->ctx_outside, mac_temp);
memcpy(mac, mac_temp, mac_size);
}
void hmac_sha512str(const unsigned char *key, unsigned int key_size,
const unsigned char *message, unsigned int message_len,
unsigned char *mac, unsigned mac_size)
{
hmac_sha512_ctx ctx;
hmac_sha512_init(&ctx, key, key_size);
hmac_sha512_update(&ctx, message, message_len);
hmac_sha512_final(&ctx, mac, mac_size);
}
int init_hexbytes_noT(char *hexbytes,unsigned char *message,long len);
#ifndef libtom_hmac
#define libtom_hmac
#include "hmac/crypt_argchk.c"
#include "hmac/hash_memory.c"
#include "hmac/hmac_init.c"
#include "hmac/hmac_process.c"
#include "hmac/hmac_done.c"
#include "hmac/hmac_file.c"
#include "hmac/hmac_memory.c"
#include "hmac/rmd128.c"
#include "hmac/rmd160.c"
#include "hmac/rmd256.c"
#include "hmac/rmd320.c"
#include "hmac/tiger.c"
#include "hmac/md2.c"
#include "hmac/md4.c"
#include "hmac/md5.c"
#include "hmac/sha1.c"
#include "hmac/whirl.c"
#include "hmac/sha224.c"
#include "hmac/sha256.c"
#include "hmac/sha384.c"
#include "hmac/sha512.c"
#endif
char *hmac_sha512_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[SHA512_DIGEST_SIZE],checkbuf[SHA512_DIGEST_SIZE*2 + 1]; char dest2[SHA512_DIGEST_SIZE*2 + 1]; unsigned long size = sizeof(checkbuf);
//int i;
hmac_sha512str((const unsigned char *)key,key_size,(const unsigned char *)message,(int)strlen(message),mac,SHA512_DIGEST_SIZE);
//for (i=0; i<SHA512_DIGEST_SIZE; i++)
// sprintf(&dest[i*2],"%02x", mac[i]);
//dest[2 * SHA512_DIGEST_SIZE] = '\0';
hmac_memory(&sha512_desc,(void *)key,key_size,(void *)message,strlen(message),checkbuf,&size);
init_hexbytes_noT(dest,mac,SHA512_DIGEST_SIZE);
init_hexbytes_noT(dest2,checkbuf,SHA512_DIGEST_SIZE);
if ( memcmp(checkbuf,mac,SHA512_DIGEST_SIZE) != 0 )
printf("hmac_512 : %s vs %s\n",dest,dest2);
return(dest);
}
char *hmac_sha384_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&sha384_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
void calc_hmac_sha256(uint8_t *mac,int32_t maclen,uint8_t *key,int32_t key_size,uint8_t *message,int32_t len)
{
unsigned long size = maclen;
hmac_memory(&sha256_desc,(void *)key,key_size,(void *)message,len,mac,&size);
}
char *hmac_sha256_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&sha256_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_sha224_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&sha224_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_rmd320_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&rmd320_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_rmd256_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&rmd256_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_rmd160_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&rmd160_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_rmd128_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&rmd128_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_sha1_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&sha1_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_md2_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&md2_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_md4_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&md4_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_md5_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&md5_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_tiger_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&tiger_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_whirlpool_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&whirlpool_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
void calc_md2str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
bits128 x;
calc_md2(hexstr,buf,msg,len);
decode_hex(buf,sizeof(x),hexstr);
//memcpy(buf,x.bytes,sizeof(x));
}
void calc_md4str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
bits128 x;
calc_md4(hexstr,buf,msg,len);
decode_hex(buf,sizeof(x),hexstr);
//memcpy(buf,x.bytes,sizeof(x));
}
void calc_md5str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
bits128 x;
calc_md5(hexstr,msg,len);
decode_hex(buf,sizeof(x),hexstr);
//memcpy(buf,x.bytes,sizeof(x));
}
| 32.268105 | 151 | 0.647789 |
f16bbbd5d4ebd04cd5b87421a265c4a0b24c8587 | 963 | h | C | PrivateFrameworks/OfficeImport/OISFUJsonScanner.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 17 | 2018-11-13T04:02:58.000Z | 2022-01-20T09:27:13.000Z | PrivateFrameworks/OfficeImport/OISFUJsonScanner.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 3 | 2018-04-06T02:02:27.000Z | 2018-10-02T01:12:10.000Z | PrivateFrameworks/OfficeImport/OISFUJsonScanner.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 1 | 2018-09-28T13:54:23.000Z | 2018-09-28T13:54:23.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class NSCharacterSet, NSString;
__attribute__((visibility("hidden")))
@interface OISFUJsonScanner : NSObject
{
NSString *mString;
unsigned short *mCharacters;
unsigned long long mLength;
unsigned long long mOffset;
NSCharacterSet *mWhitespaceCharacterSet;
NSCharacterSet *mDecimalDigitCharacterSet;
}
- (id)parseObjectWithMaxDepth:(int)arg1;
- (id)parseNumber;
- (id)parseFalse;
- (id)parseTrue;
- (id)parseNull;
- (BOOL)parseConstantString:(const char *)arg1;
- (id)parseArrayWithMaxDepth:(int)arg1;
- (id)parseDictionaryWithMaxDepth:(int)arg1;
- (id)parseString;
- (void)appendCharactersInRange:(struct _NSRange)arg1 toString:(id)arg2;
- (id)parseHexCharacter;
- (void)skipWhitespace;
- (unsigned short)nextCharacter;
- (void)dealloc;
- (id)initWithString:(id)arg1;
@end
| 24.075 | 83 | 0.73001 |
ccba15a49f471ac3be99de40c156d1e2c8161539 | 306 | h | C | DDModels/DDModels/Classes/DDDataModels/Models/LocationsDM/DDLocationsAPIM.h | syedqamara/Dastak | e4016e0d43cfd782f99708339331c8ed37eaaf5e | [
"MIT"
] | null | null | null | DDModels/DDModels/Classes/DDDataModels/Models/LocationsDM/DDLocationsAPIM.h | syedqamara/Dastak | e4016e0d43cfd782f99708339331c8ed37eaaf5e | [
"MIT"
] | null | null | null | DDModels/DDModels/Classes/DDDataModels/Models/LocationsDM/DDLocationsAPIM.h | syedqamara/Dastak | e4016e0d43cfd782f99708339331c8ed37eaaf5e | [
"MIT"
] | null | null | null | //
// DDLocationsAPIM.h
// DDModels
//
// Created by Zubair Ahmad on 04/02/2020.
//
#import "DDBaseApiModel.h"
#import "DDLocationsData.h"
NS_ASSUME_NONNULL_BEGIN
@interface DDLocationsAPIM : DDBaseApiModel
@property (nonatomic, strong) DDLocationsData <Optional> * data;
@end
NS_ASSUME_NONNULL_END
| 17 | 64 | 0.75817 |
78eb4d979c352230f637b9514043bc66f0a6d7a6 | 864 | c | C | C/other/check_for_subsequence.c | zhcet19/NeoAlgo-1 | c534a23307109280bda0e4867d6e8e490002a4ee | [
"MIT"
] | 897 | 2020-06-25T00:12:52.000Z | 2022-03-24T00:49:31.000Z | C/other/check_for_subsequence.c | zhcet19/NeoAlgo-1 | c534a23307109280bda0e4867d6e8e490002a4ee | [
"MIT"
] | 5,707 | 2020-06-24T17:53:28.000Z | 2022-01-22T05:03:15.000Z | C/other/check_for_subsequence.c | zhcet19/NeoAlgo-1 | c534a23307109280bda0e4867d6e8e490002a4ee | [
"MIT"
] | 1,817 | 2020-06-25T03:51:05.000Z | 2022-03-29T05:14:07.000Z | #include <stdio.h>
#include <string.h>
int main()
{
char str1[1000] , str2[1000];
int i = 0 , j = 0; // i will point to string 1 and j will point to string 2
printf(" Enter first string :\n");
scanf("%s" , str1); // str1 is substring
printf(" Enter second string :\n");
scanf("%s" , str2); //str2 is full string
while (i < strlen(str1) && j < strlen(str2))
{
if (str1[i] == str2[j])
{
i++;
}
j++;
}
if (i == strlen(str1))
{
printf("Yes, str1 is substring of str2\n");
}
else
{
printf("No, str1 is not a substring of str2\n");
}
return 0;
}
/*
Time Complexity: O(n)
Space Complexity: O(1)
Input:
DTH SDFDTHFGB
QBR EQVBA
Output:
Yes, str1 is substring of str2
No, str1 is not substring of str2
*/
| 19.636364 | 100 | 0.513889 |
00b26fedc523fcf89378826990d093615fcbc17d | 679 | h | C | HeterogeneousCore/SonicCore/interface/SonicClient.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | HeterogeneousCore/SonicCore/interface/SonicClient.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | HeterogeneousCore/SonicCore/interface/SonicClient.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #ifndef HeterogeneousCore_SonicCore_SonicClient
#define HeterogeneousCore_SonicCore_SonicClient
#include "HeterogeneousCore/SonicCore/interface/SonicClientBase.h"
#include "HeterogeneousCore/SonicCore/interface/SonicClientTypes.h"
//convenience definition for multiple inheritance (base and types)
template <typename InputT, typename OutputT = InputT>
class SonicClient : public SonicClientBase, public SonicClientTypes<InputT, OutputT> {
public:
//constructor
SonicClient(const edm::ParameterSet& params, const std::string& debugName, const std::string& clientName)
: SonicClientBase(params, debugName, clientName), SonicClientTypes<InputT, OutputT>() {}
};
#endif
| 39.941176 | 107 | 0.81296 |
faca1ddd792f036052a0fab87e6ac4b0252a80a2 | 2,252 | h | C | Common/MdfModel/HillShade.h | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 2 | 2017-04-19T01:38:30.000Z | 2020-07-31T03:05:32.000Z | Common/MdfModel/HillShade.h | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | null | null | null | Common/MdfModel/HillShade.h | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 1 | 2021-12-29T10:46:12.000Z | 2021-12-29T10:46:12.000Z | //
// Copyright (C) 2004-2011 by Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of version 2.1 of the GNU Lesser
// General Public License as published by the Free Software Foundation.
//
// 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
#ifndef HILLSHADE_H_
#define HILLSHADE_H_
#include <vector>
#include "MdfRootObject.h"
BEGIN_NAMESPACE_MDFMODEL
//-------------------------------------------------------------------------
// DESCRIPTION:
// Class HillShade is used to specify how to shade given a band and a light
// source.
//-------------------------------------------------------------------------
class MDFMODEL_API HillShade : public MdfRootObject
{
public:
HillShade();
virtual ~HillShade();
// Property : Band
const MdfString& GetBand() const;
void SetBand(const MdfString& strBandName);
// Property : Azimuth, in degrees.
double GetAzimuth() const;
void SetAzimuth(double dAzimuth);
// Property : Altitude, in degrees.
double GetAltitude() const;
void SetAltitude(double dAltitude);
// Property : Scale Factor, Optional. Default value is 1.
// Apply to band before computing hillshade.
double GetScaleFactor() const;
void SetScaleFactor(double dScaleFactor);
private:
// Hidden copy constructor and assignment.
HillShade(const HillShade &);
HillShade& operator = (const HillShade &);
// Band
MdfString m_strBandName;
// Azimuth
double m_dAzimuth;
// Altitude
double m_dAltitude;
// Scale Factor
double m_dScaleFactor;
};
END_NAMESPACE_MDFMODEL
#endif // HILLSHADE_H_
| 30.432432 | 79 | 0.617229 |
784929be73cd19704ae77775799bb7367f9ceb3b | 2,621 | c | C | pepdna/kmodule/core.c | kr1stj0n/pep-dna | 17136ca8c16238423bf1ca1ab4302d51d2fc8e57 | [
"RSA-MD",
"Linux-OpenIB",
"FTL",
"TCP-wrappers",
"CECILL-B"
] | 3 | 2021-11-12T13:01:51.000Z | 2022-02-19T09:06:23.000Z | pepdna/kmodule/core.c | kr1stj0n/pep-dna | 17136ca8c16238423bf1ca1ab4302d51d2fc8e57 | [
"RSA-MD",
"Linux-OpenIB",
"FTL",
"TCP-wrappers",
"CECILL-B"
] | null | null | null | pepdna/kmodule/core.c | kr1stj0n/pep-dna | 17136ca8c16238423bf1ca1ab4302d51d2fc8e57 | [
"RSA-MD",
"Linux-OpenIB",
"FTL",
"TCP-wrappers",
"CECILL-B"
] | null | null | null | /*
* pep-dna/pepdna/kmodule/core.c: PEP-DNA core module
*
* Copyright (C) 2020 Kristjon Ciko <kristjoc@ifi.uio.no>
*
* 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 3 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 <https://www.gnu.org/licenses/>.
*/
#include "core.h"
#include "server.h"
#include "tcp_utils.h"
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/moduleparam.h>
/* START of Module Parameters */
int port = 0;
module_param(port, int, 0644);
MODULE_PARM_DESC(port, "TCP port for listen()");
int mode = -1;
module_param(mode, int, 0644);
MODULE_PARM_DESC(mode,
"TCP2TCP | TCP2RINA | TCP2CCN | RINA2TCP | RINA2RINA | CCN2TCP | CCN2CCN");
/* END of Module Parameters */
int sysctl_pepdna_sock_rmem[3] __read_mostly; /* min/default/max */
int sysctl_pepdna_sock_wmem[3] __read_mostly; /* min/default/max */
static const char* get_mode_name(void)
{
switch (mode) {
case 0: return "TCP2TCP";
case 1: return "TCP2RINA";
case 2: return "TCP2CCN";
case 3: return "RINA2TCP";
case 4: return "RINA2RINA";
case 5: return "CCN2TCP";
case 6: return "CCN2CCN";
default: return "ERROR";
}
}
static int __init pepdna_init(void)
{
int rc = 0;
sysctl_pepdna_sock_rmem[0] = RCVBUF_MIN;
sysctl_pepdna_sock_rmem[1] = RCVBUF_DEF;
sysctl_pepdna_sock_rmem[2] = RCVBUF_MAX;
sysctl_pepdna_sock_wmem[0] = SNDBUF_MIN;
sysctl_pepdna_sock_wmem[1] = SNDBUF_DEF;
sysctl_pepdna_sock_wmem[2] = SNDBUF_MAX;
rc = pepdna_register_sysctl();
if (rc) {
pr_err("Register sysctl failed with err. %d", rc);
return rc;
}
rc = pepdna_server_start();
if (rc < 0)
pr_err("PEP-DNA LKM loaded with errors");
pep_info("PEP-DNA LKM loaded succesfully in %s mode", get_mode_name());
return rc;
}
static void __exit pepdna_exit(void)
{
pepdna_server_stop();
pepdna_unregister_sysctl();
}
/*
* register init/exit functions
*/
module_init(pepdna_init);
module_exit(pepdna_exit);
/* module metadata */
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Kr1stj0n C1k0");
MODULE_VERSION(PEPDNA_MOD_VER);
MODULE_DESCRIPTION("PEP-DNA kernel module");
| 25.950495 | 80 | 0.71652 |
285ba69095b5c919f08c8bd33e77b408a584001f | 316 | h | C | EaseIM/EaseIM/Class/Settings/ConnectUs/EMAboutHuanXinViewController.h | jinliang04551/chat-ios | 578c2d95a63c31e6ae0a0465d2e9fc24a5309b69 | [
"Apache-2.0"
] | 16 | 2020-09-27T08:52:39.000Z | 2022-02-28T02:57:32.000Z | EaseIM/EaseIM/Class/Settings/ConnectUs/EMAboutHuanXinViewController.h | jinliang04551/chat-ios | 578c2d95a63c31e6ae0a0465d2e9fc24a5309b69 | [
"Apache-2.0"
] | 7 | 2021-02-08T04:04:26.000Z | 2021-12-15T02:29:50.000Z | EaseIM/EaseIM/Class/Settings/ConnectUs/EMAboutHuanXinViewController.h | jinliang04551/chat-ios | 578c2d95a63c31e6ae0a0465d2e9fc24a5309b69 | [
"Apache-2.0"
] | 18 | 2020-09-24T05:07:01.000Z | 2022-03-11T09:06:43.000Z | //
// EMAboutHuanXinViewController.h
// EaseIM
//
// Created by 娜塔莎 on 2020/6/9.
// Copyright © 2020 zmw. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "EMRefreshViewController.h"
NS_ASSUME_NONNULL_BEGIN
@interface EMAboutHuanXinViewController : EMRefreshViewController
@end
NS_ASSUME_NONNULL_END
| 16.631579 | 65 | 0.765823 |
9e51292f47ea6945feacb43a0bc8d18a9c27983b | 14,631 | h | C | core/hash_map.h | Layer3/godot-OpenAudioSolution | 9872e53ea1f459ca8308d5d481a71fc1ba52d1c3 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 5 | 2015-10-06T07:56:16.000Z | 2016-10-02T21:18:51.000Z | core/hash_map.h | Layer3/godot-OpenAudioSolution | 9872e53ea1f459ca8308d5d481a71fc1ba52d1c3 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 8 | 2018-07-08T17:53:29.000Z | 2020-07-18T06:40:37.000Z | core/hash_map.h | Layer3/godot-OpenAudioSolution | 9872e53ea1f459ca8308d5d481a71fc1ba52d1c3 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 2 | 2016-02-05T18:51:02.000Z | 2020-06-05T20:30:08.000Z | /*************************************************************************/
/* hash_map.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef HASH_MAP_H
#define HASH_MAP_H
#include "core/error_macros.h"
#include "core/hashfuncs.h"
#include "core/list.h"
#include "core/math/math_funcs.h"
#include "core/os/memory.h"
#include "core/ustring.h"
/**
* @class HashMap
* @author Juan Linietsky <reduzio@gmail.com>
*
* Implementation of a standard Hashing HashMap, for quick lookups of Data associated with a Key.
* The implementation provides hashers for the default types, if you need a special kind of hasher, provide
* your own.
* @param TKey Key, search is based on it, needs to be hasheable. It is unique in this container.
* @param TData Data, data associated with the key
* @param Hasher Hasher object, needs to provide a valid static hash function for TKey
* @param Comparator comparator object, needs to be able to safely compare two TKey values. It needs to ensure that x == x for any items inserted in the map. Bear in mind that nan != nan when implementing an equality check.
* @param MIN_HASH_TABLE_POWER Miminum size of the hash table, as a power of two. You rarely need to change this parameter.
* @param RELATIONSHIP Relationship at which the hash table is resized. if amount of elements is RELATIONSHIP
* times bigger than the hash table, table is resized to solve this condition. if RELATIONSHIP is zero, table is always MIN_HASH_TABLE_POWER.
*
*/
template <class TKey, class TData, class Hasher = HashMapHasherDefault, class Comparator = HashMapComparatorDefault<TKey>, uint8_t MIN_HASH_TABLE_POWER = 3, uint8_t RELATIONSHIP = 8>
class HashMap {
public:
struct Pair {
TKey key;
TData data;
Pair() {}
Pair(const TKey &p_key, const TData &p_data) :
key(p_key),
data(p_data) {
}
};
struct Element {
private:
friend class HashMap;
uint32_t hash;
Element *next;
Element() { next = 0; }
Pair pair;
public:
const TKey &key() const {
return pair.key;
}
TData &value() {
return pair.data;
}
const TData &value() const {
return pair.value();
}
};
private:
Element **hash_table;
uint8_t hash_table_power;
uint32_t elements;
void make_hash_table() {
ERR_FAIL_COND(hash_table);
hash_table = memnew_arr(Element *, (1 << MIN_HASH_TABLE_POWER));
hash_table_power = MIN_HASH_TABLE_POWER;
elements = 0;
for (int i = 0; i < (1 << MIN_HASH_TABLE_POWER); i++)
hash_table[i] = 0;
}
void erase_hash_table() {
ERR_FAIL_COND_MSG(elements, "Cannot erase hash table if there are still elements inside.");
memdelete_arr(hash_table);
hash_table = 0;
hash_table_power = 0;
elements = 0;
}
void check_hash_table() {
int new_hash_table_power = -1;
if ((int)elements > ((1 << hash_table_power) * RELATIONSHIP)) {
/* rehash up */
new_hash_table_power = hash_table_power + 1;
while ((int)elements > ((1 << new_hash_table_power) * RELATIONSHIP)) {
new_hash_table_power++;
}
} else if ((hash_table_power > (int)MIN_HASH_TABLE_POWER) && ((int)elements < ((1 << (hash_table_power - 1)) * RELATIONSHIP))) {
/* rehash down */
new_hash_table_power = hash_table_power - 1;
while ((int)elements < ((1 << (new_hash_table_power - 1)) * RELATIONSHIP)) {
new_hash_table_power--;
}
if (new_hash_table_power < (int)MIN_HASH_TABLE_POWER)
new_hash_table_power = MIN_HASH_TABLE_POWER;
}
if (new_hash_table_power == -1)
return;
Element **new_hash_table = memnew_arr(Element *, ((uint64_t)1 << new_hash_table_power));
ERR_FAIL_COND_MSG(!new_hash_table, "Out of memory.");
for (int i = 0; i < (1 << new_hash_table_power); i++) {
new_hash_table[i] = 0;
}
if (hash_table) {
for (int i = 0; i < (1 << hash_table_power); i++) {
while (hash_table[i]) {
Element *se = hash_table[i];
hash_table[i] = se->next;
int new_pos = se->hash & ((1 << new_hash_table_power) - 1);
se->next = new_hash_table[new_pos];
new_hash_table[new_pos] = se;
}
}
memdelete_arr(hash_table);
}
hash_table = new_hash_table;
hash_table_power = new_hash_table_power;
}
/* I want to have only one function.. */
_FORCE_INLINE_ const Element *get_element(const TKey &p_key) const {
uint32_t hash = Hasher::hash(p_key);
uint32_t index = hash & ((1 << hash_table_power) - 1);
Element *e = hash_table[index];
while (e) {
/* checking hash first avoids comparing key, which may take longer */
if (e->hash == hash && Comparator::compare(e->pair.key, p_key)) {
/* the pair exists in this hashtable, so just update data */
return e;
}
e = e->next;
}
return NULL;
}
Element *create_element(const TKey &p_key) {
/* if element doesn't exist, create it */
Element *e = memnew(Element);
ERR_FAIL_COND_V_MSG(!e, NULL, "Out of memory.");
uint32_t hash = Hasher::hash(p_key);
uint32_t index = hash & ((1 << hash_table_power) - 1);
e->next = hash_table[index];
e->hash = hash;
e->pair.key = p_key;
e->pair.data = TData();
hash_table[index] = e;
elements++;
return e;
}
void copy_from(const HashMap &p_t) {
if (&p_t == this)
return; /* much less bother with that */
clear();
if (!p_t.hash_table || p_t.hash_table_power == 0)
return; /* not copying from empty table */
hash_table = memnew_arr(Element *, (uint64_t)1 << p_t.hash_table_power);
hash_table_power = p_t.hash_table_power;
elements = p_t.elements;
for (int i = 0; i < (1 << p_t.hash_table_power); i++) {
hash_table[i] = NULL;
const Element *e = p_t.hash_table[i];
while (e) {
Element *le = memnew(Element); /* local element */
*le = *e; /* copy data */
/* add to list and reassign pointers */
le->next = hash_table[i];
hash_table[i] = le;
e = e->next;
}
}
}
public:
Element *set(const TKey &p_key, const TData &p_data) {
return set(Pair(p_key, p_data));
}
Element *set(const Pair &p_pair) {
Element *e = NULL;
if (!hash_table)
make_hash_table(); // if no table, make one
else
e = const_cast<Element *>(get_element(p_pair.key));
/* if we made it up to here, the pair doesn't exist, create and assign */
if (!e) {
e = create_element(p_pair.key);
if (!e)
return NULL;
check_hash_table(); // perform mantenience routine
}
e->pair.data = p_pair.data;
return e;
}
bool has(const TKey &p_key) const {
return getptr(p_key) != NULL;
}
/**
* Get a key from data, return a const reference.
* WARNING: this doesn't check errors, use either getptr and check NULL, or check
* first with has(key)
*/
const TData &get(const TKey &p_key) const {
const TData *res = getptr(p_key);
CRASH_COND_MSG(!res, "Map key not found.");
return *res;
}
TData &get(const TKey &p_key) {
TData *res = getptr(p_key);
CRASH_COND_MSG(!res, "Map key not found.");
return *res;
}
/**
* Same as get, except it can return NULL when item was not found.
* This is mainly used for speed purposes.
*/
_FORCE_INLINE_ TData *getptr(const TKey &p_key) {
if (unlikely(!hash_table))
return NULL;
Element *e = const_cast<Element *>(get_element(p_key));
if (e)
return &e->pair.data;
return NULL;
}
_FORCE_INLINE_ const TData *getptr(const TKey &p_key) const {
if (unlikely(!hash_table))
return NULL;
const Element *e = const_cast<Element *>(get_element(p_key));
if (e)
return &e->pair.data;
return NULL;
}
/**
* Same as get, except it can return NULL when item was not found.
* This version is custom, will take a hash and a custom key (that should support operator==()
*/
template <class C>
_FORCE_INLINE_ TData *custom_getptr(C p_custom_key, uint32_t p_custom_hash) {
if (unlikely(!hash_table))
return NULL;
uint32_t hash = p_custom_hash;
uint32_t index = hash & ((1 << hash_table_power) - 1);
Element *e = hash_table[index];
while (e) {
/* checking hash first avoids comparing key, which may take longer */
if (e->hash == hash && Comparator::compare(e->pair.key, p_custom_key)) {
/* the pair exists in this hashtable, so just update data */
return &e->pair.data;
}
e = e->next;
}
return NULL;
}
template <class C>
_FORCE_INLINE_ const TData *custom_getptr(C p_custom_key, uint32_t p_custom_hash) const {
if (unlikely(!hash_table))
return NULL;
uint32_t hash = p_custom_hash;
uint32_t index = hash & ((1 << hash_table_power) - 1);
const Element *e = hash_table[index];
while (e) {
/* checking hash first avoids comparing key, which may take longer */
if (e->hash == hash && Comparator::compare(e->pair.key, p_custom_key)) {
/* the pair exists in this hashtable, so just update data */
return &e->pair.data;
}
e = e->next;
}
return NULL;
}
/**
* Erase an item, return true if erasing was successful
*/
bool erase(const TKey &p_key) {
if (unlikely(!hash_table))
return false;
uint32_t hash = Hasher::hash(p_key);
uint32_t index = hash & ((1 << hash_table_power) - 1);
Element *e = hash_table[index];
Element *p = NULL;
while (e) {
/* checking hash first avoids comparing key, which may take longer */
if (e->hash == hash && Comparator::compare(e->pair.key, p_key)) {
if (p) {
p->next = e->next;
} else {
//begin of list
hash_table[index] = e->next;
}
memdelete(e);
elements--;
if (elements == 0)
erase_hash_table();
else
check_hash_table();
return true;
}
p = e;
e = e->next;
}
return false;
}
inline const TData &operator[](const TKey &p_key) const { //constref
return get(p_key);
}
inline TData &operator[](const TKey &p_key) { //assignment
Element *e = NULL;
if (!hash_table)
make_hash_table(); // if no table, make one
else
e = const_cast<Element *>(get_element(p_key));
/* if we made it up to here, the pair doesn't exist, create */
if (!e) {
e = create_element(p_key);
CRASH_COND(!e);
check_hash_table(); // perform mantenience routine
}
return e->pair.data;
}
/**
* Get the next key to p_key, and the first key if p_key is null.
* Returns a pointer to the next key if found, NULL otherwise.
* Adding/Removing elements while iterating will, of course, have unexpected results, don't do it.
*
* Example:
*
* const TKey *k=NULL;
*
* while( (k=table.next(k)) ) {
*
* print( *k );
* }
*
*/
const TKey *next(const TKey *p_key) const {
if (unlikely(!hash_table))
return NULL;
if (!p_key) { /* get the first key */
for (int i = 0; i < (1 << hash_table_power); i++) {
if (hash_table[i]) {
return &hash_table[i]->pair.key;
}
}
} else { /* get the next key */
const Element *e = get_element(*p_key);
ERR_FAIL_COND_V_MSG(!e, NULL, "Invalid key supplied.");
if (e->next) {
/* if there is a "next" in the list, return that */
return &e->next->pair.key;
} else {
/* go to next elements */
uint32_t index = e->hash & ((1 << hash_table_power) - 1);
index++;
for (int i = index; i < (1 << hash_table_power); i++) {
if (hash_table[i]) {
return &hash_table[i]->pair.key;
}
}
}
/* nothing found, was at end */
}
return NULL; /* nothing found */
}
inline unsigned int size() const {
return elements;
}
inline bool empty() const {
return elements == 0;
}
void clear() {
/* clean up */
if (hash_table) {
for (int i = 0; i < (1 << hash_table_power); i++) {
while (hash_table[i]) {
Element *e = hash_table[i];
hash_table[i] = e->next;
memdelete(e);
}
}
memdelete_arr(hash_table);
}
hash_table = 0;
hash_table_power = 0;
elements = 0;
}
void operator=(const HashMap &p_table) {
copy_from(p_table);
}
HashMap() {
hash_table = NULL;
elements = 0;
hash_table_power = 0;
}
void get_key_value_ptr_array(const Pair **p_pairs) const {
if (unlikely(!hash_table))
return;
for (int i = 0; i < (1 << hash_table_power); i++) {
Element *e = hash_table[i];
while (e) {
*p_pairs = &e->pair;
p_pairs++;
e = e->next;
}
}
}
void get_key_list(List<TKey> *p_keys) const {
if (unlikely(!hash_table))
return;
for (int i = 0; i < (1 << hash_table_power); i++) {
Element *e = hash_table[i];
while (e) {
p_keys->push_back(e->pair.key);
e = e->next;
}
}
}
HashMap(const HashMap &p_table) {
hash_table = NULL;
elements = 0;
hash_table_power = 0;
copy_from(p_table);
}
~HashMap() {
clear();
}
};
#endif
| 24.263682 | 223 | 0.609323 |
9e79df6eaf81f0cc40d9f2594692400a564c2933 | 218 | h | C | libxml2/include/win32/expatVer.h | orynider/php-5.6.3x4VC9 | 47f9765b797279061c364e004153a0919895b23e | [
"BSD-2-Clause"
] | 1 | 2021-02-24T13:01:00.000Z | 2021-02-24T13:01:00.000Z | libxml2/include/win32/expatVer.h | orynider/php-5.6.3x4VC9 | 47f9765b797279061c364e004153a0919895b23e | [
"BSD-2-Clause"
] | null | null | null | libxml2/include/win32/expatVer.h | orynider/php-5.6.3x4VC9 | 47f9765b797279061c364e004153a0919895b23e | [
"BSD-2-Clause"
] | null | null | null | #define expatVer "2.2.5"
/* From expat.iss */
#define PACKAGE_VERSION_STRING expatVer
#define PACKAGE_VERSION_MAJOR 2
#define PACKAGE_VERSION_MINOR 2
#define PACKAGE_VERSION_PATCH 5
#define PACKAGE_VERSION_SUBMINOR 0
| 27.25 | 39 | 0.825688 |
366f7c38fa631f95738840bf62d7c1729299c021 | 449 | h | C | Canape/Classes/Encryption/CPEncryption.h | bliex/canape | f54cb6f2d3b41c771569566599f7bed82daca83a | [
"MIT"
] | null | null | null | Canape/Classes/Encryption/CPEncryption.h | bliex/canape | f54cb6f2d3b41c771569566599f7bed82daca83a | [
"MIT"
] | null | null | null | Canape/Classes/Encryption/CPEncryption.h | bliex/canape | f54cb6f2d3b41c771569566599f7bed82daca83a | [
"MIT"
] | null | null | null | //
// CPEncryption.h
// Test
//
// Created by bliex on 2016. 4. 4..
// Copyright © 2016년 bliex. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonCryptor.h>
#define PLIST_PASSWORD @"password"
@interface CPEncryption : NSObject
+(NSData *)AES256EncryptWithKey:(NSString *)key data:(NSMutableDictionary *) dictionary;
+(NSMutableDictionary *)AES256DecryptWithKey:(NSString *)key data:(NSData *) data;
@end
| 22.45 | 88 | 0.730512 |
36d20e16b4f1bcea724cfcea13a6c3289800c976 | 3,189 | h | C | Assignment_8/srt/raymath.h | arjun372/CS_35L | 5d540408a4e9b784efe9e7fb2dd72cde94b05f3f | [
"MIT"
] | null | null | null | Assignment_8/srt/raymath.h | arjun372/CS_35L | 5d540408a4e9b784efe9e7fb2dd72cde94b05f3f | [
"MIT"
] | null | null | null | Assignment_8/srt/raymath.h | arjun372/CS_35L | 5d540408a4e9b784efe9e7fb2dd72cde94b05f3f | [
"MIT"
] | 3 | 2019-04-03T03:21:36.000Z | 2020-03-12T19:36:46.000Z | #ifndef SRT_RAYMATH_H
#define SRT_RAYMATH_H
//
// math.h
// srt
//
// Created by vector on 11/2/10.
// Copyright (c) 2010 Brian F. Allen. All rights reserved.
// 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 3 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/>.
#define min(a, b) (((a) < (b)) ? (a) : (b))
#define max(a, b) (((a) > (b)) ? (a) : (b))
extern const long double PI;
extern const double dEpsilon; /* for ray-intersect test */
extern const double dInfinity;
typedef double Vec3[3];
typedef struct sphere_struct sphere_t;
typedef struct
{
Vec3 org; /* origin */
Vec3 dir; /* direction */
} ray_t;
typedef struct
{
Vec3 pos;
Vec3 color;
} light_t;
typedef struct
{
light_t* lights;
int light_count;
sphere_t* spheres;
int sphere_count;
} scene_t;
void init_scene( scene_t* scene );
sphere_t* add_sphere( scene_t* scene,
double x, double y, double z,
double radius,
double r, double g, double b );
light_t* add_light( scene_t* scene,
double x, double y, double z,
double r, double g, double b );
typedef void (*shader_func_t)( Vec3 out_color,
scene_t* scene,
sphere_t* sphere,
ray_t* original_ray,
double hit_on_ray,
int recursion_depth );
struct sphere_struct
{
Vec3 org; /* center */
double rad; /* radius */
Vec3 color; /* surface color */
shader_func_t shader; /* surface shader */
};
/* holds the normal and distance away
* that an intersection was found.
*/
typedef struct
{
Vec3 n; /* normal */
double t; /* distance */
} hit_t;
void zero( Vec3 out );
void set( Vec3 out, double x, double y, double z );
void copy( Vec3 to, Vec3 from );
void add( Vec3 out, Vec3 a, Vec3 b );
void sub( Vec3 out, Vec3 a, Vec3 b );
void mul( Vec3 out, Vec3 a, double s );
double dot( Vec3 a, Vec3 b );
double len( Vec3 a );
void cross( Vec3 out, Vec3 a, Vec3 b );
void norm( Vec3 out, Vec3 a );
void reflect( Vec3 out, Vec3 incoming, Vec3 surf_norm );
void sphere_normal( Vec3 out, sphere_t* s, Vec3 dir );
double gamma( double raw );
/* returns the distance along ray of first interestion with sphere
* post: return is positive (since it's a ray and not a line)
*/
double sphere_intersect( sphere_t* sphere, ray_t* ray );
void sphere_copy( sphere_t* to, sphere_t* from );
/*
* Test functions
*/
int is_close( double a, double b );
#endif
| 25.717742 | 72 | 0.618689 |
2c680c327442b1ebc27e8c3a127fcc81caf270ea | 6,913 | c | C | lkm_queue.c | awidegreen/lkm_queue | 40872db64cddd9228109cd3bda591e97ee349acb | [
"MIT"
] | null | null | null | lkm_queue.c | awidegreen/lkm_queue | 40872db64cddd9228109cd3bda591e97ee349acb | [
"MIT"
] | null | null | null | lkm_queue.c | awidegreen/lkm_queue | 40872db64cddd9228109cd3bda591e97ee349acb | [
"MIT"
] | null | null | null | #include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/mutex.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include "signal.h"
#include "defs.h"
#define SIGNAL_QUEUE_SIZE 100
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Armin Widegreen <armin.widegreen@gmail.com>");
MODULE_DESCRIPTION("A LKM (misc) char-device queue");
//------------------------------------------------------------------------------
struct queue_node {
struct signal_t* data;
struct queue_node* next;
};
//------------------------------------------------------------------------------
struct signal_queue {
wait_queue_head_t read_queue;
struct mutex lock;
struct queue_node* front;
struct queue_node* rear;
unsigned long size;
unsigned long max_size;
};
//------------------------------------------------------------------------------
struct signal_queue* global_queue;
//------------------------------------------------------------------------------
void
q_dequeue(struct signal_queue* queue) {
struct queue_node* temp = queue->front;
if (queue->front == NULL)
{ // queue is empty
return;
}
if (queue->front == queue->rear)
{
queue->front = queue->rear = NULL;
}
else
{
queue->front = queue->front->next;
}
--queue->size;
/*printk(KERN_INFO "Signal denqueued, new size: %lu!\n", queue->size);*/
kfree(temp->data);
kfree(temp);
}
//------------------------------------------------------------------------------
struct signal_t*
q_front(struct signal_queue* queue)
{
if (queue->front == NULL)
{ // queue is empty
return NULL;
}
return queue->front->data;
}
//------------------------------------------------------------------------------
void
q_clear(struct signal_queue* queue)
{
while (q_front(queue))
q_dequeue(queue);
}
//------------------------------------------------------------------------------
void
q_enqueue(struct signal_queue* queue, struct signal_t* sig)
{
struct queue_node* temp = NULL;
if (queue->size >= queue->max_size)
return;
temp = kzalloc(sizeof(*queue->front), GFP_KERNEL);
if (unlikely(!temp))
goto out_free;
temp->data = sig;
temp->next = NULL;
++queue->size;
if (queue->front == NULL && queue->rear == NULL)
{ // empty queue
queue->front = queue->rear = temp;
goto out;
}
queue->rear->next = temp;
queue->rear = temp;
out:
/*printk(KERN_INFO "Signal enqueued, new size: %lu!\n", queue->size);*/
return;
out_free:
printk(KERN_INFO "Something went wrong when enqueueing!\n");
q_clear(queue);
kfree(queue);
}
//------------------------------------------------------------------------------
bool
q_empty(struct signal_queue* queue)
{
return (queue->front == NULL && queue->rear == NULL);
}
//------------------------------------------------------------------------------
static struct signal_queue* queue_alloc(unsigned long size)
{
struct signal_queue *queue = NULL;
queue = kzalloc(sizeof(*queue), GFP_KERNEL);
if (unlikely(!queue))
goto out;
queue->front = NULL;
queue->rear = NULL;
queue->size = 0;
queue->max_size = SIGNAL_QUEUE_SIZE;
init_waitqueue_head(&queue->read_queue);
mutex_init(&queue->lock);
out:
return queue;
}
//------------------------------------------------------------------------------
static void queue_free(struct signal_queue *queue)
{
q_clear(queue);
kfree(queue);
}
//------------------------------------------------------------------------------
static int queue_dev_open(struct inode *inode, struct file *file)
{
return 0;
}
//------------------------------------------------------------------------------
static ssize_t queue_dev_read(struct file *file, char __user * out,
size_t size, loff_t * off)
{
struct signal_queue *queue = global_queue;
struct signal_t* signal;
ssize_t result;
if (mutex_lock_interruptible(&queue->lock)) {
result = -ERESTARTSYS;
goto out;
}
while (q_empty(queue)) {
mutex_unlock(&queue->lock);
if (file->f_flags & O_NONBLOCK) {
result = -EAGAIN;
goto out;
}
// TODO
if (wait_event_interruptible(queue->read_queue, !q_empty(queue))) {
result = -ERESTARTSYS;
goto out;
}
if (mutex_lock_interruptible(&queue->lock)) {
result = -ERESTARTSYS;
goto out;
}
}
signal = q_front(queue);
size = sizeof(*signal);
if (copy_to_user(out, signal, size)) {
result = -EFAULT;
goto out_unlock;
}
q_dequeue(queue);
result = size;
out_unlock:
mutex_unlock(&queue->lock);
out:
return result;
}
//------------------------------------------------------------------------------
static ssize_t queue_dev_write(struct file *file, const char __user * in,
size_t size, loff_t * off)
{
struct signal_queue* queue = global_queue;
ssize_t result;
struct signal_t* signal = NULL;
if (mutex_lock_interruptible(&queue->lock)) {
result = -ERESTARTSYS;
goto out;
}
signal = kzalloc(sizeof(*signal), GFP_KERNEL);
if (unlikely(!signal)) {
result = -EFAULT;
goto out_unlock;
}
if (copy_from_user(signal, in, size)) {
result = -EFAULT;
goto out_unlock;
}
q_enqueue(queue, signal);
wake_up_interruptible(&queue->read_queue);
result = size;
out_unlock:
mutex_unlock(&queue->lock);
out:
return result;
}
//------------------------------------------------------------------------------
static int queue_dev_close(struct inode *inode, struct file *file)
{
return 0;
}
//------------------------------------------------------------------------------
static struct file_operations queue_dev_fops = {
.owner = THIS_MODULE,
.open = queue_dev_open,
.read = queue_dev_read,
.write = queue_dev_write,
.release = queue_dev_close,
.llseek = noop_llseek
};
//------------------------------------------------------------------------------
static struct miscdevice queue_dev_misc_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = DEVICE_NAME,
.fops = &queue_dev_fops
};
//------------------------------------------------------------------------------
static int __init queue_dev_init(void)
{
global_queue = queue_alloc(SIGNAL_QUEUE_SIZE);
if (unlikely(!global_queue)) {
return -ENOMEM;
}
misc_register(&queue_dev_misc_device);
printk(KERN_INFO "queue_dev device has been registered, with queue size %d\n",
SIGNAL_QUEUE_SIZE);
return 0;
}
//------------------------------------------------------------------------------
static void __exit queue_dev_exit(void)
{
queue_free(global_queue);
misc_deregister(&queue_dev_misc_device);
printk(KERN_INFO "queue_dev device has been unregistered\n");
}
//------------------------------------------------------------------------------
module_init(queue_dev_init);
module_exit(queue_dev_exit);
| 22.157051 | 80 | 0.5264 |
89fb505b205202ec168360fa547da3a88c62ae63 | 241 | h | C | xdefs/xdefs.h | xdlmost/xtool | 88a2ac7b73e108431dc01d6d88480b5c364121a5 | [
"MIT"
] | null | null | null | xdefs/xdefs.h | xdlmost/xtool | 88a2ac7b73e108431dc01d6d88480b5c364121a5 | [
"MIT"
] | null | null | null | xdefs/xdefs.h | xdlmost/xtool | 88a2ac7b73e108431dc01d6d88480b5c364121a5 | [
"MIT"
] | null | null | null | #ifndef X_DEFS_H
#define X_DEFS_H
#include "x_basic_macro_defs.h"
__X_BEGIN_DECLS
#include "x_basic_type_defs.h"
#include "x_module_defs.h"
#include "x_ret.h"
#ifndef NULL
#define NULL 0
#endif
__X_END_DECLS
#endif | 13.388889 | 35 | 0.713693 |
3251611d27887098283cc3bdbf3f8f6c4596f547 | 11,354 | c | C | gtk/buddylookup.c | Advance2000/linphone | 5b101ab79bbb83f52462cbdbaf8e451858ce911b | [
"BSD-2-Clause"
] | null | null | null | gtk/buddylookup.c | Advance2000/linphone | 5b101ab79bbb83f52462cbdbaf8e451858ce911b | [
"BSD-2-Clause"
] | null | null | null | gtk/buddylookup.c | Advance2000/linphone | 5b101ab79bbb83f52462cbdbaf8e451858ce911b | [
"BSD-2-Clause"
] | null | null | null | /*
linphone, gtk-glade interface.
Copyright (C) 2008 Simon MORLAT (simon.morlat@linphone.org)
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "linphone.h"
#include "sipsetup.h"
static void linphone_gtk_display_lookup_results(GtkWidget *w, const MSList *results);
enum {
LOOKUP_RESULT_NAME,
LOOKUP_RESULT_SIP_URI,
LOOKUP_RESULT_ADDRESS,
LOOKUP_RESULT_ICON,
LOOKUP_RESULT_NCOL
};
void linphone_gtk_buddy_lookup_window_destroyed(GtkWidget *w){
guint tid=GPOINTER_TO_INT(g_object_get_data(G_OBJECT(w),"typing_timeout"));
if (tid!=0){
g_source_remove(tid);
}
tid=GPOINTER_TO_INT(g_object_get_data(G_OBJECT(w),"buddylookup_processing"));
if (tid!=0){
g_source_remove(tid);
}
}
static void enable_add_buddy_button(GtkWidget *w){
gtk_widget_set_sensitive(linphone_gtk_get_widget(w,"add_buddy"),TRUE);
}
static void disable_add_buddy_button(GtkWidget *w){
gtk_widget_set_sensitive(linphone_gtk_get_widget(w,"add_buddy"),FALSE);
}
static void buddy_selection_changed(GtkWidget *w){
GtkWidget *results=linphone_gtk_get_widget(w,"search_results");
GtkTreeSelection *select;
GtkTreeIter iter;
GtkTreeModel *model;
enable_add_buddy_button(w);
select = gtk_tree_view_get_selection(GTK_TREE_VIEW(results));
if (gtk_tree_selection_get_selected (select, &model, &iter))
{
GtkTreePath *path=gtk_tree_model_get_path(model,&iter);
gtk_tree_view_collapse_all(GTK_TREE_VIEW(results));
gtk_tree_view_expand_row(GTK_TREE_VIEW(results),path,FALSE);
gtk_tree_path_free(path);
}
}
GtkWidget * linphone_gtk_show_buddy_lookup_window(SipSetupContext *ctx){
GtkTreeStore *store;
GtkCellRenderer *renderer,*pbuf_renderer;
GtkTreeViewColumn *column;
GtkTreeSelection *select;
GtkWidget *w=linphone_gtk_create_window("buddylookup", NULL);
GtkWidget *results=linphone_gtk_get_widget(w,"search_results");
GtkProgressBar *pb=GTK_PROGRESS_BAR(linphone_gtk_get_widget(w,"progressbar"));
store = gtk_tree_store_new(LOOKUP_RESULT_NCOL, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, GDK_TYPE_PIXBUF);
/*gtk_tree_view_set_hover_expand(GTK_TREE_VIEW(results),TRUE);*/
gtk_tree_view_set_model(GTK_TREE_VIEW(results),GTK_TREE_MODEL(store));
g_object_unref(G_OBJECT(store));
renderer = gtk_cell_renderer_text_new ();
column = gtk_tree_view_column_new_with_attributes (_("Firstname, Lastname"),
renderer,
"markup", LOOKUP_RESULT_NAME,
NULL);
g_object_set (G_OBJECT(column), "resizable", TRUE, NULL);
pbuf_renderer=gtk_cell_renderer_pixbuf_new();
g_object_set(G_OBJECT(renderer),"is-expander",TRUE,NULL);
gtk_tree_view_column_pack_start(column,pbuf_renderer,FALSE);
gtk_tree_view_column_add_attribute (column,pbuf_renderer,
"pixbuf",
LOOKUP_RESULT_ICON);
gtk_tree_view_append_column (GTK_TREE_VIEW (results), column);
/*
column = gtk_tree_view_column_new_with_attributes (_("SIP address"),
renderer,
"text", LOOKUP_RESULT_SIP_URI,
NULL);
g_object_set (G_OBJECT(column), "resizable", TRUE, NULL);
gtk_tree_view_append_column (GTK_TREE_VIEW (results), column);
*/
select = gtk_tree_view_get_selection (GTK_TREE_VIEW (results));
gtk_tree_selection_set_mode (select, GTK_SELECTION_SINGLE);
g_signal_connect_swapped(G_OBJECT(select),"changed",(GCallback)buddy_selection_changed,w);
/*
#if GTK_CHECK_VERSION(2,12,0)
gtk_tree_view_set_tooltip_column(GTK_TREE_VIEW(results),LOOKUP_RESULT_ADDRESS);
#endif
*/
g_object_set_data(G_OBJECT(w),"SipSetupContext",ctx);
g_object_weak_ref(G_OBJECT(w),(GWeakNotify)linphone_gtk_buddy_lookup_window_destroyed,w);
//g_signal_connect_swapped(G_OBJECT(w),"destroy",(GCallback)linphone_gtk_buddy_lookup_window_destroyed,w);
gtk_progress_bar_set_fraction(pb,0);
gtk_progress_bar_set_text(pb,NULL);
gtk_dialog_add_button(GTK_DIALOG(w),GTK_STOCK_CLOSE,GTK_RESPONSE_CLOSE);
g_object_set_data(G_OBJECT(w),"last_state",GINT_TO_POINTER(-1));
gtk_widget_show(w);
return w;
}
void linphone_gtk_buddy_lookup_set_keyword(GtkWidget *w, const char *kw){
gtk_entry_set_text(GTK_ENTRY(linphone_gtk_get_widget(w,"keyword")),kw);
}
static gboolean linphone_gtk_process_buddy_lookup(GtkWidget *w){
BuddyLookupStatus bls;
SipSetupContext *ctx;
int last_state;
gchar *tmp;
MSList *results=NULL;
GtkProgressBar *pb=GTK_PROGRESS_BAR(linphone_gtk_get_widget(w,"progressbar"));
BuddyLookupRequest *req=(BuddyLookupRequest*)g_object_get_data(G_OBJECT(w),"buddylookup_request");
ctx=(SipSetupContext*)g_object_get_data(G_OBJECT(w),"SipSetupContext");
last_state=GPOINTER_TO_INT(g_object_get_data(G_OBJECT(w),"last_state"));
if (req==NULL) {
g_object_set_data(G_OBJECT(w),"buddylookup_processing",GINT_TO_POINTER(0));
return FALSE;
}
bls=req->status;
if (last_state==bls) return TRUE;
switch(bls){
case BuddyLookupNone:
gtk_progress_bar_set_fraction(pb,0);
gtk_progress_bar_set_text(pb,NULL);
break;
case BuddyLookupFailure:
gtk_progress_bar_set_fraction(pb,0);
gtk_progress_bar_set_text(pb,_("Error communicating with server."));
break;
case BuddyLookupConnecting:
gtk_progress_bar_set_fraction(pb,0.2);
gtk_progress_bar_set_text(pb,_("Connecting..."));
break;
case BuddyLookupConnected:
gtk_progress_bar_set_fraction(pb,0.4);
gtk_progress_bar_set_text(pb,_("Connected"));
break;
case BuddyLookupReceivingResponse:
gtk_progress_bar_set_fraction(pb,0.8);
gtk_progress_bar_set_text(pb,_("Receiving data..."));
break;
case BuddyLookupDone:
results=req->results;
linphone_gtk_display_lookup_results(
linphone_gtk_get_widget(w,"search_results"),
results);
gtk_progress_bar_set_fraction(pb,1);
tmp=g_strdup_printf(ngettext("Found %i contact",
"Found %i contacts", ms_list_size(results)),
ms_list_size(results));
gtk_progress_bar_set_text(pb,tmp);
g_free(tmp);
sip_setup_context_buddy_lookup_free(ctx,req);
g_object_set_data(G_OBJECT(w),"buddylookup_request",NULL);
break;
}
g_object_set_data(G_OBJECT(w),"last_state",GINT_TO_POINTER(bls));
return TRUE;
}
static gboolean keyword_typing_finished(GtkWidget *w){
guint tid=GPOINTER_TO_INT(g_object_get_data(G_OBJECT(w),"typing_timeout"));
const char *keyword;
SipSetupContext *ctx;
if (tid!=0){
g_source_remove(tid);
}
keyword=gtk_entry_get_text(GTK_ENTRY(linphone_gtk_get_widget(w,"keyword")));
if (strlen(keyword)>=1){
BuddyLookupRequest *req;
guint tid2;
ctx=(SipSetupContext*)g_object_get_data(G_OBJECT(w),"SipSetupContext");
req=(BuddyLookupRequest*)g_object_get_data(G_OBJECT(w),"buddylookup_request");
if (req!=NULL){
sip_setup_context_buddy_lookup_free(ctx,req);
}
req=sip_setup_context_create_buddy_lookup_request(ctx);
buddy_lookup_request_set_key(req,keyword);
sip_setup_context_buddy_lookup_submit(ctx,req);
g_object_set_data(G_OBJECT(w),"buddylookup_request",req);
if (g_object_get_data(G_OBJECT(w),"buddylookup_processing")==NULL){
tid2=g_timeout_add(20,(GSourceFunc)linphone_gtk_process_buddy_lookup,w);
g_object_set_data(G_OBJECT(w),"buddylookup_processing",GINT_TO_POINTER(tid2));
}
}
return FALSE;
}
void linphone_gtk_keyword_changed(GtkEditable *e){
GtkWidget *w=gtk_widget_get_toplevel(GTK_WIDGET(e));
guint tid=GPOINTER_TO_INT(g_object_get_data(G_OBJECT(w),"typing_timeout"));
if (tid!=0){
g_source_remove(tid);
}
tid=g_timeout_add(2000,(GSourceFunc)keyword_typing_finished,w);
g_object_set_data(G_OBJECT(w),"typing_timeout",GINT_TO_POINTER(tid));
}
static void linphone_gtk_display_lookup_results(GtkWidget *w, const MSList *results){
GtkTreeStore *store;
GtkTreeIter iter;
gchar *tmp;
const MSList *elem;
store=GTK_TREE_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(w)));
gtk_tree_store_clear(store);
disable_add_buddy_button(gtk_widget_get_toplevel(w));
for(elem=results;elem!=NULL;elem=elem->next){
BuddyInfo *bi=(BuddyInfo*)elem->data;
GdkPixbuf *pbuf;
GtkTreeIter depth1;
gtk_tree_store_append(store,&iter,NULL);
tmp=g_strdup_printf("%s, %s (%s)",bi->firstname,bi->lastname,bi->displayname);
gtk_tree_store_set(store,&iter,LOOKUP_RESULT_NAME, tmp,-1);
g_free(tmp);
gtk_tree_store_set(store,&iter,LOOKUP_RESULT_SIP_URI, bi->sip_uri,-1);
tmp=g_strdup_printf("%s, %s %s\n%s",bi->address.street, bi->address.zip, bi->address.town, bi->address.country);
gtk_tree_store_set(store,&iter,LOOKUP_RESULT_ADDRESS, tmp,-1);
g_free(tmp);
if (bi->image_data!=NULL){
pbuf=_gdk_pixbuf_new_from_memory_at_scale(bi->image_data,bi->image_length,-1,40,TRUE);
if (pbuf) {
gtk_tree_store_set(store,&iter,LOOKUP_RESULT_ICON,pbuf,-1);
g_object_unref(G_OBJECT(pbuf));
}
}
gtk_tree_store_append(store,&depth1,&iter);
tmp=g_strdup_printf("<big>%s, %s (%s)</big>\n<i>%s</i>, <b>%s</b> %s\n%s\n%s",
bi->firstname,bi->lastname,bi->displayname,bi->address.street,
bi->address.zip, bi->address.town, bi->address.country,bi->sip_uri);
gtk_tree_store_set(store,&depth1,LOOKUP_RESULT_NAME,tmp,-1);
g_free(tmp);
if (bi->image_data!=NULL){
pbuf=_gdk_pixbuf_new_from_memory_at_scale(bi->image_data,bi->image_length,-1,-1,TRUE);
if (pbuf) {
gtk_tree_store_set(store,&depth1,LOOKUP_RESULT_ICON,pbuf,-1);
g_object_unref(G_OBJECT(pbuf));
}
}
}
}
void linphone_gtk_add_buddy_from_database(GtkWidget *button){
GtkWidget *w=gtk_widget_get_toplevel(button);
GtkTreeSelection *select;
GtkTreeIter iter;
GtkTreeModel *model;
select = gtk_tree_view_get_selection(GTK_TREE_VIEW(linphone_gtk_get_widget(w,"search_results")));
if (gtk_tree_selection_get_selected (select, &model, &iter))
{
char *uri;
char *name;
char *addr;
LinphoneFriend *lf;
int presence=linphone_gtk_get_ui_config_int("use_subscribe_notify",1);
gtk_tree_model_get (model, &iter,LOOKUP_RESULT_SIP_URI , &uri,LOOKUP_RESULT_NAME, &name, -1);
addr=g_strdup_printf("%s <%s>",name,uri);
lf=linphone_friend_new_with_address(addr);
linphone_friend_set_inc_subscribe_policy(lf,presence ? LinphoneSPAccept : LinphoneSPDeny);
linphone_friend_send_subscribe(lf,presence);
linphone_core_add_friend(linphone_gtk_get_core(),lf);
linphone_gtk_show_friends();
g_free(addr);
g_free(uri);
g_free(name);
}
}
/*called when double clicking on a contact */
void linphone_gtk_buddy_lookup_contact_activated(GtkWidget *treeview){
linphone_gtk_add_buddy_from_database(treeview);
gtk_widget_destroy(gtk_widget_get_toplevel(treeview));
}
| 37.104575 | 114 | 0.752951 |
d0cfe5d766deaff0efcd000e7ac05cdba6850128 | 7,017 | c | C | contrib/slapd-modules/nssov/shadow.c | matherm-aboehm/openldap | 2615a35b32b3596a1e8f872f0c244bc4a41a047e | [
"OLDAP-2.8"
] | 12 | 2015-03-24T10:41:33.000Z | 2021-03-19T10:46:29.000Z | contrib/slapd-modules/nssov/shadow.c | matherm-aboehm/openldap | 2615a35b32b3596a1e8f872f0c244bc4a41a047e | [
"OLDAP-2.8"
] | 8 | 2015-01-28T02:53:22.000Z | 2021-12-08T05:31:04.000Z | contrib/slapd-modules/nssov/shadow.c | matherm-aboehm/openldap | 2615a35b32b3596a1e8f872f0c244bc4a41a047e | [
"OLDAP-2.8"
] | 8 | 2015-04-14T13:03:24.000Z | 2019-09-19T03:22:11.000Z | /* shadow.c - shadow account lookup routines */
/* $OpenLDAP$ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
*
* Copyright 2008-2018 The OpenLDAP Foundation.
* Portions Copyright 2008 by Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
/* ACKNOWLEDGEMENTS:
* This code references portions of the nss-ldapd package
* written by Arthur de Jong. The nss-ldapd code was forked
* from the nss-ldap library written by Luke Howard.
*/
#include "nssov.h"
/* ( nisSchema.2.1 NAME 'shadowAccount' SUP top AUXILIARY
* DESC 'Additional attributes for shadow passwords'
* MUST uid
* MAY ( userPassword $ shadowLastChange $ shadowMin
* shadowMax $ shadowWarning $ shadowInactive $
* shadowExpire $ shadowFlag $ description ) )
*/
/* the basic search filter for searches */
static struct berval shadow_filter = BER_BVC("(objectClass=shadowAccount)");
/* the attributes to request with searches */
static struct berval shadow_keys[] = {
BER_BVC("uid"),
BER_BVC("userPassword"),
BER_BVC("shadowLastChange"),
BER_BVC("shadowMin"),
BER_BVC("shadowMax"),
BER_BVC("shadowWarning"),
BER_BVC("shadowInactive"),
BER_BVC("shadowExpire"),
BER_BVC("shadowFlag"),
BER_BVNULL
};
#define UID_KEY 0
#define PWD_KEY 1
#define CHG_KEY 2
#define MIN_KEY 3
#define MAX_KEY 4
#define WRN_KEY 5
#define INA_KEY 6
#define EXP_KEY 7
#define FLG_KEY 8
/* default values for attributes */
static struct berval default_shadow_userPassword = BER_BVC("*"); /* unmatchable */
static int default_nums[] = { 0,0,
-1, /* LastChange */
-1, /* Min */
-1, /* Max */
-1, /* Warning */
-1, /* Inactive */
-1, /* Expire */
0 /* Flag */
};
NSSOV_INIT(shadow)
static long to_date(struct berval *date,AttributeDescription *attr)
{
long value;
char *tmp;
/* do some special handling for date values on AD */
if (strcasecmp(attr->ad_cname.bv_val,"pwdLastSet")==0)
{
char buffer[8];
size_t l;
/* we expect an AD 64-bit datetime value;
we should do date=date/864000000000-134774
but that causes problems on 32-bit platforms,
first we devide by 1000000000 by stripping the
last 9 digits from the string and going from there */
l=date->bv_len-9;
if (l<1 || l>(sizeof(buffer)-1))
return 0; /* error */
strncpy(buffer,date->bv_val,l);
buffer[l]='\0';
value=strtol(buffer,&tmp,0);
if ((buffer[0]=='\0')||(*tmp!='\0'))
{
Debug(LDAP_DEBUG_ANY,"shadow entry contains non-numeric %s value\n",
attr->ad_cname.bv_val,0,0);
return 0;
}
return value/864-134774;
/* note that AD does not have expiry dates but a lastchangeddate
and some value that needs to be added */
}
value=strtol(date->bv_val,&tmp,0);
if ((date->bv_val[0]=='\0')||(*tmp!='\0'))
{
Debug(LDAP_DEBUG_ANY,"shadow entry contains non-numeric %s value\n",
attr->ad_cname.bv_val,0,0);
return 0;
}
return value;
}
#ifndef UF_DONT_EXPIRE_PASSWD
#define UF_DONT_EXPIRE_PASSWD 0x10000
#endif
#define GET_OPTIONAL_LONG(var,key) \
a = attr_find(entry->e_attrs, cbp->mi->mi_attrs[key].an_desc); \
if ( !a || BER_BVISNULL(&a->a_vals[0])) \
var = default_nums[key]; \
else \
{ \
if (a->a_numvals > 1) \
{ \
Debug(LDAP_DEBUG_ANY,"shadow entry %s contains multiple %s values\n", \
entry->e_name.bv_val, cbp->mi->mi_attrs[key].an_desc->ad_cname.bv_val,0); \
} \
var=strtol(a->a_vals[0].bv_val,&tmp,0); \
if ((a->a_vals[0].bv_val[0]=='\0')||(*tmp!='\0')) \
{ \
Debug(LDAP_DEBUG_ANY,"shadow entry %s contains non-numeric %s value\n", \
entry->e_name.bv_val, cbp->mi->mi_attrs[key].an_desc->ad_cname.bv_val,0); \
return 0; \
} \
}
#define GET_OPTIONAL_DATE(var,key) \
a = attr_find(entry->e_attrs, cbp->mi->mi_attrs[key].an_desc); \
if ( !a || BER_BVISNULL(&a->a_vals[0])) \
var = default_nums[key]; \
else \
{ \
if (a->a_numvals > 1) \
{ \
Debug(LDAP_DEBUG_ANY,"shadow entry %s contains multiple %s values\n", \
entry->e_name.bv_val, cbp->mi->mi_attrs[key].an_desc->ad_cname.bv_val,0); \
} \
var=to_date(&a->a_vals[0],cbp->mi->mi_attrs[key].an_desc); \
}
NSSOV_CBPRIV(shadow,
char buf[256];
struct berval name;);
static int write_shadow(nssov_shadow_cbp *cbp,Entry *entry)
{
struct berval tmparr[2];
struct berval *names;
Attribute *a;
char *tmp;
struct berval passwd = {0};
long lastchangedate;
long mindays;
long maxdays;
long warndays;
long inactdays;
long expiredate;
unsigned long flag;
int i;
int32_t tmpint32;
/* get username */
if (BER_BVISNULL(&cbp->name))
{
a = attr_find(entry->e_attrs, cbp->mi->mi_attrs[UID_KEY].an_desc);
if (!a)
{
Debug(LDAP_DEBUG_ANY,"shadow entry %s does not contain %s value\n",
entry->e_name.bv_val, cbp->mi->mi_attrs[UID_KEY].an_desc->ad_cname.bv_val,0);
return 0;
}
names = a->a_vals;
}
else
{
names=tmparr;
names[0]=cbp->name;
BER_BVZERO(&names[1]);
}
/* get password */
a = attr_find(entry->e_attrs, cbp->mi->mi_attrs[PWD_KEY].an_desc);
if ( a )
get_userpassword(&a->a_vals[0], &passwd);
if (BER_BVISNULL(&passwd))
passwd=default_shadow_userPassword;
/* get lastchange date */
GET_OPTIONAL_DATE(lastchangedate,CHG_KEY);
/* get mindays */
GET_OPTIONAL_LONG(mindays,MIN_KEY);
/* get maxdays */
GET_OPTIONAL_LONG(maxdays,MAX_KEY);
/* get warndays */
GET_OPTIONAL_LONG(warndays,WRN_KEY);
/* get inactdays */
GET_OPTIONAL_LONG(inactdays,INA_KEY);
/* get expire date */
GET_OPTIONAL_LONG(expiredate,EXP_KEY);
/* get flag */
GET_OPTIONAL_LONG(flag,FLG_KEY);
/* if we're using AD handle the flag specially */
if (strcasecmp(cbp->mi->mi_attrs[CHG_KEY].an_desc->ad_cname.bv_val,"pwdLastSet")==0)
{
if (flag&UF_DONT_EXPIRE_PASSWD)
maxdays=99999;
flag=0;
}
/* write the entries */
for (i=0;!BER_BVISNULL(&names[i]);i++)
{
WRITE_INT32(cbp->fp,NSLCD_RESULT_BEGIN);
WRITE_BERVAL(cbp->fp,&names[i]);
WRITE_BERVAL(cbp->fp,&passwd);
WRITE_INT32(cbp->fp,lastchangedate);
WRITE_INT32(cbp->fp,mindays);
WRITE_INT32(cbp->fp,maxdays);
WRITE_INT32(cbp->fp,warndays);
WRITE_INT32(cbp->fp,inactdays);
WRITE_INT32(cbp->fp,expiredate);
WRITE_INT32(cbp->fp,flag);
}
return 0;
}
NSSOV_CB(shadow)
NSSOV_HANDLE(
shadow,byname,
char fbuf[1024];
struct berval filter = {sizeof(fbuf)};
filter.bv_val = fbuf;
READ_STRING(fp,cbp.buf);,
cbp.name.bv_len = tmpint32;
cbp.name.bv_val = cbp.buf;
Debug(LDAP_DEBUG_ANY,"nssov_shadow_byname(%s)\n",cbp.name.bv_val,0,0);,
NSLCD_ACTION_SHADOW_BYNAME,
nssov_filter_byname(cbp.mi,UID_KEY,&cbp.name,&filter)
)
NSSOV_HANDLE(
shadow,all,
struct berval filter;
/* no parameters to read */
BER_BVZERO(&cbp.name);,
Debug(LDAP_DEBUG_ANY,"nssov_shadow_all()\n",0,0,0);,
NSLCD_ACTION_SHADOW_ALL,
(filter=cbp.mi->mi_filter,0)
)
| 27.197674 | 85 | 0.688898 |
d2ec08d26b953307294c866a3f204b00144619a9 | 13,537 | c | C | ca/teoc2007/teoc_demo_4.c | triangledirt/haze | d9f7dba1d8d38463631c8464f2324e2a192dcc9f | [
"BSD-2-Clause"
] | null | null | null | ca/teoc2007/teoc_demo_4.c | triangledirt/haze | d9f7dba1d8d38463631c8464f2324e2a192dcc9f | [
"BSD-2-Clause"
] | null | null | null | ca/teoc2007/teoc_demo_4.c | triangledirt/haze | d9f7dba1d8d38463631c8464f2324e2a192dcc9f | [
"BSD-2-Clause"
] | 1 | 2022-01-13T05:02:02.000Z | 2022-01-13T05:02:02.000Z | /* teoc.c - the evolution of culture - created 2007 by inhaesio zha */
/* gcc -ansi -O3 -lcurses -o teoc teoc.c */
#include <curses.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define GENE_INDEX_DISPLAY 0
#define GENE_INDEX_MEET 1
#define GENE_INDEX_MOVE 2
#define GENE_INDEX_PERSONALITY 3
#define MEET_STYLE_PUSH 0
#define MEET_STYLE_PULL 1
#define MEET_STYLE_EXCHANGE 2
#define CURSES_SOLID_COLORS 0
#define CURSES_VISUALIZATION 1
#define GENOME_LENGTH 128 /* 2^GENOME_ADDRESS_SIZE==GENOME_LENGTH */
#define GENOME_ADDRESS_SIZE 7
#define ITERATIONS 128 * 1000000
#define MEET_STYLE MEET_STYLE_PUSH
#define MUTATION 0
#define MUTATION_INCIDENCE_PER 100000
#define RANDOM_SEED 185379 + 0
#define SLEEP_US 100000
#define SWAP_POSITIONS_AFTER_MEET 1
#define WORLD_WIDTH 80
#define WORLD_HEIGHT 25
#define ORGANISM_COUNT (WORLD_WIDTH * WORLD_HEIGHT) / 1
struct display_gene_t {
unsigned int red;
unsigned int green;
unsigned int blue;
};
typedef struct display_gene_t display_gene_t;
struct meet_gene_t {
unsigned int address;
unsigned int length;
};
typedef struct meet_gene_t meet_gene_t;
struct move_gene_t {
int offset_x;
int offset_y;
};
typedef struct move_gene_t move_gene_t;
struct personality_gene_t {
unsigned int extrovert;
};
typedef struct personality_gene_t personality_gene_t;
struct position_t {
unsigned int x;
unsigned int y;
};
typedef struct position_t position_t;
struct organism_t {
unsigned int *genome;
position_t position;
char face;
};
typedef struct organism_t organism_t;
struct world_t {
organism_t *cells[WORLD_WIDTH][WORLD_HEIGHT];
};
typedef struct world_t world_t;
void create_organism(world_t *world, organism_t *organism);
void create_world(world_t *world);
void destroy_organism(world_t *world, organism_t *organism);
char display_color(organism_t *organism);
void find_empty_position(world_t *world, position_t *position);
unsigned int gene_at_virtual_index(organism_t *organism,
unsigned int virtual_index);
unsigned int gene_start_address(organism_t *organism, unsigned int gene_index);
void meet_organism(world_t *world, organism_t *organism_a,
organism_t *organism_b);
void move_organism(world_t *world, organism_t *organism);
void parse_display_gene(organism_t *organism, unsigned int gene_start_address,
display_gene_t *display_gene);
void parse_meet_gene(organism_t *organism, unsigned int gene_start_address,
meet_gene_t *meet_gene);
void parse_move_gene(organism_t *organism, unsigned int gene_start_address,
move_gene_t *move_gene);
void parse_move_gene_2(organism_t *organism, unsigned int gene_start_address,
move_gene_t *move_gene);
void parse_personality_gene(organism_t *organism,
unsigned int gene_start_address, personality_gene_t *personality_gene);
unsigned int random_unsigned_int(unsigned int range);
unsigned int unsigned_int_from_genome(organism_t *organism,
unsigned int gene_start_address, unsigned int gene_length);
unsigned int wrapped_index(int virtual_index, unsigned int range);
void create_organism(world_t *world, organism_t *organism)
{
position_t position;
unsigned int gene;
organism->genome = malloc(sizeof(unsigned int) * GENOME_LENGTH);
for (gene = 0; gene < GENOME_LENGTH; gene++) {
organism->genome[gene] = random_unsigned_int(2);
}
find_empty_position(world, &position);
world->cells[position.x][position.y] = organism;
organism->position = position;
organism->face = (rand() % 6) + 42;
}
void create_world(world_t *world)
{
unsigned int x;
unsigned int y;
for (x = 0; x < WORLD_WIDTH; x++) {
for (y = 0; y < WORLD_HEIGHT; y++) {
world->cells[x][y] = NULL;
}
}
}
void destroy_organism(world_t *world, organism_t *organism)
{
world->cells[organism->position.x][organism->position.y] = NULL;
free(organism->genome);
}
char display_color(organism_t *organism)
{
unsigned int display_gene_start_address;
display_gene_t display_gene;
char c;
display_gene_start_address = gene_start_address(organism,
GENE_INDEX_DISPLAY);
parse_display_gene(organism, display_gene_start_address, &display_gene);
if ((display_gene.red > display_gene.blue)
&& (display_gene.red > display_gene.green)) {
c = 'r';
}
else if ((display_gene.green > display_gene.red)
&& (display_gene.green > display_gene.blue)) {
c = 'g';
}
else if ((display_gene.blue > display_gene.green)
&& (display_gene.blue > display_gene.red)) {
c = 'b';
}
else {
c = 'w';
}
return c;
}
void find_empty_position(world_t *world, position_t *position)
{
unsigned int x;
unsigned int y;
do {
x = random_unsigned_int(WORLD_WIDTH);
y = random_unsigned_int(WORLD_HEIGHT);
} while (NULL != world->cells[x][y]);
position->x = x;
position->y = y;
}
unsigned int gene_at_virtual_index(organism_t *organism,
unsigned int virtual_index)
{
unsigned int actual_index;
actual_index = wrapped_index(virtual_index, GENOME_LENGTH);
return organism->genome[actual_index];
}
unsigned int gene_start_address(organism_t *organism, unsigned int gene_index)
{
unsigned int address_of_gene_header;
unsigned int start_address = 0;
unsigned int each_part_of_address;
unsigned int each_part_of_address_value = 1;
address_of_gene_header = GENOME_ADDRESS_SIZE * gene_index;
start_address = unsigned_int_from_genome(organism, address_of_gene_header,
GENOME_ADDRESS_SIZE);
return start_address;
}
void meet_organism(world_t *world, organism_t *organism_a,
organism_t *organism_b)
{
meet_gene_t meet_gene;
unsigned int meet_gene_start_address;
unsigned int each_gene;
unsigned int each_gene_virtual;
unsigned int temp_gene;
position_t temp_position;
meet_gene_start_address = gene_start_address(organism_a, GENE_INDEX_MEET);
parse_meet_gene(organism_a, meet_gene_start_address, &meet_gene);
for (each_gene = 0; each_gene < meet_gene.length; each_gene++) {
each_gene_virtual = wrapped_index(each_gene, GENOME_LENGTH);
#if MEET_STYLE==MEET_STYLE_PUSH
organism_b->genome[each_gene_virtual]
= organism_a->genome[each_gene_virtual];
if (MUTATION) {
if (0 == random_unsigned_int(MUTATION_INCIDENCE_PER)) {
organism_b->genome[each_gene_virtual] = random_unsigned_int(2);
}
}
#endif
#if MEET_STYLE==MEET_STYLE_PULL
organism_a->genome[each_gene_virtual]
= organism_b->genome[each_gene_virtual];
if (MUTATION) {
if (0 == random_unsigned_int(MUTATION_INCIDENCE_PER)) {
organism_a->genome[each_gene_virtual] = random_unsigned_int(2);
}
}
#endif
#if MEET_STYLE==MEET_STYLE_EXCHANGE
temp_gene = organism_a->genome[each_gene_virtual];
organism_a->genome[each_gene_virtual]
= organism_b->genome[each_gene_virtual];
organism_b->genome[each_gene_virtual] = temp_gene;
if (MUTATION) {
if (0 == random_unsigned_int(MUTATION_INCIDENCE_PER)) {
organism_a->genome[each_gene_virtual] = random_unsigned_int(2);
organism_b->genome[each_gene_virtual] = random_unsigned_int(2);
}
}
#endif
}
#if SWAP_POSITIONS_AFTER_MEET
world->cells[organism_b->position.x][organism_b->position.y] = organism_a;
world->cells[organism_a->position.x][organism_a->position.y] = organism_b;
temp_position.x = organism_a->position.x;
temp_position.y = organism_a->position.y;
organism_a->position.x = organism_b->position.x;
organism_a->position.y = organism_b->position.y;
organism_b->position.x = temp_position.x;
organism_b->position.y = temp_position.y;
#endif
}
void move_organism(world_t *world, organism_t *organism)
{
move_gene_t move_gene;
personality_gene_t personality_gene;
unsigned int move_gene_start_address;
unsigned int personality_gene_start_address;
unsigned int current_x;
unsigned int current_y;
unsigned int target_x;
unsigned int target_y;
move_gene_start_address = gene_start_address(organism, GENE_INDEX_MOVE);
parse_move_gene(organism, move_gene_start_address, &move_gene);
personality_gene_start_address = gene_start_address(organism,
GENE_INDEX_PERSONALITY);
parse_personality_gene(organism, personality_gene_start_address,
&personality_gene);
current_x = organism->position.x;
current_y = organism->position.y;
target_x = wrapped_index(current_x + move_gene.offset_x, WORLD_WIDTH);
target_y = wrapped_index(current_y + move_gene.offset_y, WORLD_HEIGHT);
if (NULL == world->cells[target_x][target_y]) {
world->cells[target_x][target_y] = organism;
world->cells[current_x][current_y] = NULL;
organism->position.x = target_x;
organism->position.y = target_y;
} else {
if (personality_gene.extrovert) {
meet_organism(world, organism, world->cells[target_x][target_y]);
}
else {
target_x = wrapped_index(current_x + (-1 * move_gene.offset_x),
WORLD_WIDTH);
target_y = wrapped_index(current_y + (-1 * move_gene.offset_y),
WORLD_HEIGHT);
if (NULL == world->cells[target_x][target_y]) {
world->cells[target_x][target_y] = organism;
world->cells[current_x][current_y] = NULL;
organism->position.x = target_x;
organism->position.y = target_y;
}
}
}
}
void parse_display_gene(organism_t *organism, unsigned int gene_start_address,
display_gene_t *display_gene)
{
display_gene->red = unsigned_int_from_genome
(organism, gene_start_address + 0, 8);
display_gene->green = unsigned_int_from_genome
(organism, gene_start_address + 8, 8);
display_gene->blue = unsigned_int_from_genome
(organism, gene_start_address + 16, 8);
}
void parse_meet_gene(organism_t *organism, unsigned int gene_start_address,
meet_gene_t *meet_gene)
{
meet_gene->address = unsigned_int_from_genome
(organism, gene_start_address + 0, 8);
meet_gene->length = unsigned_int_from_genome
(organism, gene_start_address + 8, 8);
}
void parse_move_gene(organism_t *organism, unsigned int gene_start_address,
move_gene_t *move_gene)
{
int offset_x;
int offset_y;
unsigned int is_negative_x;
unsigned int is_negative_y;
offset_x = unsigned_int_from_genome(organism, gene_start_address + 0, 1);
is_negative_x = unsigned_int_from_genome
(organism, gene_start_address + 1, 1);
offset_y = unsigned_int_from_genome(organism, gene_start_address + 2, 1);
is_negative_y = unsigned_int_from_genome
(organism, gene_start_address + 3, 1);
if (is_negative_x) {
offset_x *= -1;
}
if (is_negative_y) {
offset_y *= -1;
}
move_gene->offset_x = offset_x;
move_gene->offset_y = offset_y;
}
void parse_personality_gene(organism_t *organism,
unsigned int gene_start_address, personality_gene_t *personality_gene)
{
personality_gene->extrovert = unsigned_int_from_genome
(organism, gene_start_address + 0, 1);
}
unsigned int random_unsigned_int(unsigned int range)
{
return random() % range;
}
unsigned int unsigned_int_from_genome(organism_t *organism,
unsigned int gene_start_address, unsigned int gene_length)
{
unsigned int each_part_of_address;
unsigned int each_part_of_address_value = 1;
unsigned int r = 0;
unsigned int gene_end_address;
gene_end_address = gene_start_address + gene_length;
for (each_part_of_address = gene_start_address;
each_part_of_address < gene_end_address;
each_part_of_address++) {
r += each_part_of_address_value
* gene_at_virtual_index(organism, each_part_of_address);
each_part_of_address_value *= 2;
}
return r;
}
unsigned int wrapped_index(int virtual_index, unsigned int range)
{
unsigned int wrapped_index;
if (virtual_index >= (int) range) {
wrapped_index = virtual_index - range;
}
else if (virtual_index < 0) {
wrapped_index = range + virtual_index;
} else {
wrapped_index = virtual_index;
}
return wrapped_index;
}
int main(int argc, char *argv[])
{
world_t world;
unsigned int each_iteration;
unsigned int each_organism;
unsigned int x;
unsigned int y;
char c;
char color;
organism_t organisms[ORGANISM_COUNT];
srandom(RANDOM_SEED);
#if CURSES_VISUALIZATION
initscr();
start_color();
#if CURSES_SOLID_COLORS
init_pair(1, COLOR_BLACK, COLOR_RED);
init_pair(2, COLOR_BLACK, COLOR_GREEN);
init_pair(3, COLOR_BLACK, COLOR_BLUE);
init_pair(4, COLOR_BLACK, COLOR_WHITE);
init_pair(5, COLOR_BLACK, COLOR_BLACK);
#else
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(3, COLOR_BLUE, COLOR_BLACK);
init_pair(4, COLOR_WHITE, COLOR_BLACK);
init_pair(5, COLOR_BLACK, COLOR_BLACK);
#endif
#endif
create_world(&world);
for (each_organism = 0; each_organism < ORGANISM_COUNT; each_organism++) {
create_organism(&world, &organisms[each_organism]);
}
for (each_iteration = 0; each_iteration < ITERATIONS; each_iteration++) {
for (each_organism = 0; each_organism < ORGANISM_COUNT;
each_organism++) {
move_organism(&world, &organisms[each_organism]);
}
#if CURSES_VISUALIZATION
for (x = 0; x < WORLD_WIDTH; x++) {
for (y = 0; y < WORLD_HEIGHT; y++) {
if (NULL == world.cells[x][y]) {
color = 'x';
c = ' ';
}
else {
color = display_color(world.cells[x][y]);
c = world.cells[x][y]->face;
}
switch (color) {
case 'r':
mvaddch(y, x, c | COLOR_PAIR(1));
break;
case 'g':
mvaddch(y, x, c | COLOR_PAIR(2));
break;
case 'b':
mvaddch(y, x, c | COLOR_PAIR(3));
break;
case 'w':
mvaddch(y, x, c | COLOR_PAIR(4));
break;
default:
mvaddch(y, x, c | COLOR_PAIR(5));
break;
}
}
}
refresh();
usleep(SLEEP_US);
#endif
}
for (each_organism = 0; each_organism < ORGANISM_COUNT; each_organism++) {
destroy_organism(&world, &organisms[each_organism]);
}
#if CURSES_VISUALIZATION
endwin();
#endif
return 0;
}
| 27.796715 | 79 | 0.750831 |
c595baea783ead6cb049fb60746260f1f447f6a6 | 405 | h | C | src/module.h | hiventive/hvmodule | 023e699ccc2bcced16ec66ac82868aff1a301c58 | [
"MIT"
] | 1 | 2020-08-25T12:49:15.000Z | 2020-08-25T12:49:15.000Z | src/module.h | hiventive/hvmodule | 023e699ccc2bcced16ec66ac82868aff1a301c58 | [
"MIT"
] | null | null | null | src/module.h | hiventive/hvmodule | 023e699ccc2bcced16ec66ac82868aff1a301c58 | [
"MIT"
] | null | null | null | /**
* @file module.h
* @author Benjamin Barrois <benjamin.barrois@hiventive.com>
* @date May, 2018
* @copyright Copyright (C) 2018, Hiventive.
*
* @brief Hiventive Module
*
* Usage: #include <hv/module.h>
*/
#ifndef HV_MODULE_INC_H_
#define HV_MODULE_INC_H_
#include "hv/module/module/name.h"
#include "hv/module/base-module/base-module.h"
#include "hv/module/module/module.h"
#endif
| 20.25 | 60 | 0.696296 |
c5cac5e581fb2fe7c1553b9dfde5b5147f283026 | 31,936 | h | C | src/filemgr.h | greensky00/forestdb-1 | 00d6995399b8a980e777597bdca3b6b879b0651a | [
"Apache-2.0"
] | 1 | 2021-03-01T07:27:58.000Z | 2021-03-01T07:27:58.000Z | src/filemgr.h | greensky00/forestdb-1 | 00d6995399b8a980e777597bdca3b6b879b0651a | [
"Apache-2.0"
] | null | null | null | src/filemgr.h | greensky00/forestdb-1 | 00d6995399b8a980e777597bdca3b6b879b0651a | [
"Apache-2.0"
] | 1 | 2021-11-19T14:34:06.000Z | 2021-11-19T14:34:06.000Z | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2010 Couchbase, Inc
*
* 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 _JSAHN_FILEMGR_H
#define _JSAHN_FILEMGR_H
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <errno.h>
#ifdef _ASYNC_IO
#if !defined(WIN32) && !defined(_WIN32)
#include <libaio.h>
#include <sys/time.h>
#endif
#endif
#include "libforestdb/fdb_errors.h"
#include "atomic.h"
#include "internal_types.h"
#include "common.h"
#include "hash.h"
#include "partiallock.h"
#include "atomic.h"
#include "checksum.h"
#include "filemgr_ops.h"
#include "encryption.h"
#include "superblock.h"
#ifdef __cplusplus
extern "C" {
#endif
#define FILEMGR_SYNC 0x01
#define FILEMGR_READONLY 0x02
#define FILEMGR_ROLLBACK_IN_PROG 0x04
#define FILEMGR_CREATE 0x08
#define FILEMGR_REMOVAL_IN_PROG 0x10
#define FILEMGR_CREATE_CRC32 0x20 // Used in testing upgrade path
#define FILEMGR_CANCEL_COMPACTION 0x40 // Cancel the compaction
#define FILEMGR_SUCCESSFULLY_COMPACTED 0x80 // Compaction is done
struct filemgr_config {
filemgr_config& operator=(const filemgr_config& config) {
blocksize = config.blocksize;
ncacheblock = config.ncacheblock;
flag = config.flag;
seqtree_opt = config.seqtree_opt;
chunksize = config.chunksize;
options = config.options;
prefetch_duration = config.prefetch_duration;
num_wal_shards = config.num_wal_shards;
num_bcache_shards = config.num_bcache_shards;
encryption_key = config.encryption_key;
atomic_store_uint64_t(&block_reusing_threshold,
atomic_get_uint64_t(&config.block_reusing_threshold,
std::memory_order_relaxed),
std::memory_order_relaxed);
atomic_store_uint64_t(&num_keeping_headers,
atomic_get_uint64_t(&config.num_keeping_headers,
std::memory_order_relaxed),
std::memory_order_relaxed);
do_not_cache_doc_blocks = config.do_not_cache_doc_blocks;
return *this;
}
// TODO: Move these variables to private members as we refactor the code in C++.
int blocksize;
int ncacheblock;
int flag;
int chunksize;
uint8_t options;
uint8_t seqtree_opt;
uint64_t prefetch_duration;
uint16_t num_wal_shards;
uint16_t num_bcache_shards;
fdb_encryption_key encryption_key;
// Stale block reusing threshold
atomic_uint64_t block_reusing_threshold;
// Number of the last commit headders whose stale blocks should
// be kept for snapshot readers.
atomic_uint64_t num_keeping_headers;
bool do_not_cache_doc_blocks;
};
#ifndef _LATENCY_STATS
#define LATENCY_STAT_START()
#define LATENCY_STAT_END(file, type)
#else
#define LATENCY_STAT_START() \
uint64_t begin=get_monotonic_ts();
#define LATENCY_STAT_END(file, type)\
do {\
uint64_t end = get_monotonic_ts();\
filemgr_update_latency_stat(file, type, ts_diff(begin, end));} while(0)
struct latency_stat {
atomic_uint32_t lat_min;
atomic_uint32_t lat_max;
atomic_uint64_t lat_sum;
atomic_uint64_t lat_num;
};
#endif // _LATENCY_STATS
struct async_io_handle {
#ifdef _ASYNC_IO
#if !defined(WIN32) && !defined(_WIN32)
struct iocb **ioq;
struct io_event *events;
io_context_t ioctx;
#endif
#endif
uint8_t *aio_buf;
uint64_t *offset_array;
size_t queue_depth;
size_t block_size;
int fd;
};
typedef int filemgr_fs_type_t;
enum {
FILEMGR_FS_NO_COW = 0x01,
FILEMGR_FS_EXT4_WITH_COW = 0x02,
FILEMGR_FS_BTRFS = 0x03
};
struct filemgr_buffer{
void *block;
bid_t lastbid;
};
typedef uint16_t filemgr_header_len_t;
typedef uint64_t filemgr_magic_t;
typedef uint64_t filemgr_header_revnum_t;
struct filemgr_header{
filemgr_header_len_t size;
filemgr_header_revnum_t revnum;
atomic_uint64_t seqnum;
atomic_uint64_t bid;
struct kvs_ops_stat op_stat; // op stats for default KVS
struct kvs_stat stat; // stats for the default KVS
void *data;
};
typedef uint8_t filemgr_prefetch_status_t;
enum {
FILEMGR_PREFETCH_IDLE = 0,
FILEMGR_PREFETCH_RUNNING = 1,
FILEMGR_PREFETCH_ABORT = 2
};
#define DLOCK_MAX (41) /* a prime number */
struct wal;
struct fnamedic_item;
struct kvs_header;
typedef struct {
mutex_t mutex;
bool locked;
} mutex_lock_t;
struct filemgr {
char *filename; // Current file name.
atomic_uint32_t ref_count;
uint8_t fflags;
uint16_t filename_len;
uint32_t blocksize;
int fd;
atomic_uint64_t pos;
atomic_uint64_t last_commit;
atomic_uint64_t last_writable_bmp_revnum;
atomic_uint64_t num_invalidated_blocks;
atomic_uint8_t io_in_prog;
struct wal *wal;
struct filemgr_header header;
struct filemgr_ops *ops;
struct hash_elem e;
atomic_uint8_t status;
struct filemgr_config *config;
char *old_filename; // Old file name before compaction
char *new_filename; // New file name after compaction
std::atomic<struct fnamedic_item *> bcache;
fdb_txn global_txn;
bool in_place_compaction;
filemgr_fs_type_t fs_type;
struct kvs_header *kv_header;
void (*free_kv_header)(struct filemgr *file); // callback function
atomic_uint32_t throttling_delay;
// variables related to prefetching
atomic_uint8_t prefetch_status;
thread_t prefetch_tid;
// File format version
filemgr_magic_t version;
// superblock
struct superblock *sb;
#ifdef _LATENCY_STATS
struct latency_stat lat_stats[FDB_LATENCY_NUM_STATS];
#endif //_LATENCY_STATS
// spin lock for small region
spin_t lock;
// lock for data consistency
#ifdef __FILEMGR_DATA_PARTIAL_LOCK
struct plock plock;
#elif defined(__FILEMGR_DATA_MUTEX_LOCK)
mutex_t data_mutex[DLOCK_MAX];
#else
spin_t data_spinlock[DLOCK_MAX];
#endif //__FILEMGR_DATA_PARTIAL_LOCK
// mutex for synchronization among multiple writers.
mutex_lock_t writer_lock;
// CRC the file is using.
crc_mode_e crc_mode;
encryptor encryption;
// temporary in-memory list of stale blocks
struct list *stale_list;
// in-memory clone of system docs for reusable block info
// (they are pointed to by stale-block-tree)
struct avl_tree stale_info_tree;
// temporary tree for merging stale regions
struct avl_tree mergetree;
std::atomic<bool> stale_info_tree_loaded;
// in-memory index for a set of dirty index block updates
struct avl_tree dirty_update_idx;
// counter for the set of dirty index updates
atomic_uint64_t dirty_update_counter;
// latest dirty (immutable but not committed yet) update
struct filemgr_dirty_update_node *latest_dirty_update;
// spin lock for dirty_update_idx
spin_t dirty_update_lock;
/**
* Index for fdb_file_handle belonging to the same filemgr handle.
*/
struct avl_tree fhandle_idx;
/**
* Spin lock for file handle index.
*/
spin_t fhandle_idx_lock;
};
struct filemgr_dirty_update_node {
union {
// AVL-tree element
struct avl_node avl;
// list element
struct list_elem le;
};
// ID from the counter number
uint64_t id;
// flag indicating if this set of dirty blocks can be accessible.
bool immutable;
// flag indicating if this set of dirty blocks are already copied to newer node.
bool expired;
// number of threads (snapshots) accessing this dirty block set.
atomic_uint32_t ref_count;
// dirty root node BID for ID tree
bid_t idtree_root;
// dirty root node BID for sequence tree
bid_t seqtree_root;
// index for dirty blocks
struct avl_tree dirty_blocks;
// if true, do not keep dirty blocks in-memory.
bool bulk_load_mode;
};
struct filemgr_dirty_update_block {
// AVL-tree element
struct avl_node avl;
// contents of the block
void *addr;
// Block ID
bid_t bid;
// flag indicating if this block is immutable
bool immutable;
};
typedef fdb_status (*register_file_removal_func)(struct filemgr *file,
err_log_callback *log_callback);
typedef bool (*check_file_removal_func)(const char *filename);
typedef struct {
struct filemgr *file;
int rv;
} filemgr_open_result;
void filemgr_init(struct filemgr_config *config);
void filemgr_set_lazy_file_deletion(bool enable,
register_file_removal_func regis_func,
check_file_removal_func check_func);
/**
* Assign superblock operations.
*
* @param ops Set of superblock operations to be assigned.
* @return void.
*/
void filemgr_set_sb_operation(struct sb_ops ops);
uint64_t filemgr_get_bcache_used_space(void);
bool filemgr_set_kv_header(struct filemgr *file, struct kvs_header *kv_header,
void (*free_kv_header)(struct filemgr *file));
struct kvs_header* filemgr_get_kv_header(struct filemgr *file);
size_t filemgr_get_ref_count(struct filemgr *file);
INLINE void filemgr_incr_ref_count(struct filemgr *file) {
atomic_incr_uint32_t(&file->ref_count);
}
/**
* Get filemgr instance corresponding to the given file name.
*
* @param filename File name to find.
* @return filemgr instance. NULL if not found.
*/
struct filemgr* filemgr_get_instance(const char* filename);
filemgr_open_result filemgr_open(char *filename,
struct filemgr_ops *ops,
struct filemgr_config *config,
err_log_callback *log_callback);
uint64_t filemgr_update_header(struct filemgr *file,
void *buf,
size_t len,
bool inc_revnum);
filemgr_header_revnum_t filemgr_get_header_revnum(struct filemgr *file);
fdb_seqnum_t filemgr_get_seqnum(struct filemgr *file);
void filemgr_set_seqnum(struct filemgr *file, fdb_seqnum_t seqnum);
INLINE bid_t filemgr_get_header_bid(struct filemgr *file)
{
return ((file->header.size > 0) ?
atomic_get_uint64_t(&file->header.bid) : BLK_NOT_FOUND);
}
bid_t _filemgr_get_header_bid(struct filemgr *file);
void* filemgr_get_header(struct filemgr *file, void *buf, size_t *len,
bid_t *header_bid, fdb_seqnum_t *seqnum,
filemgr_header_revnum_t *header_revnum);
/**
* Get the current bitmap revision number of superblock.
*
* @param file Pointer to filemgr handle.
* @return Current bitmap revision number.
*/
uint64_t filemgr_get_sb_bmp_revnum(struct filemgr *file);
fdb_status filemgr_fetch_header(struct filemgr *file, uint64_t bid,
void *buf, size_t *len, fdb_seqnum_t *seqnum,
filemgr_header_revnum_t *header_revnum,
uint64_t *deltasize, uint64_t *version,
uint64_t *sb_bmp_revnum,
err_log_callback *log_callback);
uint64_t filemgr_fetch_prev_header(struct filemgr *file, uint64_t bid,
void *buf, size_t *len, fdb_seqnum_t *seqnum,
filemgr_header_revnum_t *revnum,
uint64_t *deltasize, uint64_t *version,
uint64_t *sb_bmp_revnum,
err_log_callback *log_callback);
fdb_status filemgr_close(struct filemgr *file,
bool cleanup_cache_onclose,
const char *orig_file_name,
err_log_callback *log_callback);
void filemgr_remove_all_buffer_blocks(struct filemgr *file);
void filemgr_free_func(struct hash_elem *h);
INLINE bid_t filemgr_get_next_alloc_block(struct filemgr *file)
{
return atomic_get_uint64_t(&file->pos) / file->blocksize;
}
bid_t filemgr_alloc(struct filemgr *file, err_log_callback *log_callback);
void filemgr_alloc_multiple(struct filemgr *file, int nblock, bid_t *begin,
bid_t *end, err_log_callback *log_callback);
bid_t filemgr_alloc_multiple_cond(struct filemgr *file, bid_t nextbid, int nblock,
bid_t *begin, bid_t *end,
err_log_callback *log_callback);
// Returns true if the block invalidated is from recent uncommited blocks
bool filemgr_invalidate_block(struct filemgr *file, bid_t bid);
bool filemgr_is_fully_resident(struct filemgr *file);
// returns number of immutable blocks that remain in file
uint64_t filemgr_flush_immutable(struct filemgr *file,
err_log_callback *log_callback);
fdb_status filemgr_read(struct filemgr *file,
bid_t bid, void *buf,
err_log_callback *log_callback,
bool read_on_cache_miss);
fdb_status filemgr_write_offset(struct filemgr *file, bid_t bid, uint64_t offset,
uint64_t len, void *buf, bool final_write,
err_log_callback *log_callback);
fdb_status filemgr_write(struct filemgr *file, bid_t bid, void *buf,
err_log_callback *log_callback);
ssize_t filemgr_write_blocks(struct filemgr *file, void *buf, unsigned num_blocks, bid_t start_bid);
int filemgr_is_writable(struct filemgr *file, bid_t bid);
void filemgr_remove_file(struct filemgr *file);
INLINE void filemgr_set_io_inprog(struct filemgr *file)
{
atomic_incr_uint8_t(&file->io_in_prog);
}
INLINE void filemgr_clear_io_inprog(struct filemgr *file)
{
atomic_decr_uint8_t(&file->io_in_prog);
}
fdb_status filemgr_commit(struct filemgr *file, bool sync,
err_log_callback *log_callback);
/**
* Commit DB file, and write a DB header at the given BID.
*
* @param file Pointer to filemgr handle.
* @param bid ID of the block that DB header will be written. If this value is set to
* BLK_NOT_FOUND, then DB header is appended at the end of the file.
* @param bmp_revnum Revision number of superblock's bitmap when this commit is called.
* @param sync Flag for calling fsync().
* @param log_callback Pointer to log callback function.
* @return FDB_RESULT_SUCCESS on success.
*/
fdb_status filemgr_commit_bid(struct filemgr *file, bid_t bid,
uint64_t bmp_revnum, bool sync,
err_log_callback *log_callback);
fdb_status filemgr_sync(struct filemgr *file, bool sync_option,
err_log_callback *log_callback);
fdb_status filemgr_shutdown();
void filemgr_update_file_status(struct filemgr *file, file_status_t status);
/**
* Updates the old_filename and new_filename of the current instance,
* with the arguments (non-null) provided.
*
* Returns false if oldFileName has already been set.
*/
bool filemgr_update_file_linkage(struct filemgr *file,
const char *old_filename,
const char *new_filename);
void filemgr_set_compaction_state(struct filemgr *old_file,
struct filemgr *new_file,
file_status_t status);
void filemgr_remove_pending(struct filemgr *old_file,
struct filemgr *new_file,
err_log_callback *log_callback);
/**
* Return name of the latency stat given its type.
* @param stat The type of the latency stat to be named.
*/
const char *filemgr_latency_stat_name(fdb_latency_stat_type stat);
#ifdef _LATENCY_STATS
/**
* Initialize a latency stats instance
*
* @param val Pointer to a latency stats instance to be initialized
*/
void filemgr_init_latency_stat(struct latency_stat *val);
/**
* Destroy a latency stats instance
*
* @param val Pointer to a latency stats instance to be destroyed
*/
void filemgr_destroy_latency_stat(struct latency_stat *val);
/**
* Migrate the latency stats from the source file to the destination file
*
* @param oldf Pointer to the source file manager
* @param newf Pointer to the destination file manager
*/
void filemgr_migrate_latency_stats(struct filemgr *src,
struct filemgr *dest);
/**
* Update the latency stats for a given file manager
*
* @param file Pointer to the file manager whose latency stats need to be updated
* @param type Type of a latency stat to be updated
* @param val New value of a latency stat
*/
void filemgr_update_latency_stat(struct filemgr *file,
fdb_latency_stat_type type,
uint32_t val);
/**
* Get the latency stats from a given file manager
*
* @param file Pointer to the file manager
* @param type Type of a latency stat to be retrieved
* @param stat Pointer to the stats instance to be populated
*/
void filemgr_get_latency_stat(struct filemgr *file,
fdb_latency_stat_type type,
fdb_latency_stat *stat);
#ifdef _LATENCY_STATS_DUMP_TO_FILE
/**
* Write all the latency stats for a given file manager to a stat log file
*
* @param file Pointer to the file manager
* @param log_callback Pointer to the log callback function
*/
void filemgr_dump_latency_stat(struct filemgr *file,
err_log_callback *log_callback);
#endif // _LATENCY_STATS_DUMP_TO_FILE
#endif // _LATENCY_STATS
struct kvs_ops_stat *filemgr_migrate_op_stats(struct filemgr *old_file,
struct filemgr *new_file,
struct kvs_info *kvs);
fdb_status filemgr_destroy_file(char *filename,
struct filemgr_config *config,
struct hash *destroy_set);
struct filemgr *filemgr_search_stale_links(struct filemgr *cur_file);
typedef char *filemgr_redirect_hdr_func(struct filemgr *old_file,uint8_t *buf,
struct filemgr *new_file);
char *filemgr_redirect_old_file(struct filemgr *very_old_file,
struct filemgr *new_file,
filemgr_redirect_hdr_func redirect_func);
INLINE file_status_t filemgr_get_file_status(struct filemgr *file)
{
return atomic_get_uint8_t(&file->status);
}
INLINE uint64_t filemgr_get_pos(struct filemgr *file)
{
return atomic_get_uint64_t(&file->pos);
}
fdb_status filemgr_copy_file_range(struct filemgr *src_file,
struct filemgr *dst_file,
bid_t src_bid, bid_t dst_bid,
bid_t clone_len);
bool filemgr_is_rollback_on(struct filemgr *file);
void filemgr_set_rollback(struct filemgr *file, uint8_t new_val);
/**
* Set the file manager's flag to cancel the compaction task that is currently running.
*
* @param file Pointer to the file manager instance
* @param cancel True if the compaction should be cancelled.
*/
void filemgr_set_cancel_compaction(struct filemgr *file, bool cancel);
/**
* Return true if a compaction cancellation is requested.
*
* @param file Pointer to the file manager instance
* @return True if a compaction cancellation is requested.
*/
bool filemgr_is_compaction_cancellation_requested(struct filemgr *file);
void filemgr_set_successfully_compacted(struct filemgr *file);
bool filemgr_is_successfully_compacted(struct filemgr *file);
void filemgr_set_in_place_compaction(struct filemgr *file,
bool in_place_compaction);
bool filemgr_is_in_place_compaction_set(struct filemgr *file);
void filemgr_mutex_openlock(struct filemgr_config *config);
void filemgr_mutex_openunlock(void);
void filemgr_mutex_lock(struct filemgr *file);
bool filemgr_mutex_trylock(struct filemgr *file);
void filemgr_mutex_unlock(struct filemgr *file);
bool filemgr_is_commit_header(void *head_buffer, size_t blocksize);
bool filemgr_is_cow_supported(struct filemgr *src, struct filemgr *dst);
void filemgr_set_throttling_delay(struct filemgr *file, uint64_t delay_us);
uint32_t filemgr_get_throttling_delay(struct filemgr *file);
INLINE void filemgr_set_stale_list(struct filemgr *file,
struct list *stale_list)
{
file->stale_list = stale_list;
}
void filemgr_clear_stale_list(struct filemgr *file);
void filemgr_clear_stale_info_tree(struct filemgr *file);
void filemgr_clear_mergetree(struct filemgr *file);
INLINE struct list * filemgr_get_stale_list(struct filemgr *file)
{
return file->stale_list;
}
/**
* Add an item into stale-block list of the given 'file'.
*
* @param file Pointer to file handle.
* @param pos Byte offset to the beginning of the stale region.
* @param len Length of the stale region.
* @return void.
*/
void filemgr_add_stale_block(struct filemgr *file,
bid_t pos,
size_t len);
/**
* Calculate the actual space (including block markers) used for the given document
* data, and return the list of regions to be marked as stale (if the given document
* is not physically consecutive, more than one regions will be returned).
*
* @param file Pointer to file handle.
* @param offset Byte offset to the beginning of the data.
* @param length Length of the data.
* @return List of stale regions.
*/
struct stale_regions filemgr_actual_stale_regions(struct filemgr *file,
bid_t offset,
size_t length);
/**
* Mark the given region (offset, length) as stale.
* This function automatically calculates the additional space used for block
* markers or block matadata, by internally calling filemgr_actual_stale_regions().
*
* @param file Pointer to file handle.
* @param offset Byte offset to the beginning of the data.
* @param length Length of the data.
* @return void.
*/
void filemgr_mark_stale(struct filemgr *file,
bid_t offset,
size_t length);
/**
* The node structure of fhandle index.
*/
struct filemgr_fhandle_idx_node {
/**
* Void pointer to file handle.
*/
void *fhandle;
/**
* AVL tree element.
*/
struct avl_node avl;
};
/**
* Add a FDB file handle into the superblock's global index.
*
* @param file Pointer to filemgr handle.
* @param fhandle Pointer to FDB file handle.
* @return True if successfully added.
*/
bool filemgr_fhandle_add(struct filemgr *file, void *fhandle);
/**
* Remove a FDB file handle from the superblock's global index.
*
* @param file Pointer to filemgr handle.
* @param fhandle Pointer to FDB file handle.
* @return True if successfully removed.
*/
bool filemgr_fhandle_remove(struct filemgr *file, void *fhandle);
/**
* Initialize global structures for dirty update management.
*
* @param file Pointer to filemgr handle.
* @return void.
*/
void filemgr_dirty_update_init(struct filemgr *file);
/**
* Free global structures for dirty update management.
*
* @param file Pointer to filemgr handle.
* @return void.
*/
void filemgr_dirty_update_free(struct filemgr *file);
/**
* Create a new dirty update entry.
*
* @param file Pointer to filemgr handle.
* @return Newly created dirty update entry.
*/
struct filemgr_dirty_update_node *filemgr_dirty_update_new_node(struct filemgr *file);
/**
* Return the latest complete (i.e., immutable) dirty update entry. Note that a
* dirty update that is being updated by a writer thread will not be returned.
*
* @param file Pointer to filemgr handle.
* @return Latest dirty update entry.
*/
struct filemgr_dirty_update_node *filemgr_dirty_update_get_latest(struct filemgr *file);
/**
* Increase the reference counter for the given dirty update entry.
*
* @param node Pointer to dirty update entry to increase reference counter.
* @return void.
*/
void filemgr_dirty_update_inc_ref_count(struct filemgr_dirty_update_node *node);
/**
* Commit the latest complete dirty update entry and write back all updated
* blocks into DB file. This API will remove all complete (i.e., immutable)
* dirty update entries whose reference counter is zero.
*
* @param file Pointer to filemgr handle.
* @param commit_node Pointer to dirty update entry to be flushed.
* @param log_callback Pointer to the log callback function.
* @return void.
*/
void filemgr_dirty_update_commit(struct filemgr *file,
struct filemgr_dirty_update_node *commit_node,
err_log_callback *log_callback);
/**
* Complete the given dirty update entry and make it immutable. This API will
* remove all complete (i.e., immutable) dirty update entries which are prior
* than the given dirty update entry and whose reference counter is zero.
*
* @param file Pointer to filemgr handle.
* @param node Pointer to dirty update entry to complete.
* @param node Pointer to previous dirty update entry.
* @return void.
*/
void filemgr_dirty_update_set_immutable(struct filemgr *file,
struct filemgr_dirty_update_node *prev_node,
struct filemgr_dirty_update_node *node);
/**
* Remove a dirty update entry and discard all dirty blocks from memory.
*
* @param file Pointer to filemgr handle.
* @param node Pointer to dirty update entry to be removed.
* @return void.
*/
void filemgr_dirty_update_remove_node(struct filemgr *file,
struct filemgr_dirty_update_node *node);
/**
* Close a dirty update entry. This API will remove all complete (i.e., immutable)
* dirty update entries except for the last immutable update entry.
*
* @param file Pointer to filemgr handle.
* @param node Pointer to dirty update entry to be closed.
* @return void.
*/
void filemgr_dirty_update_close_node(struct filemgr *file,
struct filemgr_dirty_update_node *node);
/**
* Set dirty root nodes for the given dirty update entry.
*
* @param file Pointer to filemgr handle.
* @param node Pointer to dirty update entry.
* @param dirty_idtree_root BID of ID tree root node.
* @param dirty_seqtree_root BID of sequence tree root node.
* @return void.
*/
INLINE void filemgr_dirty_update_set_root(struct filemgr *file,
struct filemgr_dirty_update_node *node,
bid_t dirty_idtree_root,
bid_t dirty_seqtree_root)
{
if (node) {
node->idtree_root = dirty_idtree_root;
node->seqtree_root = dirty_seqtree_root;
}
}
/**
* Get dirty root nodes for the given dirty update entry.
*
* @param file Pointer to filemgr handle.
* @param node Pointer to dirty update entry.
* @param dirty_idtree_root Pointer to the BID of ID tree root node.
* @param dirty_seqtree_root Pointer to the BID of sequence tree root node.
* @return void.
*/
INLINE void filemgr_dirty_update_get_root(struct filemgr *file,
struct filemgr_dirty_update_node *node,
bid_t *dirty_idtree_root,
bid_t *dirty_seqtree_root)
{
if (node) {
*dirty_idtree_root = node->idtree_root;
*dirty_seqtree_root = node->seqtree_root;
} else {
*dirty_idtree_root = *dirty_seqtree_root = BLK_NOT_FOUND;
}
}
/**
* Write a dirty block into the given dirty update entry.
*
* @param file Pointer to filemgr handle.
* @param bid BID of the block to be written.
* @param buf Pointer to the buffer containing the data to be written.
* @param node Pointer to the dirty update entry.
* @param log_callback Pointer to the log callback function.
* @return FDB_RESULT_SUCCESS on success.
*/
fdb_status filemgr_write_dirty(struct filemgr *file,
bid_t bid,
void *buf,
struct filemgr_dirty_update_node *node,
err_log_callback *log_callback);
/**
* Read a block through the given dirty update entries. It first tries to read
* the block from the writer's (which is being updated) dirty update entry,
* and then tries to read it from the reader's (which already became immutable)
* dirty update entry. If the block doesn't exist in both entries, then it reads
* the block from DB file.
*
* @param file Pointer to filemgr handle.
* @param bid BID of the block to be read.
* @param buf Pointer to the buffer where the read data will be copied.
* @param node_reader Pointer to the immutable dirty update entry.
* @param node_writer Pointer to the mutable dirty update entry.
* @param log_callback Pointer to the log callback function.
* @param read_on_cache_miss True if we want to read the block from file after
* cache miss.
* @return FDB_RESULT_SUCCESS on success.
*/
fdb_status filemgr_read_dirty(struct filemgr *file,
bid_t bid,
void *buf,
struct filemgr_dirty_update_node *node_reader,
struct filemgr_dirty_update_node *node_writer,
err_log_callback *log_callback,
bool read_on_cache_miss);
void _kvs_stat_set(struct filemgr *file,
fdb_kvs_id_t kv_id,
struct kvs_stat stat);
void _kvs_stat_update_attr(struct filemgr *file,
fdb_kvs_id_t kv_id,
kvs_stat_attr_t attr,
int64_t delta);
int _kvs_stat_get_kv_header(struct kvs_header *kv_header,
fdb_kvs_id_t kv_id,
struct kvs_stat *stat);
int _kvs_stat_get(struct filemgr *file,
fdb_kvs_id_t kv_id,
struct kvs_stat *stat);
uint64_t _kvs_stat_get_sum(struct filemgr *file,
kvs_stat_attr_t attr);
int _kvs_ops_stat_get_kv_header(struct kvs_header *kv_header,
fdb_kvs_id_t kv_id,
struct kvs_ops_stat *stat);
int _kvs_ops_stat_get(struct filemgr *file,
fdb_kvs_id_t kv_id,
struct kvs_ops_stat *stat);
void _init_op_stats(struct kvs_ops_stat *stat);
struct kvs_ops_stat *filemgr_get_ops_stats(struct filemgr *file,
struct kvs_info *info);
/**
* Convert a given errno value to the corresponding fdb_status value.
*
* @param errno_value errno value
* @param default_status Default fdb_status value to be returned if
* there is no corresponding fdb_status value for a given errno value.
* @return fdb_status value that corresponds to a given errno value
*/
fdb_status convert_errno_to_fdb_status(int errno_value,
fdb_status default_status);
void _print_cache_stats();
#ifdef __cplusplus
}
#endif
#endif
| 34.637744 | 100 | 0.674599 |
302b6145f7b7b6af3546ed5fa3801c3c5c1d9f4d | 17,087 | h | C | kernel/include/rtochius/radix-tree.h | tianhengZhang/rtochius | 4b42e36e5008f1a92326376e7c5986cc91095350 | [
"Apache-2.0"
] | null | null | null | kernel/include/rtochius/radix-tree.h | tianhengZhang/rtochius | 4b42e36e5008f1a92326376e7c5986cc91095350 | [
"Apache-2.0"
] | 1 | 2022-03-23T15:56:33.000Z | 2022-03-23T15:58:17.000Z | kernel/include/rtochius/radix-tree.h | tianhengZhang/rtochius | 4b42e36e5008f1a92326376e7c5986cc91095350 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2001 Momchil Velikov
* Portions Copyright (C) 2001 Christoph Hellwig
* Copyright (C) 2006 Nick Piggin
* Copyright (C) 2012 Konstantin Khlebnikov
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __RTOCHIUS_RADIX_TREE_H_
#define __RTOCHIUS_RADIX_TREE_H_
#include <base/bitops.h>
#include <base/common.h>
#include <base/list.h>
#include <base/types.h>
#include <rtochius/preempt.h>
#include <rtochius/spinlock.h>
#include <rtochius/xarray.h>
/* Keep unconverted code working */
#define radix_tree_root xarray
#define radix_tree_node xa_node
/*
* The bottom two bits of the slot determine how the remaining bits in the
* slot are interpreted:
*
* 00 - data pointer
* 10 - internal entry
* x1 - value entry
*
* The internal entry may be a pointer to the next level in the tree, a
* sibling entry, or an indicator that the entry in this slot has been moved
* to another location in the tree and the lookup should be restarted. While
* NULL fits the 'data pointer' pattern, it means that there is no entry in
* the tree for this index (no matter what level of the tree it is found at).
* This means that storing a NULL entry in the tree is the same as deleting
* the entry from the tree.
*/
#define RADIX_TREE_ENTRY_MASK 3UL
#define RADIX_TREE_INTERNAL_NODE 2UL
static inline bool radix_tree_is_internal_node(void *ptr)
{
return ((unsigned long)ptr & RADIX_TREE_ENTRY_MASK) ==
RADIX_TREE_INTERNAL_NODE;
}
/*** radix-tree API starts here ***/
#define RADIX_TREE_MAP_SHIFT XA_CHUNK_SHIFT
#define RADIX_TREE_MAP_SIZE (1UL << RADIX_TREE_MAP_SHIFT)
#define RADIX_TREE_MAP_MASK (RADIX_TREE_MAP_SIZE-1)
#define RADIX_TREE_MAX_TAGS XA_MAX_MARKS
#define RADIX_TREE_TAG_LONGS XA_MARK_LONGS
#define RADIX_TREE_INDEX_BITS (8 /* CHAR_BIT */ * sizeof(unsigned long))
#define RADIX_TREE_MAX_PATH (DIV_ROUND_UP(RADIX_TREE_INDEX_BITS, \
RADIX_TREE_MAP_SHIFT))
/* The IDR tag is stored in the low bits of xa_flags */
#define ROOT_IS_IDR ((gfp_t)4)
/* The top bits of xa_flags are used to store the root tags */
#define ROOT_TAG_SHIFT (__GFP_BITS_SHIFT)
#define RADIX_TREE_INIT(name, mask) XARRAY_INIT(name, mask)
#define RADIX_TREE(name, mask) \
struct radix_tree_root name = RADIX_TREE_INIT(name, mask)
#define INIT_RADIX_TREE(root, mask) xa_init_flags(root, mask)
static inline bool radix_tree_empty(const struct radix_tree_root *root)
{
return root->xa_head == NULL;
}
/**
* struct radix_tree_iter - radix tree iterator state
*
* @index: index of current slot
* @next_index: one beyond the last index for this chunk
* @tags: bit-mask for tag-iterating
* @node: node that contains current slot
*
* This radix tree iterator works in terms of "chunks" of slots. A chunk is a
* subinterval of slots contained within one radix tree leaf node. It is
* described by a pointer to its first slot and a struct radix_tree_iter
* which holds the chunk's position in the tree and its size. For tagged
* iteration radix_tree_iter also holds the slots' bit-mask for one chosen
* radix tree tag.
*/
struct radix_tree_iter {
unsigned long index;
unsigned long next_index;
unsigned long tags;
struct radix_tree_node *node;
};
/**
* Radix-tree synchronization
*
* The radix-tree API requires that users provide all synchronisation (with
* specific exceptions, noted below).
*
* Synchronization of access to the data items being stored in the tree, and
* management of their lifetimes must be completely managed by API users.
*
* For API usage, in general,
* - any function _modifying_ the tree or tags (inserting or deleting
* items, setting or clearing tags) must exclude other modifications, and
* exclude any functions reading the tree.
* - any function _reading_ the tree or tags (looking up items or tags,
* gang lookups) must exclude modifications to the tree, but may occur
* concurrently with other readers.
*
* The notable exceptions to this rule are the following functions:
* __radix_tree_lookup
* radix_tree_lookup
* radix_tree_lookup_slot
* radix_tree_tag_get
* radix_tree_gang_lookup
* radix_tree_gang_lookup_tag
* radix_tree_gang_lookup_tag_slot
* radix_tree_tagged
*
* The first 7 functions are able to be called locklessly, using RCU. The
* caller must ensure calls to these functions are made within rcu_read_lock()
* regions. Other readers (lock-free or otherwise) and modifications may be
* running concurrently.
*
* It is still required that the caller manage the synchronization and lifetimes
* of the items. So if RCU lock-free lookups are used, typically this would mean
* that the items have their own locks, or are amenable to lock-free access; and
* that the items are freed by RCU (or only freed after having been deleted from
* the radix tree *and* a synchronize_rcu() grace period).
*
* (Note, rcu_assign_pointer and rcu_dereference are not needed to control
* access to data items when inserting into or looking up from the radix tree)
*
* Note that the value returned by radix_tree_tag_get() may not be relied upon
* if only the RCU read lock is held. Functions to set/clear tags and to
* delete nodes running concurrently with it may affect its result such that
* two consecutive reads in the same locked section may return different
* values. If reliability is required, modification functions must also be
* excluded from concurrency.
*
* radix_tree_tagged is able to be called without locking or RCU.
*/
/**
* radix_tree_deref_slot - dereference a slot
* @slot: slot pointer, returned by radix_tree_lookup_slot
*
* For use with radix_tree_lookup_slot(). Caller must hold tree at least read
* locked across slot lookup and dereference. Not required if write lock is
* held (ie. items cannot be concurrently inserted).
*
* radix_tree_deref_retry must be used to confirm validity of the pointer if
* only the read lock is held.
*
* Return: entry stored in that slot.
*/
static inline void *radix_tree_deref_slot(void **slot)
{
return dereference_check(*slot);
}
/**
* radix_tree_deref_slot_protected - dereference a slot with tree lock held
* @slot: slot pointer, returned by radix_tree_lookup_slot
*
* Similar to radix_tree_deref_slot. The caller does not hold the RCU read
* lock but it must hold the tree lock to prevent parallel updates.
*
* Return: entry stored in that slot.
*/
static inline void *radix_tree_deref_slot_protected(void **slot,
spinlock_t *treelock)
{
return dereference_protected(*slot);
}
/**
* radix_tree_deref_retry - check radix_tree_deref_slot
* @arg: pointer returned by radix_tree_deref_slot
* Returns: 0 if retry is not required, otherwise retry is required
*
* radix_tree_deref_retry must be used with radix_tree_deref_slot.
*/
static inline int radix_tree_deref_retry(void *arg)
{
return unlikely(radix_tree_is_internal_node(arg));
}
/**
* radix_tree_exception - radix_tree_deref_slot returned either exception?
* @arg: value returned by radix_tree_deref_slot
* Returns: 0 if well-aligned pointer, non-0 if either kind of exception.
*/
static inline int radix_tree_exception(void *arg)
{
return unlikely((unsigned long)arg & RADIX_TREE_ENTRY_MASK);
}
int radix_tree_insert(struct radix_tree_root *, unsigned long index,
void *);
void *__radix_tree_lookup(const struct radix_tree_root *, unsigned long index,
struct radix_tree_node **nodep, void ***slotp);
void *radix_tree_lookup(const struct radix_tree_root *, unsigned long);
void **radix_tree_lookup_slot(const struct radix_tree_root *,
unsigned long index);
void __radix_tree_replace(struct radix_tree_root *, struct radix_tree_node *,
void **slot, void *entry);
void radix_tree_iter_replace(struct radix_tree_root *,
const struct radix_tree_iter *, void **slot, void *entry);
void radix_tree_replace_slot(struct radix_tree_root *,
void **slot, void *entry);
void radix_tree_iter_delete(struct radix_tree_root *,
struct radix_tree_iter *iter, void **slot);
void *radix_tree_delete_item(struct radix_tree_root *, unsigned long, void *);
void *radix_tree_delete(struct radix_tree_root *, unsigned long);
unsigned int radix_tree_gang_lookup(const struct radix_tree_root *,
void **results, unsigned long first_index,
unsigned int max_items);
int radix_tree_preload(gfp_t gfp_mask);
int radix_tree_maybe_preload(gfp_t gfp_mask);
void radix_tree_init(void);
void *radix_tree_tag_set(struct radix_tree_root *,
unsigned long index, unsigned int tag);
void *radix_tree_tag_clear(struct radix_tree_root *,
unsigned long index, unsigned int tag);
int radix_tree_tag_get(const struct radix_tree_root *,
unsigned long index, unsigned int tag);
void radix_tree_iter_tag_clear(struct radix_tree_root *,
const struct radix_tree_iter *iter, unsigned int tag);
unsigned int radix_tree_gang_lookup_tag(const struct radix_tree_root *,
void **results, unsigned long first_index,
unsigned int max_items, unsigned int tag);
unsigned int radix_tree_gang_lookup_tag_slot(const struct radix_tree_root *,
void ***results, unsigned long first_index,
unsigned int max_items, unsigned int tag);
int radix_tree_tagged(const struct radix_tree_root *, unsigned int tag);
static inline void radix_tree_preload_end(void)
{
preempt_enable();
}
void **idr_get_free(struct radix_tree_root *root,
struct radix_tree_iter *iter, gfp_t gfp,
unsigned long max);
enum {
RADIX_TREE_ITER_TAG_MASK = 0x0f, /* tag index in lower nybble */
RADIX_TREE_ITER_TAGGED = 0x10, /* lookup tagged slots */
RADIX_TREE_ITER_CONTIG = 0x20, /* stop at first hole */
};
/**
* radix_tree_iter_init - initialize radix tree iterator
*
* @iter: pointer to iterator state
* @start: iteration starting index
* Returns: NULL
*/
static __always_inline void **
radix_tree_iter_init(struct radix_tree_iter *iter, unsigned long start)
{
/*
* Leave iter->tags uninitialized. radix_tree_next_chunk() will fill it
* in the case of a successful tagged chunk lookup. If the lookup was
* unsuccessful or non-tagged then nobody cares about ->tags.
*
* Set index to zero to bypass next_index overflow protection.
* See the comment in radix_tree_next_chunk() for details.
*/
iter->index = 0;
iter->next_index = start;
return NULL;
}
/**
* radix_tree_next_chunk - find next chunk of slots for iteration
*
* @root: radix tree root
* @iter: iterator state
* @flags: RADIX_TREE_ITER_* flags and tag index
* Returns: pointer to chunk first slot, or NULL if there no more left
*
* This function looks up the next chunk in the radix tree starting from
* @iter->next_index. It returns a pointer to the chunk's first slot.
* Also it fills @iter with data about chunk: position in the tree (index),
* its end (next_index), and constructs a bit mask for tagged iterating (tags).
*/
void **radix_tree_next_chunk(const struct radix_tree_root *,
struct radix_tree_iter *iter, unsigned flags);
/**
* radix_tree_iter_lookup - look up an index in the radix tree
* @root: radix tree root
* @iter: iterator state
* @index: key to look up
*
* If @index is present in the radix tree, this function returns the slot
* containing it and updates @iter to describe the entry. If @index is not
* present, it returns NULL.
*/
static inline void **
radix_tree_iter_lookup(const struct radix_tree_root *root,
struct radix_tree_iter *iter, unsigned long index)
{
radix_tree_iter_init(iter, index);
return radix_tree_next_chunk(root, iter, RADIX_TREE_ITER_CONTIG);
}
/**
* radix_tree_iter_find - find a present entry
* @root: radix tree root
* @iter: iterator state
* @index: start location
*
* This function returns the slot containing the entry with the lowest index
* which is at least @index. If @index is larger than any present entry, this
* function returns NULL. The @iter is updated to describe the entry found.
*/
static inline void **
radix_tree_iter_find(const struct radix_tree_root *root,
struct radix_tree_iter *iter, unsigned long index)
{
radix_tree_iter_init(iter, index);
return radix_tree_next_chunk(root, iter, 0);
}
/**
* radix_tree_iter_retry - retry this chunk of the iteration
* @iter: iterator state
*
* If we iterate over a tree protected only by the RCU lock, a race
* against deletion or creation may result in seeing a slot for which
* radix_tree_deref_retry() returns true. If so, call this function
* and continue the iteration.
*/
static inline
void **radix_tree_iter_retry(struct radix_tree_iter *iter)
{
iter->next_index = iter->index;
iter->tags = 0;
return NULL;
}
static inline unsigned long
__radix_tree_iter_add(struct radix_tree_iter *iter, unsigned long slots)
{
return iter->index + slots;
}
/**
* radix_tree_iter_resume - resume iterating when the chunk may be invalid
* @slot: pointer to current slot
* @iter: iterator state
* Returns: New slot pointer
*
* If the iterator needs to release then reacquire a lock, the chunk may
* have been invalidated by an insertion or deletion. Call this function
* before releasing the lock to continue the iteration from the next index.
*/
void **radix_tree_iter_resume(void **slot,
struct radix_tree_iter *iter);
/**
* radix_tree_chunk_size - get current chunk size
*
* @iter: pointer to radix tree iterator
* Returns: current chunk size
*/
static __always_inline long
radix_tree_chunk_size(struct radix_tree_iter *iter)
{
return iter->next_index - iter->index;
}
/**
* radix_tree_next_slot - find next slot in chunk
*
* @slot: pointer to current slot
* @iter: pointer to interator state
* @flags: RADIX_TREE_ITER_*, should be constant
* Returns: pointer to next slot, or NULL if there no more left
*
* This function updates @iter->index in the case of a successful lookup.
* For tagged lookup it also eats @iter->tags.
*
* There are several cases where 'slot' can be passed in as NULL to this
* function. These cases result from the use of radix_tree_iter_resume() or
* radix_tree_iter_retry(). In these cases we don't end up dereferencing
* 'slot' because either:
* a) we are doing tagged iteration and iter->tags has been set to 0, or
* b) we are doing non-tagged iteration, and iter->index and iter->next_index
* have been set up so that radix_tree_chunk_size() returns 1 or 0.
*/
static __always_inline void **radix_tree_next_slot(void **slot,
struct radix_tree_iter *iter, unsigned flags)
{
if (flags & RADIX_TREE_ITER_TAGGED) {
iter->tags >>= 1;
if (unlikely(!iter->tags))
return NULL;
if (likely(iter->tags & 1ul)) {
iter->index = __radix_tree_iter_add(iter, 1);
slot++;
goto found;
}
if (!(flags & RADIX_TREE_ITER_CONTIG)) {
unsigned offset = __ffs(iter->tags);
iter->tags >>= offset++;
iter->index = __radix_tree_iter_add(iter, offset);
slot += offset;
goto found;
}
} else {
long count = radix_tree_chunk_size(iter);
while (--count > 0) {
slot++;
iter->index = __radix_tree_iter_add(iter, 1);
if (likely(*slot))
goto found;
if (flags & RADIX_TREE_ITER_CONTIG) {
/* forbid switching to the next chunk */
iter->next_index = 0;
break;
}
}
}
return NULL;
found:
return slot;
}
/**
* radix_tree_for_each_slot - iterate over non-empty slots
*
* @slot: the void** variable for pointer to slot
* @root: the struct radix_tree_root pointer
* @iter: the struct radix_tree_iter pointer
* @start: iteration starting index
*
* @slot points to radix tree slot, @iter->index contains its index.
*/
#define radix_tree_for_each_slot(slot, root, iter, start) \
for (slot = radix_tree_iter_init(iter, start) ; \
slot || (slot = radix_tree_next_chunk(root, iter, 0)) ; \
slot = radix_tree_next_slot(slot, iter, 0))
/**
* radix_tree_for_each_tagged - iterate over tagged slots
*
* @slot: the void** variable for pointer to slot
* @root: the struct radix_tree_root pointer
* @iter: the struct radix_tree_iter pointer
* @start: iteration starting index
* @tag: tag index
*
* @slot points to radix tree slot, @iter->index contains its index.
*/
#define radix_tree_for_each_tagged(slot, root, iter, start, tag) \
for (slot = radix_tree_iter_init(iter, start) ; \
slot || (slot = radix_tree_next_chunk(root, iter, \
RADIX_TREE_ITER_TAGGED | tag)) ; \
slot = radix_tree_next_slot(slot, iter, \
RADIX_TREE_ITER_TAGGED | tag))
void __radix_tree_node_free(struct list_head *list);
#endif /* !__RTOCHIUS_RADIX_TREE_H_ */
| 34.589069 | 80 | 0.746649 |
5cbefe86823d3884fbbd541adc07230fe14c62af | 7,727 | h | C | src/aligner_build_results_thread.h | nanprogramer/ghostz-gpu | 89f51c54ec8f6141801287dadc35174f9d7c70e0 | [
"BSD-2-Clause"
] | null | null | null | src/aligner_build_results_thread.h | nanprogramer/ghostz-gpu | 89f51c54ec8f6141801287dadc35174f9d7c70e0 | [
"BSD-2-Clause"
] | 1 | 2021-01-21T14:09:32.000Z | 2021-01-21T14:09:32.000Z | src/aligner_build_results_thread.h | Surfndez/ghostz-gpu | 89f51c54ec8f6141801287dadc35174f9d7c70e0 | [
"BSD-2-Clause"
] | null | null | null | /*
* aligner_build_results_thread.h
*
* Created on: Aug 11, 2014
* Author: shu
*/
#ifndef ALIGNER_BUILD_RESULTS_THREAD_H_
#define ALIGNER_BUILD_RESULTS_THREAD_H_
#include <boost/thread.hpp>
#include <boost/thread/barrier.hpp>
#include "queries.h"
#include "database.h"
#include "aligner_common.h"
#include "gapped_extender.h"
template<typename TDatabase>
class AlignerBuildResultsThread {
public:
typedef TDatabase Database;
struct Parameters {
boost::mutex *next_result_ids_list_i_mutex;
boost::mutex *next_query_id_mutex;
int thread_id;
uint32_t *next_result_ids_list_i;
uint32_t *next_query_id;
Queries *queries;
Database *database;
std::vector<AlignerCommon::PresearchedResult> *presearch_results_list;
std::vector<AlignerCommon::Result> *results_list;
std::vector<std::pair<uint32_t, uint32_t> > *result_ids_list;
int gapped_extension_cutoff;
AlignerCommon::AligningCommonParameters *aligningParameters;
boost::barrier *all_barrier;
};
AlignerBuildResultsThread();
virtual ~AlignerBuildResultsThread();
void Run(Parameters ¶meters);
private:
static const uint32_t kResultIdsIIncrement = 1 << 5;
static const uint32_t kQueryIdsIncrement = 1 << 5;
int PopResultIdsI(size_t result_ids_list_size,
std::vector<uint32_t> *result_ids_i_stack);
int PopQueryIds(size_t number_queries, std::vector<uint32_t> *query_ids);
Parameters *parameters_;
};
template<typename TDatabase>
AlignerBuildResultsThread<TDatabase>::AlignerBuildResultsThread() :
parameters_(NULL) {
}
template<typename TDatabase>
AlignerBuildResultsThread<TDatabase>::~AlignerBuildResultsThread() {
}
template<typename TDatabase>
void AlignerBuildResultsThread<TDatabase>::Run(Parameters ¶meters) {
parameters_ = ¶meters;
if (parameters_->thread_id == 0) {
parameters_->database->ResetChunk();
*(parameters_->next_query_id) = 0;
}
std::vector<uint32_t> result_ids_i_stack;
parameters_->all_barrier->wait();
while (parameters_->database->GetChunkId()
< (int) parameters_->database->GetNumberChunks()) {
if (parameters_->thread_id < 0) {
typename Database::PreloadTarget target = Database::kName
| Database::kSequence | Database::kOffset;
parameters_->database->Preload(
parameters_->database->GetChunkId() + 1, target);
} else {
const uint32_t database_chunk_id =
parameters_->database->GetChunkId();
const AlphabetCoder::Code *database_concatenated_sequence =
parameters_->database->GetConcatenatedSequence();
std::vector<std::pair<uint32_t, uint32_t> > &result_ids =
parameters_->result_ids_list[database_chunk_id];
const size_t result_ids_list_size = result_ids.size();
EditBlocks edit_blocks;
EditBlocks tmp_edit_blocks;
GappedExtender gapped_extender;
while (!PopResultIdsI(result_ids_list_size, &result_ids_i_stack)) {
while (!result_ids_i_stack.empty()) {
uint32_t result_ids_i = result_ids_i_stack.back();
result_ids_i_stack.pop_back();
edit_blocks.Clear();
assert(result_ids_i < result_ids_list_size);
uint32_t query_id = result_ids[result_ids_i].first;
uint32_t result_id = result_ids[result_ids_i].second;
assert(
query_id
< parameters_->queries->GetNumberOfSequences());
assert(
result_id
< (parameters_->results_list)[query_id].size());
Query *query = parameters_->queries->GetQuery(query_id);
int sum_score = 0;
AlignerCommon::Coordinate hit;
AlignerCommon::Coordinate start;
AlignerCommon::Coordinate end;
AlignerCommon::PresearchedResult *presearched_result_ptr =
¶meters_->presearch_results_list[query_id][result_id];
hit.query_position =
presearched_result_ptr->hit.query_position;
hit.database_position =
presearched_result_ptr->hit.database_position;
int score;
int query_position;
int database_position;
gapped_extender.ExtendOneSide(
query->GetSequence() + hit.query_position - 1,
hit.query_position - 1,
database_concatenated_sequence
+ hit.database_position - 1,
query->GetSequenceDelimiter(), true,
parameters_->aligningParameters->score_matrix,
parameters_->aligningParameters->gap_open,
parameters_->aligningParameters->gap_extension,
parameters_->gapped_extension_cutoff, &score,
&query_position, &database_position,
&tmp_edit_blocks);
sum_score += score;
start.query_position = hit.query_position - 1
+ query_position;
start.database_position = hit.database_position - 1
+ database_position;
tmp_edit_blocks.Reverse();
edit_blocks.Add(tmp_edit_blocks);
gapped_extender.ExtendOneSide(
query->GetSequence() + hit.query_position,
query->GetSequenceLength() - hit.query_position,
database_concatenated_sequence
+ hit.database_position,
query->GetSequenceDelimiter(), false,
parameters_->aligningParameters->score_matrix,
parameters_->aligningParameters->gap_open,
parameters_->aligningParameters->gap_extension,
parameters_->gapped_extension_cutoff, &score,
&query_position, &database_position,
&tmp_edit_blocks);
sum_score += score;
end.query_position = hit.query_position + query_position;
end.database_position = hit.database_position
+ database_position;
edit_blocks.Add(tmp_edit_blocks);
std::vector<EditBlocks::EditOpType> edits =
edit_blocks.ToVector();
AlignerCommon::BuildResult(*query, *(parameters_->database),
presearched_result_ptr->database_chunk_id,
presearched_result_ptr->subject_id_in_chunk,
sum_score, hit, start, end, edits,
parameters_->results_list[query_id][result_id]);
}
}
}
parameters_->all_barrier->wait();
if (parameters_->thread_id == 0) {
parameters_->database->NextChunk();
*(parameters_->next_result_ids_list_i) = 0;
}
parameters_->all_barrier->wait();
}
parameters_->all_barrier->wait();
std::vector<uint32_t> query_ids;
size_t number_queries = parameters_->queries->GetNumberOfSequences();
while (!PopQueryIds(number_queries, &query_ids)) {
while (!query_ids.empty()) {
uint32_t query_id = query_ids.back();
query_ids.pop_back();
sort(parameters_->results_list[query_id].begin(),
parameters_->results_list[query_id].end(),
AlignerCommon::ResultGreaterScore());
}
}
}
template<typename TDatabase>
int AlignerBuildResultsThread<TDatabase>::PopResultIdsI(size_t result_ids_list_size,
std::vector<uint32_t> *result_ids_i_stack) {
uint32_t start_id = 0;
uint32_t end_id = 0;
assert(result_ids_i_stack->empty());
{
boost::unique_lock<boost::mutex> lock(*(parameters_->next_result_ids_list_i_mutex));
start_id = *(parameters_->next_result_ids_list_i);
end_id = std::min(result_ids_list_size,
size_t(start_id + kResultIdsIIncrement));
*(parameters_->next_result_ids_list_i) = end_id;
}
for (uint32_t i = start_id; i < end_id; ++i) {
result_ids_i_stack->push_back(i);
}
return result_ids_i_stack->empty() ? 1 : 0;
}
template<typename TDatabase>
int AlignerBuildResultsThread<TDatabase>::PopQueryIds(size_t number_queries,
std::vector<uint32_t> *query_ids) {
uint32_t start_id = 0;
uint32_t end_id = 0;
assert(query_ids->empty());
{
boost::unique_lock<boost::mutex> lock(*(parameters_->next_query_id_mutex));
start_id = *(parameters_->next_query_id);
end_id = std::min(number_queries,
size_t(start_id + kQueryIdsIncrement));
*(parameters_->next_query_id) = end_id;
}
for (uint32_t i = start_id; i < end_id; ++i) {
query_ids->push_back(i);
}
return query_ids->empty() ? 1 : 0;
}
#endif /* ALIGNER_BUILD_RESULTS_THREAD_H_ */
| 33.306034 | 86 | 0.731461 |
65985036c5c34135cca8f9e487d0fbc35148e6b3 | 9,711 | c | C | sources/drivers/acpi/acpica/utaddress.c | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | 2 | 2018-03-09T23:59:27.000Z | 2018-04-01T07:58:39.000Z | sources/drivers/acpi/acpica/utaddress.c | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | null | null | null | sources/drivers/acpi/acpica/utaddress.c | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | 3 | 2017-06-24T20:23:09.000Z | 2018-03-25T04:30:11.000Z | /******************************************************************************
*
* Module Name: utaddress - op_region address range check
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2014, Intel Corp.
* 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,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* 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 MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"
#define _COMPONENT ACPI_UTILITIES
ACPI_MODULE_NAME("utaddress")
/*******************************************************************************
*
* FUNCTION: acpi_ut_add_address_range
*
* PARAMETERS: space_id - Address space ID
* address - op_region start address
* length - op_region length
* region_node - op_region namespace node
*
* RETURN: Status
*
* DESCRIPTION: Add the Operation Region address range to the global list.
* The only supported Space IDs are Memory and I/O. Called when
* the op_region address/length operands are fully evaluated.
*
* MUTEX: Locks the namespace
*
* NOTE: Because this interface is only called when an op_region argument
* list is evaluated, there cannot be any duplicate region_nodes.
* Duplicate Address/Length values are allowed, however, so that multiple
* address conflicts can be detected.
*
******************************************************************************/
acpi_status
acpi_ut_add_address_range(acpi_adr_space_type space_id,
acpi_physical_address address,
u32 length, struct acpi_namespace_node *region_node)
{
struct acpi_address_range *range_info;
acpi_status status;
ACPI_FUNCTION_TRACE(ut_add_address_range);
if ((space_id != ACPI_ADR_SPACE_SYSTEM_MEMORY) &&
(space_id != ACPI_ADR_SPACE_SYSTEM_IO)) {
return_ACPI_STATUS(AE_OK);
}
/* Allocate/init a new info block, add it to the appropriate list */
range_info = ACPI_ALLOCATE(sizeof(struct acpi_address_range));
if (!range_info) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
range_info->start_address = address;
range_info->end_address = (address + length - 1);
range_info->region_node = region_node;
status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE(status)) {
ACPI_FREE(range_info);
return_ACPI_STATUS(status);
}
range_info->next = acpi_gbl_address_range_list[space_id];
acpi_gbl_address_range_list[space_id] = range_info;
ACPI_DEBUG_PRINT((ACPI_DB_NAMES,
"\nAdded [%4.4s] address range: 0x%8.8X%8.8X-0x%8.8X%8.8X\n",
acpi_ut_get_node_name(range_info->region_node),
ACPI_FORMAT_UINT64(address),
ACPI_FORMAT_UINT64(range_info->end_address)));
(void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE);
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_remove_address_range
*
* PARAMETERS: space_id - Address space ID
* region_node - op_region namespace node
*
* RETURN: None
*
* DESCRIPTION: Remove the Operation Region from the global list. The only
* supported Space IDs are Memory and I/O. Called when an
* op_region is deleted.
*
* MUTEX: Assumes the namespace is locked
*
******************************************************************************/
void
acpi_ut_remove_address_range(acpi_adr_space_type space_id,
struct acpi_namespace_node *region_node)
{
struct acpi_address_range *range_info;
struct acpi_address_range *prev;
ACPI_FUNCTION_TRACE(ut_remove_address_range);
if ((space_id != ACPI_ADR_SPACE_SYSTEM_MEMORY) &&
(space_id != ACPI_ADR_SPACE_SYSTEM_IO)) {
return_VOID;
}
/* Get the appropriate list head and check the list */
range_info = prev = acpi_gbl_address_range_list[space_id];
while (range_info) {
if (range_info->region_node == region_node) {
if (range_info == prev) { /* Found at list head */
acpi_gbl_address_range_list[space_id] =
range_info->next;
} else {
prev->next = range_info->next;
}
ACPI_DEBUG_PRINT((ACPI_DB_NAMES,
"\nRemoved [%4.4s] address range: 0x%8.8X%8.8X-0x%8.8X%8.8X\n",
acpi_ut_get_node_name(range_info->
region_node),
ACPI_FORMAT_UINT64(range_info->
start_address),
ACPI_FORMAT_UINT64(range_info->
end_address)));
ACPI_FREE(range_info);
return_VOID;
}
prev = range_info;
range_info = range_info->next;
}
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_check_address_range
*
* PARAMETERS: space_id - Address space ID
* address - Start address
* length - Length of address range
* warn - TRUE if warning on overlap desired
*
* RETURN: Count of the number of conflicts detected. Zero is always
* returned for Space IDs other than Memory or I/O.
*
* DESCRIPTION: Check if the input address range overlaps any of the
* ASL operation region address ranges. The only supported
* Space IDs are Memory and I/O.
*
* MUTEX: Assumes the namespace is locked.
*
******************************************************************************/
u32
acpi_ut_check_address_range(acpi_adr_space_type space_id,
acpi_physical_address address, u32 length, u8 warn)
{
struct acpi_address_range *range_info;
acpi_physical_address end_address;
char *pathname;
u32 overlap_count = 0;
ACPI_FUNCTION_TRACE(ut_check_address_range);
if ((space_id != ACPI_ADR_SPACE_SYSTEM_MEMORY) &&
(space_id != ACPI_ADR_SPACE_SYSTEM_IO)) {
return_UINT32(0);
}
range_info = acpi_gbl_address_range_list[space_id];
end_address = address + length - 1;
/* Check entire list for all possible conflicts */
while (range_info) {
/*
* Check if the requested address/length overlaps this
* address range. There are four cases to consider:
*
* 1) Input address/length is contained completely in the
* address range
* 2) Input address/length overlaps range at the range start
* 3) Input address/length overlaps range at the range end
* 4) Input address/length completely encompasses the range
*/
if ((address <= range_info->end_address) &&
(end_address >= range_info->start_address)) {
/* Found an address range overlap */
overlap_count++;
if (warn) { /* Optional warning message */
pathname =
acpi_ns_get_external_pathname(range_info->
region_node);
ACPI_WARNING((AE_INFO,
"%s range 0x%8.8X%8.8X-0x%8.8X%8.8X conflicts with OpRegion 0x%8.8X%8.8X-0x%8.8X%8.8X (%s)",
acpi_ut_get_region_name(space_id),
ACPI_FORMAT_UINT64(address),
ACPI_FORMAT_UINT64(end_address),
ACPI_FORMAT_UINT64(range_info->
start_address),
ACPI_FORMAT_UINT64(range_info->
end_address),
pathname));
ACPI_FREE(pathname);
}
}
range_info = range_info->next;
}
return_UINT32(overlap_count);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_delete_address_lists
*
* PARAMETERS: None
*
* RETURN: None
*
* DESCRIPTION: Delete all global address range lists (called during
* subsystem shutdown).
*
******************************************************************************/
void acpi_ut_delete_address_lists(void)
{
struct acpi_address_range *next;
struct acpi_address_range *range_info;
int i;
/* Delete all elements in all address range lists */
for (i = 0; i < ACPI_ADDRESS_RANGE_MAX; i++) {
next = acpi_gbl_address_range_list[i];
while (next) {
range_info = next;
next = range_info->next;
ACPI_FREE(range_info);
}
acpi_gbl_address_range_list[i] = NULL;
}
}
| 32.587248 | 103 | 0.640923 |
458f6dcee334e0d78563b949b84143aae9858f25 | 355 | c | C | c-intro-gb/D17.c | andreitsy/problem-solutions | 366423ae1976bbf2d2d24934a439e7bc23c84b1a | [
"MIT"
] | null | null | null | c-intro-gb/D17.c | andreitsy/problem-solutions | 366423ae1976bbf2d2d24934a439e7bc23c84b1a | [
"MIT"
] | null | null | null | c-intro-gb/D17.c | andreitsy/problem-solutions | 366423ae1976bbf2d2d24934a439e7bc23c84b1a | [
"MIT"
] | null | null | null | #include <stdio.h>
int akkerman(int m, int n)
{
if (m == 0){
return n + 1;
}
else if((m > 0) && (n == 0)){
return akkerman(m - 1, 1);
}
else if((m > 0) && (n > 0)){
return akkerman(m - 1, akkerman(m, n - 1));
}
}
int main() {
int n, m;
scanf("%i %i", &m, &n);
printf("%i", akkerman(m, n));
}
| 16.136364 | 51 | 0.411268 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.