*
\***********************************************************************/
-
#include "xbt/RngStream.h"
#include "xbt/sysdep.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-
/*---------------------------------------------------------------------*/
/* Private part. */
/*---------------------------------------------------------------------*/
-
#define norm 2.328306549295727688e-10
#define m1 4294967087.0
#define m2 4294944443.0
#define two53 9007199254740992.0
#define fact 5.9604644775390625e-8 /* 1 / 2^24 */
-
-
-
-/* Default initial seed of the package. Will be updated to become
- the seed of the next created stream. */
+/* Default initial seed of the package. Will be updated to become the seed of the next created stream. */
static double nextSeed[6] = { 12345, 12345, 12345, 12345, 12345, 12345 };
-
/* The following are the transition matrices of the two MRG components */
/* (in matrix form), raised to the powers -1, 1, 2^76, and 2^127, resp.*/
static double InvA1[3][3] = { /* Inverse of A1p0 */
{ 2824425944.0, 32183930.0, 2093834863.0 }
};
-
-
-
-
-/*-------------------------------------------------------------------------*/
-
static double MultModM (double a, double s, double c, double m)
/* Compute (a*s + c) % m. m must be < 2^35. Works also for s, c < 0 */
{
return v;
}
-
-/*-------------------------------------------------------------------------*/
-
static void MatVecModM (double A[3][3], double s[3], double v[3], double m)
/* Returns v = A*s % m. Assumes that -m < s[i] < m. */
/* Works even if v = s. */
v[i] = x[i];
}
-
-/*-------------------------------------------------------------------------*/
-
-static void MatMatModM (double A[3][3], double B[3][3], double C[3][3],
- double m)
+static void MatMatModM (double A[3][3], double B[3][3], double C[3][3], double m)
/* Returns C = A*B % m. Work even if A = C or B = C or A = B = C. */
{
int i, j;
}
}
-
-/*-------------------------------------------------------------------------*/
-
static void MatTwoPowModM (double A[3][3], double B[3][3], double m, long e)
/* Compute matrix B = (A^(2^e) % m); works even if A = B */
{
MatMatModM (B, B, B, m);
}
-
-/*-------------------------------------------------------------------------*/
-
static void MatPowModM (double A[3][3], double B[3][3], double m, long n)
/* Compute matrix B = A^n % m ; works even if A = B */
{
}
}
-
-/*-------------------------------------------------------------------------*/
-
static double U01 (RngStream g)
{
long k;
return (g->Anti) ? (1 - u) : u;
}
-
-/*-------------------------------------------------------------------------*/
-
static double U01d (RngStream g)
{
double u;
}
}
-
-/*-------------------------------------------------------------------------*/
-
static int CheckSeed (unsigned long seed[6])
{
- /* Check that the seeds are legitimate values. Returns 0 if legal seeds,
- -1 otherwise */
+ /* Check that the seeds are legitimate values. Returns 0 if legal seeds, -1 otherwise */
int i;
for (i = 0; i < 3; ++i) {
return 0;
}
-
/*---------------------------------------------------------------------*/
/* Public part. */
/*---------------------------------------------------------------------*/
-
RngStream RngStream_CreateStream (const char name[])
{
int i;
return g;
}
-/*-------------------------------------------------------------------------*/
-
void RngStream_DeleteStream (RngStream * p)
{
if (*p == NULL)
*p = NULL;
}
-/*-------------------------------------------------------------------------*/
-
RngStream RngStream_CopyStream (const RngStream src)
{
RngStream g;
return g;
}
-/*-------------------------------------------------------------------------*/
-
void RngStream_ResetStartStream (RngStream g)
{
int i;
g->Cg[i] = g->Bg[i] = g->Ig[i];
}
-/*-------------------------------------------------------------------------*/
-
void RngStream_ResetNextSubstream (RngStream g)
{
int i;
g->Cg[i] = g->Bg[i];
}
-/*-------------------------------------------------------------------------*/
-
void RngStream_ResetStartSubstream (RngStream g)
{
int i;
g->Cg[i] = g->Bg[i];
}
-/*-------------------------------------------------------------------------*/
-
int RngStream_SetPackageSeed (unsigned long seed[6])
{
int i;
return 0; /* SUCCESS */
}
-/*-------------------------------------------------------------------------*/
-
int RngStream_SetSeed (RngStream g, unsigned long seed[6])
{
int i;
return 0; /* SUCCESS */
}
-/*-------------------------------------------------------------------------*/
-
void RngStream_AdvanceState (RngStream g, long e, long c)
{
double B1[3][3], C1[3][3], B2[3][3], C2[3][3];
MatVecModM (C2, &g->Cg[3], &g->Cg[3], m2);
}
-/*-------------------------------------------------------------------------*/
-
void RngStream_GetState (RngStream g, unsigned long seed[6])
{
int i;
seed[i] = g->Cg[i];
}
-/*-------------------------------------------------------------------------*/
-
void RngStream_WriteState (RngStream g)
{
int i;
printf ("%lu }\n\n", (unsigned long) g->Cg[5]);
}
-/*-------------------------------------------------------------------------*/
-
void RngStream_WriteStateFull (RngStream g)
{
int i;
printf ("%lu }\n\n", (unsigned long) g->Cg[5]);
}
-/*-------------------------------------------------------------------------*/
-
void RngStream_IncreasedPrecis (RngStream g, int incp)
{
g->IncPrec = incp;
}
-/*-------------------------------------------------------------------------*/
-
void RngStream_SetAntithetic (RngStream g, int a)
{
g->Anti = a;
}
-/*-------------------------------------------------------------------------*/
-
double RngStream_RandU01 (RngStream g)
{
if (g->IncPrec)
return U01 (g);
}
-/*-------------------------------------------------------------------------*/
-
int RngStream_RandInt (RngStream g, int i, int j)
{
return i + (int) ((j - i + 1.0) * RngStream_RandU01 (g));
* */
int xbt_backtrace_no_malloc(void **array, int size) {
-
int i = 0;
for(i=0; i < size; i++)
array[i] = NULL;
}
}
-
void xbt_ex_setup_backtrace(xbt_ex_t * e) //FIXME: This code could be greatly improved/simplifyied with http://cairo.sourcearchive.com/documentation/1.9.4/backtrace-symbols_8c-source.html
{
int i;
binary_name = bprintf("%s/%s", data, xbt_binary_name);
if (!stat(binary_name, &stat_buf)) {
/* Found. */
- XBT_DEBUG("Looked in the PATH for the binary. Found %s",
- binary_name);
+ XBT_DEBUG("Looked in the PATH for the binary. Found %s", binary_name);
break;
}
}
e->used = 1;
e->bt_strings = xbt_new(char *, 1);
- e->bt_strings[0] =
- bprintf("(binary '%s' not found in the PATH)", xbt_binary_name);
+ e->bt_strings[0] = bprintf("(binary '%s' not found in the PATH)", xbt_binary_name);
free(backtrace_syms);
return;
}
} else {
binary_name = xbt_strdup(xbt_binary_name);
}
- cmd = curr =
- xbt_new(char,
- strlen(ADDR2LINE) + 25 + strlen(binary_name) + 32 * e->used);
+ cmd = curr = xbt_new(char, strlen(ADDR2LINE) + 25 + strlen(binary_name) + 32 * e->used);
curr += sprintf(curr, "%s -f -e %s ", ADDR2LINE, binary_name);
free(binary_name);
addr = strtol(addrs[i], &p, 16);
if (*p != '\0') {
- XBT_CRITICAL("Cannot parse backtrace address '%s' (addr=%#lx)",
- addrs[i], addr);
+ XBT_CRITICAL("Cannot parse backtrace address '%s' (addr=%#lx)", addrs[i], addr);
}
XBT_DEBUG("addr=%s (as string) =%#lx (as number)", addrs[i], addr);
}
if (found) {
XBT_DEBUG("%#lx in [%#lx-%#lx]", addr, first, last);
- XBT_DEBUG
- ("Symbol found, map lines not further displayed (even if looking for next ones)");
+ XBT_DEBUG("Symbol found, map lines not further displayed (even if looking for next ones)");
}
}
fclose(maps);
free(addrs[i]);
if (!found) {
- XBT_VERB
- ("Problem while reading the maps file. Following backtrace will be mangled.");
+ XBT_VERB("Problem while reading the maps file. Following backtrace will be mangled.");
XBT_DEBUG("No dynamic. Static symbol: %s", backtrace_syms[i]);
e->bt_strings[i] = bprintf("** In ?? (%s)", backtrace_syms[i]);
continue;
addrs[i] = bprintf("0x%0*lx", addr_len - 2, addr - offset);
XBT_DEBUG("offset=%#lx new addr=%s", offset, addrs[i]);
- /* Got it. We have our new address. Let's get the library path and we
- are set */
+ /* Got it. We have our new address. Let's get the library path and we are set */
p = xbt_strdup(backtrace_syms[i]);
if (p[0] == '[') {
/* library path not displayed in the map file either... */
/* check whether the trick worked */
if (strcmp("??", line_func)) {
XBT_DEBUG("Found dynamic symbol %s() at %s", line_func, line_pos);
- e->bt_strings[i] =
- bprintf("** In %s() at %s", line_func, line_pos);
+ e->bt_strings[i] = bprintf("** In %s() at %s", line_func, line_pos);
} else {
/* damn, nothing to do here. Let's print the raw address */
- XBT_DEBUG("Dynamic symbol not found. Raw address = %s",
- backtrace_syms[i]);
+ XBT_DEBUG("Dynamic symbol not found. Raw address = %s", backtrace_syms[i]);
e->bt_strings[i] = bprintf("** In ?? at %s", backtrace_syms[i]);
}
-
}
free(addrs[i]);
/* Mask the bottom of the stack */
if (!strncmp("main", line_func, strlen("main")) ||
- !strncmp("xbt_thread_context_wrapper", line_func,
- strlen("xbt_thread_context_wrapper"))
- || !strncmp("smx_ctx_sysv_wrapper", line_func,
- strlen("smx_ctx_sysv_wrapper"))) {
+ !strncmp("xbt_thread_context_wrapper", line_func, strlen("xbt_thread_context_wrapper"))
+ || !strncmp("smx_ctx_sysv_wrapper", line_func, strlen("smx_ctx_sysv_wrapper"))) {
int j;
for (j = i + 1; j < e->used; j++)
e->used = i + 1;
if (!strncmp
- ("xbt_thread_context_wrapper", line_func,
- strlen("xbt_thread_context_wrapper"))) {
+ ("xbt_thread_context_wrapper", line_func, strlen("xbt_thread_context_wrapper"))) {
free(e->bt_strings[i]);
e->bt_strings[i] = xbt_strdup("** (in a separate thread)");
}
}
-
-
}
pclose(pipe);
free(addrs);
#if HAVE_MC
int xbt_libunwind_backtrace(void* bt[XBT_BACKTRACE_SIZE], int size){
-
int i = 0;
for(i=0; i < size; i++)
bt[i] = NULL;
unw_getcontext (&uc);
unw_init_local (&c, &uc);
-
+
unw_word_t ip;
unw_step(&c);
-
- while(unw_step(&c) >= 0 && i < size){
+ while(unw_step(&c) >= 0 && i < size){
unw_get_reg(&c, UNW_REG_IP, &ip);
bt[i] = (void*)(long)ip;
i++;
-
}
return i;
-
}
-
#endif
/* xbt_cfgelm_t: the typedef corresponding to a config variable.
- Both data and DTD are mixed, but fixing it now would prevent me to ever
- defend my thesis. */
+ Both data and DTD are mixed, but fixing it now would prevent me to ever defend my thesis. */
typedef struct {
/* Description */
xbt_dynar_t content;
} s_xbt_cfgelm_t, *xbt_cfgelm_t;
-static const char *xbt_cfgelm_type_name[xbt_cfgelm_type_count] =
- { "int", "double", "string", "boolean", "any" };
+static const char *xbt_cfgelm_type_name[xbt_cfgelm_type_count] = { "int", "double", "string", "boolean", "any" };
const struct xbt_boolean_couple xbt_cfgelm_boolean_values[] = {
{ "yes", "no"},
static void xbt_cfgelm_free(void *data);
/* Retrieve the variable we'll modify */
-static xbt_cfgelm_t xbt_cfgelm_get(xbt_cfg_t cfg, const char *name,
- e_xbt_cfgelm_type_t type);
+static xbt_cfgelm_t xbt_cfgelm_get(xbt_cfg_t cfg, const char *name, e_xbt_cfgelm_type_t type);
/*----[ Memory management ]-----------------------------------------------*/
-
/** @brief Constructor
*
* Initialise a config set
*/
-
-
xbt_cfg_t xbt_cfg_new(void)
{
return (xbt_cfg_t) xbt_dict_new_homogeneous(&xbt_cfgelm_free);
*
* This only copy the registrations, not the actual content
*/
-
void xbt_cfg_cpy(xbt_cfg_t tocopy, xbt_cfg_t * whereto)
{
xbt_dict_cursor_t cursor = NULL;
xbt_assert(tocopy, "cannot copy NULL config");
xbt_dict_foreach((xbt_dict_t) tocopy, cursor, name, variable) {
- xbt_cfg_register(whereto, name, variable->desc, variable->type,
- variable->min, variable->max, variable->cb_set);
+ xbt_cfg_register(whereto, name, variable->desc, variable->type, variable->min, variable->max, variable->cb_set);
}
}
printf("%s %s:", indent, key);
size = xbt_dynar_length(variable->content);
- printf
- ("%d_to_%d_%s. Actual size=%d. postset=%p, List of values:\n",
- variable->min, variable->max, xbt_cfgelm_type_name[variable->type], size, variable->cb_set);
+ printf ("%d_to_%d_%s. Actual size=%d. postset=%p, List of values:\n",
+ variable->min, variable->max, xbt_cfgelm_type_name[variable->type], size, variable->cb_set);
switch (variable->type) {
-
case xbt_cfgelm_int:
for (i = 0; i < size; i++) {
ival = xbt_dynar_get_as(variable->content, i, int);
printf("%s %d\n", indent, ival);
}
break;
-
case xbt_cfgelm_double:
for (i = 0; i < size; i++) {
dval = xbt_dynar_get_as(variable->content, i, double);
printf("%s %f\n", indent, dval);
}
break;
-
case xbt_cfgelm_string:
for (i = 0; i < size; i++) {
sval = xbt_dynar_get_as(variable->content, i, char *);
printf("%s %s\n", indent, sval);
}
break;
-
case xbt_cfgelm_boolean:
for (i = 0; i < size; i++) {
ival = xbt_dynar_get_as(variable->content, i, int);
printf("%s %d\n", indent, ival);
}
break;
-
case xbt_cfgelm_alias:
/* no content */
break;
-
default:
printf("%s Invalid type!!\n", indent);
break;
}
-
}
if (name)
/*
* free an config element
*/
-
void xbt_cfgelm_free(void *data)
{
xbt_cfgelm_t c = (xbt_cfgelm_t) data;
}
/*----[ Registering stuff ]-----------------------------------------------*/
-
/** @brief Register an element within a config set
*
* @param cfg the config set
* @param max the maximum number of values for this config element
* @param cb_set callback function called when a value is set
*/
-
-void xbt_cfg_register(xbt_cfg_t * cfg,
- const char *name, const char *desc,
- e_xbt_cfgelm_type_t type, int min,
- int max, xbt_cfg_cb_t cb_set)
+void xbt_cfg_register(xbt_cfg_t * cfg, const char *name, const char *desc, e_xbt_cfgelm_type_t type, int min,
+ int max, xbt_cfg_cb_t cb_set)
{
xbt_cfgelm_t res;
case xbt_cfgelm_int:
res->content = xbt_dynar_new(sizeof(int), NULL);
break;
-
case xbt_cfgelm_double:
res->content = xbt_dynar_new(sizeof(double), NULL);
break;
-
case xbt_cfgelm_string:
res->content = xbt_dynar_new(sizeof(char *), xbt_free_ref);
break;
-
case xbt_cfgelm_boolean:
res->content = xbt_dynar_new(sizeof(int), NULL);
break;
-
default:
XBT_ERROR("%d is an invalid type code", (int)type);
break;
}
-
xbt_dict_set((xbt_dict_t) * cfg, name, res, NULL);
}
xbt_dict_set((xbt_dict_t) * cfg, oldname, res, NULL);
}
+
/** @brief Unregister an element from a config set.
*
* @param cfg the config set
* Note that it removes both the description and the actual content.
* Throws not_found when no such element exists.
*/
-
void xbt_cfg_unregister(xbt_cfg_t cfg, const char *name)
{
XBT_DEBUG("Unregister elm '%s' from set %p", name, cfg);
*
* Note that this does not allow to set the description, so you should prefer the other interface
*/
-
void xbt_cfg_register_str(xbt_cfg_t * cfg, const char *entry)
{
char *entrycpy = xbt_strdup(entry);
XBT_DEBUG("Register string '%s'", entry);
tok = strchr(entrycpy, ':');
- xbt_assert(tok, "Invalid config element descriptor: %s%s",
- entry, "; Should be <name>:<min nb>_to_<max nb>_<type>");
+ xbt_assert(tok, "Invalid config element descriptor: %s%s", entry, "; Should be <name>:<min nb>_to_<max nb>_<type>");
*(tok++) = '\0';
min = strtol(tok, &tok, 10);
- xbt_assert(tok, "Invalid minimum in config element descriptor %s",
- entry);
+ xbt_assert(tok, "Invalid minimum in config element descriptor %s", entry);
- xbt_assert(strcmp(tok, "_to_"),
- "Invalid config element descriptor : %s%s",
+ xbt_assert(strcmp(tok, "_to_"), "Invalid config element descriptor : %s%s",
entry, "; Should be <name>:<min nb>_to_<max nb>_<type>");
tok += strlen("_to_");
max = strtol(tok, &tok, 10);
- xbt_assert(tok, "Invalid maximum in config element descriptor %s",
- entry);
+ xbt_assert(tok, "Invalid maximum in config element descriptor %s", entry);
- xbt_assert(*tok == '_',
- "Invalid config element descriptor: %s%s", entry,
+ xbt_assert(*tok == '_', "Invalid config element descriptor: %s%s", entry,
"; Should be <name>:<min nb>_to_<max nb>_<type>");
tok++;
- for (type = (e_xbt_cfgelm_type_t)0;
- type < xbt_cfgelm_type_count
- && strcmp(tok, xbt_cfgelm_type_name[type]); type++);
- xbt_assert(type < xbt_cfgelm_type_count,
- "Invalid type in config element descriptor: %s%s", entry,
+ for (type = (e_xbt_cfgelm_type_t)0; type < xbt_cfgelm_type_count && strcmp(tok, xbt_cfgelm_type_name[type]); type++);
+ xbt_assert(type < xbt_cfgelm_type_count, "Invalid type in config element descriptor: %s%s", entry,
"; Should be one of 'string', 'int' or 'double'.");
xbt_cfg_register(cfg, entrycpy, NULL, type, min, max, NULL);
printf(" %s: %s\n", name, variable->desc);
}
}
+
/** @brief Displays the declared options and their description */
void xbt_cfg_help(xbt_cfg_t cfg)
{
case xbt_cfgelm_int:
printf("%d%s", xbt_dynar_get_as(variable->content, i, int), sep);
break;
-
case xbt_cfgelm_double:
printf("%f%s", xbt_dynar_get_as(variable->content, i, double), sep);
break;
-
case xbt_cfgelm_string:
printf("'%s'%s", xbt_dynar_get_as(variable->content, i, char *), sep);
break;
-
case xbt_cfgelm_boolean: {
int b = xbt_dynar_get_as(variable->content, i, int);
- const char *bs = b ? xbt_cfgelm_boolean_values[0].true_val
- : xbt_cfgelm_boolean_values[0].false_val;
+ const char *bs = b ? xbt_cfgelm_boolean_values[0].true_val: xbt_cfgelm_boolean_values[0].false_val;
if (b == 0 || b == 1)
printf("'%s'%s", bs, sep);
else
printf("'%s/%d'%s", bs, b, sep);
break;
}
-
default:
printf("Invalid type!!%s", sep);
}
}
}
-
xbt_dynar_free(&names);
}
size = xbt_dynar_length(variable->content);
if (variable->min > size) {
xbt_dict_cursor_free(&cursor);
- THROWF(mismatch_error, 0,
- "Config elem %s needs at least %d %s, but there is only %d values.",
- name, variable->min, xbt_cfgelm_type_name[variable->type],
- size);
+ THROWF(mismatch_error, 0, "Config elem %s needs at least %d %s, but there is only %d values.",
+ name, variable->min, xbt_cfgelm_type_name[variable->type], size);
}
if (variable->isdefault && size > variable->min) {
xbt_dict_cursor_free(&cursor);
- THROWF(mismatch_error, 0,
- "Config elem %s theoretically accepts %d %s, but has a default of %d values.",
+ THROWF(mismatch_error, 0, "Config elem %s theoretically accepts %d %s, but has a default of %d values.",
name, variable->min, xbt_cfgelm_type_name[variable->type], size);
}
if (variable->max > 0 && variable->max < size) {
xbt_dict_cursor_free(&cursor);
- THROWF(mismatch_error, 0,
- "Config elem %s accepts at most %d %s, but there is %d values.",
- name, variable->max, xbt_cfgelm_type_name[variable->type],
- size);
+ THROWF(mismatch_error, 0, "Config elem %s accepts at most %d %s, but there is %d values.",
+ name, variable->max, xbt_cfgelm_type_name[variable->type], size);
}
}
-
xbt_dict_cursor_free(&cursor);
}
xbt_assert(type == xbt_cfgelm_any || res->type == type,
"You tried to access to the config element %s as an %s, but its type is %s.",
- name,
- xbt_cfgelm_type_name[type], xbt_cfgelm_type_name[res->type]);
-
+ name, xbt_cfgelm_type_name[type], xbt_cfgelm_type_name[res->type]);
return res;
}
*
* @return the type of the given element
*/
-
e_xbt_cfgelm_type_t xbt_cfg_get_type(xbt_cfg_t cfg, const char *name)
{
-
xbt_cfgelm_t variable = NULL;
variable = xbt_dict_get_or_null((xbt_dict_t) cfg, name);
if (!variable)
- THROWF(not_found_error, 0,
- "Can't get the type of '%s' since this variable does not exist",
- name);
+ THROWF(not_found_error, 0, "Can't get the type of '%s' since this variable does not exist", name);
XBT_DEBUG("type in variable = %d", (int)variable->type);
-
return variable->type;
}
CATCH(e) {
if (e.category == not_found_error) {
xbt_ex_free(e);
- THROWF(not_found_error, 0,
- "Can't set the property '%s' since it's not registered",
- name);
+ THROWF(not_found_error, 0, "Can't set the property '%s' since it's not registered", name);
}
RETHROW;
}
str = va_arg(pa, char *);
xbt_cfg_set_string(cfg, name, str);
break;
-
case xbt_cfgelm_int:
i = va_arg(pa, int);
xbt_cfg_set_int(cfg, name, i);
break;
-
case xbt_cfgelm_double:
d = va_arg(pa, double);
xbt_cfg_set_double(cfg, name, d);
break;
-
case xbt_cfgelm_boolean:
str = va_arg(pa, char *);
xbt_cfg_set_boolean(cfg, name, str);
break;
-
default:
xbt_die("Config element variable %s not valid (type=%d)", name, (int)type);
}
* @param cfg config set to fill
* @param name variable name
* @param ... variable value
- *
*/
void xbt_cfg_set(xbt_cfg_t cfg, const char *name, ...)
{
/** @brief Add values parsed from a string into a config set
*
* @param cfg config set to fill
- * @param options a string containing the content to add to the config set. This
- * is a '\\t',' ' or '\\n' or ',' separated list of variables. Each individual variable is
- * like "[name]:[value]" where [name] is the name of an already registred
- * variable, and [value] conforms to the data type under which this variable was
- * registred.
+ * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
+ * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
+ * already registered variable, and [value] conforms to the data type under which this variable was registered.
*
* @todo This is a crude manual parser, it should be a proper lexer.
*/
-
void xbt_cfg_set_parse(xbt_cfg_t cfg, const char *options) {
-
char *optionlist_cpy;
char *option, *name, *val;
-
int len;
XBT_IN();
XBT_DEBUG("List to parse and set:'%s'", options);
option = optionlist_cpy;
while (1) { /* breaks in the code */
-
if (!option)
break;
name = option;
len = strlen(name);
- XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld",
- name, len, (long) (option - name));
+ XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
/* Pass the value */
- while (option - name <= (len - 1) && *option != ' ' && *option != '\n'
- && *option != '\t' && *option != ',') {
+ while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
XBT_DEBUG("Take %c.", *option);
option++;
}
if (option - name == len) {
XBT_DEBUG("Boundary=EOL");
option = NULL; /* don't do next iteration */
-
} else {
- XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld",
- *option, len, (long) (option - name));
-
+ XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
/* Pass the following blank chars */
*(option++) = '\0';
- while (option - name < (len - 1) &&
- (*option == ' ' || *option == '\n' || *option == '\t')) {
+ while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
/* fprintf(stderr,"Ignore a blank char.\n"); */
option++;
}
val = strchr(name, ':');
if (!val) {
/* don't free(optionlist_cpy) here, 'name' points inside it */
- xbt_die("Option '%s' badly formatted. Should be of the form 'name:value'",
- name);
+ xbt_die("Option '%s' badly formatted. Should be of the form 'name:value'", name);
}
*(val++) = '\0';
variable = NULL;
}
}
- }
- CATCH(e) {
+ } CATCH(e) {
if (e.category == not_found_error) {
xbt_ex_free(e);
THROWF(not_found_error, 0, "No registered variable corresponding to '%s'.", key);
case xbt_cfgelm_string:
xbt_cfg_set_string(cfg, key, value); /* throws */
break;
-
case xbt_cfgelm_int:
i = strtol(value, &ret, 0);
if (ret == value) {
xbt_die("Value of option %s not valid. Should be an integer", key);
}
-
xbt_cfg_set_int(cfg, key, i); /* throws */
break;
-
case xbt_cfgelm_double:
d = strtod(value, &ret);
if (ret == value) {
xbt_die("Value of option %s not valid. Should be a double", key);
}
-
xbt_cfg_set_double(cfg, key, d); /* throws */
break;
-
case xbt_cfgelm_boolean:
xbt_cfg_set_boolean(cfg, key, value); /* throws */
ret = (char *)value + strlen(value);
break;
-
default:
THROWF(unknown_error, 0, "Type of config element %s is not valid.", key);
break;
}
-
return ret;
}
if (variable->isdefault){
xbt_cfg_set_int(cfg, name, val);
variable->isdefault = 1;
- }
- else
- XBT_DEBUG
- ("Do not override configuration variable '%s' with value '%d' because it was already set.",
- name, val);
+ } else
+ XBT_DEBUG("Do not override configuration variable '%s' with value '%d' because it was already set.", name, val);
}
/** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
if (variable->isdefault) {
xbt_cfg_set_double(cfg, name, val);
variable->isdefault = 1;
- }
- else
- XBT_DEBUG
- ("Do not override configuration variable '%s' with value '%f' because it was already set.",
- name, val);
+ } else
+ XBT_DEBUG("Do not override configuration variable '%s' with value '%f' because it was already set.", name, val);
}
/** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
* This is useful to change the default value of a variable while allowing
* users to override it with command line arguments
*/
-void xbt_cfg_setdefault_string(xbt_cfg_t cfg, const char *name,
- const char *val)
+void xbt_cfg_setdefault_string(xbt_cfg_t cfg, const char *name, const char *val)
{
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_string);
if (variable->isdefault){
xbt_cfg_set_string(cfg, name, val);
variable->isdefault = 1;
- }
- else
- XBT_DEBUG
- ("Do not override configuration variable '%s' with value '%s' because it was already set.",
- name, val);
+ } else
+ XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.", name, val);
}
-
/** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
*
* This is useful to change the default value of a variable while allowing
variable->isdefault = 1;
}
else
- XBT_DEBUG
- ("Do not override configuration variable '%s' with value '%s' because it was already set.",
- name, val);
+ XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.", name, val);
}
/** @brief Set or add an integer value to \a name within \a cfg
*/
void xbt_cfg_set_int(xbt_cfg_t cfg, const char *name, int val)
{
-
XBT_VERB("Configuration setting: %s=%d", name, val);
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_int);
if (variable->max == 1) {
xbt_dynar_set(variable->content, 0, &val);
} else {
- if (variable->max
- && xbt_dynar_length(variable->content) ==
- (unsigned long) variable->max)
- THROWF(mismatch_error, 0,
- "Cannot add value %d to the config element %s since it's already full (size=%d)",
+ if (variable->max && xbt_dynar_length(variable->content) == (unsigned long) variable->max)
+ THROWF(mismatch_error, 0, "Cannot add value %d to the config element %s since it's already full (size=%d)",
val, name, variable->max);
xbt_dynar_push(variable->content, &val);
* @param name the name of the variable
* @param val the doule to set
*/
-
void xbt_cfg_set_double(xbt_cfg_t cfg, const char *name, double val)
{
-
XBT_VERB("Configuration setting: %s=%f", name, val);
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_double);
if (variable->max == 1) {
xbt_dynar_set(variable->content, 0, &val);
} else {
- if (variable->max
- && xbt_dynar_length(variable->content) == variable->max)
- THROWF(mismatch_error, 0,
- "Cannot add value %f to the config element %s since it's already full (size=%d)",
+ if (variable->max && xbt_dynar_length(variable->content) == variable->max)
+ THROWF(mismatch_error, 0, "Cannot add value %f to the config element %s since it's already full (size=%d)",
val, name, variable->max);
xbt_dynar_push(variable->content, &val);
* @param val the value to be added
*
*/
-
void xbt_cfg_set_string(xbt_cfg_t cfg, const char *name, const char *val)
{
char *newval = xbt_strdup(val);
} else {
if (variable->max
&& xbt_dynar_length(variable->content) == variable->max)
- THROWF(mismatch_error, 0,
- "Cannot add value %s to the config element %s since it's already full (size=%d)",
+ THROWF(mismatch_error, 0, "Cannot add value %s to the config element %s since it's already full (size=%d)",
name, val, variable->max);
xbt_dynar_push(variable->content, &newval);
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_boolean);
for (i = 0; xbt_cfgelm_boolean_values[i].true_val != NULL; i++) {
- if (strcmp(val, xbt_cfgelm_boolean_values[i].true_val) == 0){
- bval = 1;
- break;
- }
- if (strcmp(val, xbt_cfgelm_boolean_values[i].false_val) == 0){
- bval = 0;
- break;
- }
+ if (strcmp(val, xbt_cfgelm_boolean_values[i].true_val) == 0){
+ bval = 1;
+ break;
+ }
+ if (strcmp(val, xbt_cfgelm_boolean_values[i].false_val) == 0){
+ bval = 0;
+ break;
+ }
}
if (xbt_cfgelm_boolean_values[i].true_val == NULL) {
xbt_die("Value of option '%s' not valid. Should be a boolean (yes,no,on,off,true,false,0,1)", val);
if (variable->max == 1) {
xbt_dynar_set(variable->content, 0, &bval);
} else {
- if (variable->max
- && xbt_dynar_length(variable->content) ==
- (unsigned long) variable->max)
- THROWF(mismatch_error, 0,
- "Cannot add value %s to the config element %s since it's already full (size=%d)",
+ if (variable->max && xbt_dynar_length(variable->content) == (unsigned long) variable->max)
+ THROWF(mismatch_error, 0, "Cannot add value %s to the config element %s since it's already full (size=%d)",
val, name, variable->max);
xbt_dynar_push(variable->content, &bval);
}
/* ---- [ Removing ] ---- */
-
/** @brief Remove the provided \e val integer value from a variable
*
* @param cfg the config set
*/
void xbt_cfg_rm_int(xbt_cfg_t cfg, const char *name, int val)
{
-
unsigned int cpt;
int seen;
return;
}
}
-
- THROWF(not_found_error, 0,
- "Can't remove the value %d of config element %s: value not found.",
- val, name);
+ THROWF(not_found_error, 0, "Can't remove the value %d of config element %s: value not found.", val, name);
}
/** @brief Remove the provided \e val double value from a variable
* @param name the name of the variable
* @param val the value to be removed
*/
-
void xbt_cfg_rm_double(xbt_cfg_t cfg, const char *name, double val)
{
unsigned int cpt;
}
}
- THROWF(not_found_error, 0,
- "Can't remove the value %f of config element %s: value not found.",
- val, name);
+ THROWF(not_found_error, 0,"Can't remove the value %f of config element %s: value not found.", val, name);
}
/** @brief Remove the provided \e val string value from a variable
}
}
- THROWF(not_found_error, 0,
- "Can't remove the value %s of config element %s: value not found.",
- val, name);
+ THROWF(not_found_error, 0, "Can't remove the value %s of config element %s: value not found.", val, name);
}
/** @brief Remove the provided \e val boolean value from a variable
*/
void xbt_cfg_rm_boolean(xbt_cfg_t cfg, const char *name, int val)
{
-
unsigned int cpt;
int seen;
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_boolean);
}
}
- THROWF(not_found_error, 0,
- "Can't remove the value %d of config element %s: value not found.",
- val, name);
+ THROWF(not_found_error, 0, "Can't remove the value %d of config element %s: value not found.", val, name);
}
/** @brief Remove the \e pos th value from the provided variable */
-
void xbt_cfg_rm_at(xbt_cfg_t cfg, const char *name, int pos)
{
-
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_any);
if (xbt_dynar_length(variable->content) == variable->min)
* @param cfg the config set
* @param name the name of the variable
*/
-
void xbt_cfg_empty(xbt_cfg_t cfg, const char *name)
{
xbt_cfgelm_t variable = NULL;
TRY {
variable = xbt_dict_get((xbt_dict_t) cfg, name);
- }
- CATCH(e) {
+ } CATCH(e) {
if (e.category != not_found_error)
RETHROW;
if (variable)
xbt_dynar_reset(variable->content);
}
-/*
- * Say if the value is the default value
- */
+
+/* Say if the value is the default value */
int xbt_cfg_is_default_value(xbt_cfg_t cfg, const char *name)
{
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_any);
}
/*----[ Getting ]---------------------------------------------------------*/
-
/** @brief Retrieve an integer value of a variable (get a warning if not uniq)
*
* @param cfg the config set
* @param name the name of the variable
*
* Returns the first value from the config set under the given name.
- * If there is more than one value, it will issue a warning. Consider using
- * xbt_cfg_get_dynar() instead.
+ * If there is more than one value, it will issue a warning. Consider using xbt_cfg_get_dynar() instead.
*/
int xbt_cfg_get_int(xbt_cfg_t cfg, const char *name)
{
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_int);
if (xbt_dynar_length(variable->content) > 1) {
- XBT_WARN
- ("You asked for the first value of the config element '%s', but there is %lu values",
+ XBT_WARN("You asked for the first value of the config element '%s', but there is %lu values",
name, xbt_dynar_length(variable->content));
}
* @param name the name of the variable
*
* Returns the first value from the config set under the given name.
- * If there is more than one value, it will issue a warning. Consider using
- * xbt_cfg_get_dynar() instead.
+ * If there is more than one value, it will issue a warning. Consider using xbt_cfg_get_dynar() instead.
*/
-
double xbt_cfg_get_double(xbt_cfg_t cfg, const char *name)
{
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_double);
if (xbt_dynar_length(variable->content) > 1) {
- XBT_WARN
- ("You asked for the first value of the config element '%s', but there is %lu values\n",
+ XBT_WARN ("You asked for the first value of the config element '%s', but there is %lu values\n",
name, xbt_dynar_length(variable->content));
}
*
* \warning the returned value is the actual content of the config set
*/
-
char *xbt_cfg_get_string(xbt_cfg_t cfg, const char *name)
{
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_string);
if (xbt_dynar_length(variable->content) > 1) {
- XBT_WARN
- ("You asked for the first value of the config element '%s', but there is %lu values\n",
+ XBT_WARN("You asked for the first value of the config element '%s', but there is %lu values\n",
name, xbt_dynar_length(variable->content));
} else if (xbt_dynar_is_empty(variable->content)) {
return NULL;
* @param name the name of the variable
*
* Returns the first value from the config set under the given name.
- * If there is more than one value, it will issue a warning. Consider using
- * xbt_cfg_get_dynar() instead.
+ * If there is more than one value, it will issue a warning. Consider using xbt_cfg_get_dynar() instead.
*/
int xbt_cfg_get_boolean(xbt_cfg_t cfg, const char *name)
{
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_boolean);
if (xbt_dynar_length(variable->content) > 1) {
- XBT_WARN
- ("You asked for the first value of the config element '%s', but there is %lu values",
+ XBT_WARN("You asked for the first value of the config element '%s', but there is %lu values",
name, xbt_dynar_length(variable->content));
}
TRY {
variable = xbt_dict_get((xbt_dict_t) cfg, name);
- }
- CATCH(e) {
+ } CATCH(e) {
if (e.category == not_found_error) {
xbt_ex_free(e);
- THROWF(not_found_error, 0,
- "No registered variable %s in this config set", name);
+ THROWF(not_found_error, 0, "No registered variable %s in this config set", name);
}
RETHROW;
}
return variable->content;
}
-
/** @brief Retrieve one of the integer value of a variable */
int xbt_cfg_get_int_at(xbt_cfg_t cfg, const char *name, int pos)
{
-
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_int);
return xbt_dynar_get_as(variable->content, pos, int);
}
/** @brief Retrieve one of the double value of a variable */
double xbt_cfg_get_double_at(xbt_cfg_t cfg, const char *name, int pos)
{
-
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_double);
return xbt_dynar_get_as(variable->content, pos, double);
}
-
/** @brief Retrieve one of the string value of a variable */
char *xbt_cfg_get_string_at(xbt_cfg_t cfg, const char *name, int pos)
{
-
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_string);
return xbt_dynar_get_as(variable->content, pos, char *);
}
/** @brief Retrieve one of the boolean value of a variable */
int xbt_cfg_get_boolean_at(xbt_cfg_t cfg, const char *name, int pos)
{
-
xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_boolean);
return xbt_dynar_get_as(variable->content, pos, int);
}
-
#ifdef SIMGRID_TEST
#include "xbt.h"
#include "xbt/ex.h"
{
xbt_cfg_t set = make_set();
xbt_test_add("Alloc and free a config set");
- xbt_cfg_set_parse(set,
- "peername:veloce user:mquinson\nuser:oaumage\tuser:alegrand");
+ xbt_cfg_set_parse(set, "peername:veloce user:mquinson\nuser:oaumage\tuser:alegrand");
xbt_cfg_free(&set);
xbt_cfg_free(&set);
}
xbt_ex_t e;
xbt_test_add("Having too few elements for speed");
- xbt_cfg_set_parse(set,
- "peername:veloce user:mquinson\nuser:oaumage\tuser:alegrand");
+ xbt_cfg_set_parse(set, "peername:veloce user:mquinson\nuser:oaumage\tuser:alegrand");
TRY {
xbt_cfg_check(set);
- }
- CATCH(e) {
- if (e.category != mismatch_error ||
- strncmp(e.msg, "Config elem speed needs",
- strlen("Config elem speed needs")))
+ } CATCH(e) {
+ if (e.category != mismatch_error || strncmp(e.msg, "Config elem speed needs", strlen("Config elem speed needs")))
xbt_test_fail("Got an exception. msg=%s", e.msg);
xbt_ex_free(e);
}
xbt_cfg_free(&set);
xbt_cfg_free(&set);
-
-
xbt_test_add("Having too much values of 'speed'");
set = make_set();
xbt_cfg_set_parse(set, "peername:toto:42 user:alegrand");
TRY {
xbt_cfg_set_parse(set, "speed:42 speed:24 speed:34");
- }
- CATCH(e) {
+ } CATCH(e) {
if (e.category != mismatch_error ||
- strncmp(e.msg, "Cannot add value 34 to the config elem speed",
- strlen("Config elem speed needs")))
+ strncmp(e.msg, "Cannot add value 34 to the config elem speed", strlen("Config elem speed needs")))
xbt_test_fail("Got an exception. msg=%s", e.msg);
xbt_ex_free(e);
}
xbt_cfg_check(set);
xbt_cfg_free(&set);
xbt_cfg_free(&set);
-
}
XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
{
-
xbt_test_add("Get a single value");
{
/* get_single_value */
xbt_dynar_t dyn;
xbt_cfg_t myset = make_set();
- xbt_cfg_set_parse(myset,
- "peername:veloce user:foo\nuser:bar\tuser:toto");
+ xbt_cfg_set_parse(myset, "peername:veloce user:foo\nuser:bar\tuser:toto");
xbt_cfg_set_parse(myset, "speed:42");
xbt_cfg_check(myset);
dyn = xbt_cfg_get_dynar(myset, "user");
if (xbt_dynar_length(dyn) != 3)
- xbt_test_fail("Dynar length = %lu, I expected 3",
- xbt_dynar_length(dyn));
+ xbt_test_fail("Dynar length = %lu, I expected 3", xbt_dynar_length(dyn));
if (strcmp(xbt_dynar_get_as(dyn, 0, char *), "foo"))
- xbt_test_fail("Dynar[0] = %s, I expected foo",
- xbt_dynar_get_as(dyn, 0, char *));
+ xbt_test_fail("Dynar[0] = %s, I expected foo", xbt_dynar_get_as(dyn, 0, char *));
if (strcmp(xbt_dynar_get_as(dyn, 1, char *), "bar"))
- xbt_test_fail("Dynar[1] = %s, I expected bar",
- xbt_dynar_get_as(dyn, 1, char *));
+ xbt_test_fail("Dynar[1] = %s, I expected bar", xbt_dynar_get_as(dyn, 1, char *));
if (strcmp(xbt_dynar_get_as(dyn, 2, char *), "toto"))
- xbt_test_fail("Dynar[2] = %s, I expected toto",
- xbt_dynar_get_as(dyn, 2, char *));
+ xbt_test_fail("Dynar[2] = %s, I expected toto", xbt_dynar_get_as(dyn, 2, char *));
xbt_cfg_free(&myset);
}
TRY {
xbt_cfg_set_parse(myset, "color:blue");
- }
- CATCH(e) {
+ } CATCH(e) {
if (e.category != not_found_error)
xbt_test_exception(e);
xbt_ex_free(e);
/* Context */
xbt_test_unit_t _xbt_test_current_unit = NULL;
-
/* test suite test log */
typedef struct s_xbt_test_log {
char *text;
static void xbt_test_log_dump(xbt_test_log_t log)
{
if (log)
- fprintf(stderr, " log %p(%s:%d)=%s\n", log, log->file, log->line,
- log->text);
+ fprintf(stderr, " log %p(%s:%d)=%s\n", log, log->file, log->line, log->text);
else
fprintf(stderr, " log=NULL\n");
}
if (test) {
xbt_test_log_t log;
unsigned int it_log;
- fprintf(stderr, " test %p(%s:%d)=%s (%s)\n",
- test, test->file, test->line, test->title,
+ fprintf(stderr, " test %p(%s:%d)=%s (%s)\n", test, test->file, test->line, test->title,
test->failed ? "failed" : "not failed");
xbt_dynar_foreach(test->logs, it_log, log)
xbt_test_log_dump(log);
if (unit) {
xbt_test_test_t test;
unsigned int it_test;
- fprintf(stderr, " UNIT %s: %s (%s)\n",
- unit->name, unit->title,
- (unit->enabled ? "enabled" : "disabled"));
+ fprintf(stderr, " UNIT %s: %s (%s)\n", unit->name, unit->title, (unit->enabled ? "enabled" : "disabled"));
if (unit->enabled)
xbt_dynar_foreach(unit->tests, it_test, test)
xbt_test_test_dump(test);
va_list ap;
if (!_xbt_test_suites)
- _xbt_test_suites =
- xbt_dynar_new(sizeof(xbt_test_suite_t), xbt_test_suite_free);
+ _xbt_test_suites = xbt_dynar_new(sizeof(xbt_test_suite_t), xbt_test_suite_free);
va_start(ap, fmt);
suite->title = bvprintf(fmt, ap);
- suite->units =
- xbt_dynar_new(sizeof(xbt_test_unit_t), &xbt_test_unit_free);
+ suite->units = xbt_dynar_new(sizeof(xbt_test_unit_t), &xbt_test_unit_free);
va_end(ap);
suite->name = name;
suite->enabled = 1;
}
/** @brief retrieve a testsuite from name, or create a new one */
-xbt_test_suite_t xbt_test_suite_by_name(const char *name, const char *fmt,
- ...)
+xbt_test_suite_t xbt_test_suite_by_name(const char *name, const char *fmt, ...)
{
xbt_test_suite_t suite;
unsigned int it_suite;
if (suite) {
xbt_test_unit_t unit;
unsigned int it_unit;
- fprintf(stderr, "TESTSUITE %s: %s (%s)\n",
- suite->name, suite->title,
- suite->enabled ? "enabled" : "disabled");
+ fprintf(stderr, "TESTSUITE %s: %s (%s)\n", suite->name, suite->title, suite->enabled ? "enabled" : "disabled");
if (suite->enabled)
xbt_dynar_foreach(suite->units, it_unit, unit)
xbt_test_unit_dump(unit);
}
/* add test case to test suite */
-void xbt_test_suite_push(xbt_test_suite_t suite, const char *name,
- ts_test_cb_t func, const char *fmt, ...)
+void xbt_test_suite_push(xbt_test_suite_t suite, const char *name, ts_test_cb_t func, const char *fmt, ...)
{
xbt_test_unit_t unit;
va_list ap;
int suite_len = strlen(suite->title);
int i;
- xbt_assert(suite_len < 68,
- "suite title \"%s\" too long (%d should be less than 68",
- suite->title, suite_len);
+ xbt_assert(suite_len < 68, "suite title \"%s\" too long (%d should be less than 68", suite->title, suite_len);
suite_title[0] = ' ';
for (i = 1; i < 80; i++)
suite_title[i++] = '\n';
suite_title[80] = '\0';
- sprintf(suite_title + 40 - (suite_len + 4) / 2, "[ %s ]",
- suite->title);
+ sprintf(suite_title + 40 - (suite_len + 4) / 2, "[ %s ]", suite->title);
suite_title[40 + (suite_len + 5) / 2] = '=';
if (!suite->enabled)
snprintf(suite_title + 70, 11, " DISABLED ");
unit->test_expect++;
}
}
-
-
/* Display whether this unit went well */
- if (unit->test_failed > 0 || unit->test_expect ||
- (verbosity && unit->nb_tests > 0)) {
+ if (unit->test_failed > 0 || unit->test_expect || (verbosity && unit->nb_tests > 0)) {
/* some tests failed (or were supposed to), so do detailed reporting of test case */
if (unit->test_failed > 0) {
fprintf(stderr, ".. failed\n");
xbt_dynar_foreach(unit->tests, it_test, test) {
file = (test->file != NULL ? test->file : unit->file);
line = (test->line != 0 ? test->line : unit->line);
- fprintf(stderr, " %s: %s [%s:%d]\n",
- (test->ignored ? " SKIP"
- : (test->expected_failure
- ? (test->
- failed ? "EFAIL" : "EPASS") : (test->failed ?
- " FAIL" :
- " PASS"))),
- test->title, file, line);
-
- if ((test->expected_failure && !test->failed)
- || (!test->expected_failure && test->failed)) {
+ fprintf(stderr, " %s: %s [%s:%d]\n", (test->ignored ? " SKIP" : (test->expected_failure
+ ? (test-> failed ? "EFAIL" : "EPASS") : (test->failed ? " FAIL" : " PASS"))),test->title, file, line);
+
+ if ((test->expected_failure && !test->failed) || (!test->expected_failure && test->failed)) {
xbt_dynar_foreach(test->logs, it_log, log) {
file = (log->file != NULL ? log->file : file);
line = (log->line != 0 ? log->line : line);
- fprintf(stderr, " %s:%d: %s\n",
- file, line, log->text);
-
+ fprintf(stderr, " %s:%d: %s\n", file, line, log->text);
}
}
}
- fprintf(stderr, " Summary: %d of %d tests failed",
- unit->test_failed, unit->nb_tests);
+ fprintf(stderr, " Summary: %d of %d tests failed", unit->test_failed, unit->nb_tests);
if (unit->test_ignore) {
fprintf(stderr, " (%d tests ignored)\n", unit->test_ignore);
} else {
fprintf(stderr, "\n");
}
-
} else if (!unit->enabled) {
fprintf(stderr, " disabled\n"); /* no test were run */
} else if (unit->nb_tests) {
_xbt_test_suite_ignore++;
}
-
/* print test suite summary */
if (suite->enabled) {
-
- fprintf(stderr,
- " =====================================================================%s\n",
- (suite->nb_units
- ? (suite->unit_failed ? "== FAILED" : "====== OK")
- : (suite->unit_disabled ? " DISABLED" : "==== SKIP")));
- fprintf(stderr, " Summary: Units: %.0f%% ok (%d units: ",
- suite->nb_units
- ? ((1 -
- (double) suite->unit_failed / (double) suite->nb_units) *
- 100.0) : 100.0, suite->nb_units);
+ fprintf(stderr," =====================================================================%s\n",
+ (suite->nb_units ? (suite->unit_failed ? "== FAILED" : "====== OK") :
+ (suite->unit_disabled ? " DISABLED" : "==== SKIP")));
+ fprintf(stderr, " Summary: Units: %.0f%% ok (%d units: ", suite->nb_units
+ ? ((1 - (double) suite->unit_failed / (double) suite->nb_units) * 100.0) : 100.0, suite->nb_units);
if (suite->nb_units != suite->unit_failed) {
- fprintf(stderr, "%s%d ok", (first ? "" : ", "),
- suite->nb_units - suite->unit_failed);
+ fprintf(stderr, "%s%d ok", (first ? "" : ", "), suite->nb_units - suite->unit_failed);
first = 0;
}
if (suite->unit_failed) {
- fprintf(stderr, "%s%d failed", (first ? "" : ", "),
- suite->unit_failed);
+ fprintf(stderr, "%s%d failed", (first ? "" : ", "), suite->unit_failed);
first = 0;
}
if (suite->unit_ignore) {
- fprintf(stderr, "%s%d ignored", (first ? "" : ", "),
- suite->unit_ignore);
+ fprintf(stderr, "%s%d ignored", (first ? "" : ", "), suite->unit_ignore);
first = 0;
}
if (suite->unit_disabled) {
- fprintf(stderr, "%s%d disabled", (first ? "" : ", "),
- suite->unit_disabled);
+ fprintf(stderr, "%s%d disabled", (first ? "" : ", "), suite->unit_disabled);
}
- fprintf(stderr, ")\n Tests: %.0f%% ok (%d tests: ",
- suite->nb_tests
- ? ((1 -
- (double) suite->test_failed / (double) suite->nb_tests) *
- 100.0) : 100.0, suite->nb_tests);
+ fprintf(stderr, ")\n Tests: %.0f%% ok (%d tests: ", suite->nb_tests
+ ? ((1 - (double) suite->test_failed / (double) suite->nb_tests) * 100.0) : 100.0, suite->nb_tests);
first = 1;
if (suite->nb_tests != suite->test_failed) {
- fprintf(stderr, "%s%d ok", (first ? "" : ", "),
- suite->nb_tests - suite->test_failed);
+ fprintf(stderr, "%s%d ok", (first ? "" : ", "), suite->nb_tests - suite->test_failed);
first = 0;
}
if (suite->test_failed) {
- fprintf(stderr, "%s%d failed", (first ? "" : ", "),
- suite->test_failed);
+ fprintf(stderr, "%s%d failed", (first ? "" : ", "), suite->test_failed);
first = 0;
}
if (suite->test_ignore) {
- fprintf(stderr, "%s%d ignored", (first ? "" : "; "),
- suite->test_ignore);
+ fprintf(stderr, "%s%d ignored", (first ? "" : "; "), suite->test_ignore);
first = 0;
}
if (suite->test_expect) {
- fprintf(stderr, "%s%d expected to fail", (first ? "" : "; "),
- suite->test_expect);
+ fprintf(stderr, "%s%d expected to fail", (first ? "" : "; "), suite->test_expect);
}
fprintf(stderr, ")\n");
}
break; /* found the relevant serie. We are happy */
}
} /* search relevant series */
- xbt_assert(it != xbt_dynar_length(_xbt_test_suites), "No suite of name '%s' found. Cannot apply the selection\n", suitename);
+ xbt_assert(it != xbt_dynar_length(_xbt_test_suites),
+ "No suite of name '%s' found. Cannot apply the selection\n", suitename);
}
-
}
}
xbt_test_suite_run(suite, verbosity);
/* Display some more statistics */
- fprintf(stderr, "\n\n TOTAL: Suites: %.0f%% ok (%d suites: ",
- _xbt_test_nb_suites
- ? ((1 -
- (double) _xbt_test_suite_failed /
- (double) _xbt_test_nb_suites) * 100.0)
+ fprintf(stderr, "\n\n TOTAL: Suites: %.0f%% ok (%d suites: ",_xbt_test_nb_suites
+ ? ((1 - (double) _xbt_test_suite_failed / (double) _xbt_test_nb_suites) * 100.0)
: 100.0, _xbt_test_nb_suites);
if (_xbt_test_nb_suites != _xbt_test_suite_failed) {
fprintf(stderr, "%d ok", _xbt_test_nb_suites - _xbt_test_suite_failed);
if (_xbt_test_suite_ignore) {
fprintf(stderr, "%s%d ignored", (first ? "" : ", "), _xbt_test_suite_ignore);
}
- fprintf(stderr, ")\n Units: %.0f%% ok (%d units: ",
- _xbt_test_nb_units
- ? ((1 -
- (double) _xbt_test_unit_failed /
- (double) _xbt_test_nb_units) * 100.0) : 100.0,
- _xbt_test_nb_units);
+ fprintf(stderr, ")\n Units: %.0f%% ok (%d units: ", _xbt_test_nb_units
+ ? ((1 - (double) _xbt_test_unit_failed / (double) _xbt_test_nb_units) * 100.0) : 100.0, _xbt_test_nb_units);
first = 1;
if (_xbt_test_nb_units != _xbt_test_unit_failed) {
fprintf(stderr, "%s%d ok", (first ? "" : ", "), _xbt_test_nb_units - _xbt_test_unit_failed);
if (_xbt_test_unit_ignore) {
fprintf(stderr, "%s%d ignored", (first ? "" : ", "), _xbt_test_unit_ignore);
}
- fprintf(stderr, ")\n Tests: %.0f%% ok (%d tests: ",
- _xbt_test_nb_tests
- ? ((1 -
- (double) _xbt_test_test_failed /
- (double) _xbt_test_nb_tests) * 100.0) : 100.0,
- _xbt_test_nb_tests);
+ fprintf(stderr, ")\n Tests: %.0f%% ok (%d tests: ", _xbt_test_nb_tests
+ ? ((1 - (double) _xbt_test_test_failed / (double) _xbt_test_nb_tests) * 100.0) : 100.0, _xbt_test_nb_tests);
first = 1;
if (_xbt_test_nb_tests != _xbt_test_test_failed) {
fprintf(stderr, "%s%d ok", (first ? "" : ", "), _xbt_test_nb_tests - _xbt_test_test_failed);
xbt_dynar_push(test->logs, &log);
}
-
#ifdef SIMGRID_TEST
-
XBT_TEST_SUITE("cunit", "Testsuite mechanism autotest");
XBT_TEST_UNIT("expect", test_expected_failure, "expected failures")
xbt_test_log("%s %s", "Test", "log");
xbt_test_fail("EXPECTED FAILURE");
}
-
#endif /* SIMGRID_TEST */
#include "xbt/str.h"
#include "dict_private.h"
-XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict, xbt,
- "Dictionaries provide the same functionalities as hash tables");
+XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict, xbt, "Dictionaries provide the same functionalities as hash tables");
/**
* \brief Constructor
* \see xbt_dict_new_homogenous(), xbt_dict_free()
*
* Creates and initialize a new dictionary with a default hashtable size.
- * The dictionary is heterogeneous: each element can have a different free
- * function.
+ * The dictionary is heterogeneous: each element can have a different free function.
*/
xbt_dict_t xbt_dict_new(void)
{
/**
* \brief Constructor
- * \param free_ctn function to call with (\a data as argument) when
- * \a data is removed from the dictionary
+ * \param free_ctn function to call with (\a data as argument) when \a data is removed from the dictionary
* \return pointer to the destination
* \see xbt_dict_new(), xbt_dict_free()
*
}
}
-/**
- * Returns the amount of elements in the dict
- */
+/** Returns the amount of elements in the dict */
inline unsigned int xbt_dict_size(xbt_dict_t dict)
{
return (dict ? (unsigned int) dict->count : (unsigned int) 0);
xbt_dictelm_t bucklet;
xbt_dictelm_t *pprev;
- currcell =
- (xbt_dictelm_t *) xbt_realloc((char *) dict->table,
- newsize * sizeof(xbt_dictelm_t));
+ currcell = (xbt_dictelm_t *) xbt_realloc((char *) dict->table, newsize * sizeof(xbt_dictelm_t));
memset(&currcell[oldsize], 0, oldsize * sizeof(xbt_dictelm_t)); /* zero second half */
dict->table_size = --newsize;
dict->table = currcell;
continue;
twincell = currcell + oldsize;
for (pprev = currcell, bucklet = *currcell; bucklet; bucklet = *pprev) {
- /* Since we use "& size" instead of "%size" and since the size was doubled,
- each bucklet of this cell must either :
+ /* Since we use "& size" instead of "%size" and since the size was doubled, each bucklet of this cell must either:
- stay in cell i (ie, currcell)
- go to the cell i+oldsize (ie, twincell) */
if ((bucklet->hash_code & newsize) != i) { /* Move to b */
} else {
pprev = &bucklet->next;
}
-
}
if (!*currcell) /* everything moved */
* \param key the key to set the new data
* \param key_len the size of the \a key
* \param data the data to add in the dict
- * \param free_ctn function to call with (\a data as argument) when
- * \a data is removed from the dictionary. This param
- * will only be considered when the dict was instantiated with
- * xbt_dict_new() and not xbt_dict_new_homogeneous()
+ * \param free_ctn function to call with (\a data as argument) when \a data is removed from the dictionary. This param
+ * will only be considered when the dict was instantiated with xbt_dict_new() and not xbt_dict_new_homogeneous()
*
- * Set the \a data in the structure under the \a key, which can be any kind
- * of data, as long as its length is provided in \a key_len.
+ * Set the \a data in the structure under the \a key, which can be any kind of data, as long as its length is provided
+ * in \a key_len.
*/
-inline void xbt_dict_set_ext(xbt_dict_t dict,
- const char *key, int key_len,
- void *data, void_f_pvoid_t free_ctn)
+inline void xbt_dict_set_ext(xbt_dict_t dict, const char *key, int key_len, void *data, void_f_pvoid_t free_ctn)
{
-
unsigned int hash_code = xbt_str_hash_ext(key, key_len);
xbt_dictelm_t current, previous = NULL;
- XBT_CDEBUG(xbt_dict,
- "ADD %.*s hash = %u, size = %d, & = %u", key_len, key, hash_code,
+ XBT_CDEBUG(xbt_dict, "ADD %.*s hash = %u, size = %d, & = %u", key_len, key, hash_code,
dict->table_size, hash_code & dict->table_size);
current = dict->table[hash_code & dict->table_size];
- while (current != NULL &&
- (hash_code != current->hash_code || key_len != current->key_len
+ while (current != NULL && (hash_code != current->hash_code || key_len != current->key_len
|| memcmp(key, current->key, key_len))) {
previous = current;
current = current->next;
}
} else {
XBT_CDEBUG(xbt_dict, "Replace %.*s by %.*s under key %.*s",
- key_len, (char *) current->content,
- key_len, (char *) data, key_len, (char *) key);
+ key_len, (char *) current->content, key_len, (char *) data, key_len, (char *) key);
/* there is already an element with the same key: overwrite it */
xbt_dictelm_set_data(dict, current, data, free_ctn);
}
* \param dict the dict
* \param key the key to set the new data
* \param data the data to add in the dict
- * \param free_ctn function to call with (\a data as argument) when
- * \a data is removed from the dictionary. This param
- * will only be considered when the dict was instantiated with
- * xbt_dict_new() and not xbt_dict_new_homogeneous()
+ * \param free_ctn function to call with (\a data as argument) when \a data is removed from the dictionary. This param
+ * will only be considered when the dict was instantiated with xbt_dict_new() and not xbt_dict_new_homogeneous()
*
- * set the \a data in the structure under the \a key, which is a
- * null terminated string.
+ * set the \a data in the structure under the \a key, which is anull terminated string.
*/
-inline void xbt_dict_set(xbt_dict_t dict,
- const char *key, void *data,
- void_f_pvoid_t free_ctn)
+inline void xbt_dict_set(xbt_dict_t dict, const char *key, void *data, void_f_pvoid_t free_ctn)
{
-
xbt_dict_set_ext(dict, key, strlen(key), data, free_ctn);
}
unsigned int hash_code = xbt_str_hash_ext(key, key_len);
xbt_dictelm_t current = dict->table[hash_code & dict->table_size];
- while (current != NULL &&
- (hash_code != current->hash_code || key_len != current->key_len
+ while (current != NULL && (hash_code != current->hash_code || key_len != current->key_len
|| memcmp(key, current->key, key_len))) {
current = current->next;
}
unsigned int hash_code = xbt_str_hash_ext(key, key_len);
xbt_dictelm_t current = dict->table[hash_code & dict->table_size];
- while (current != NULL &&
- (hash_code != current->hash_code || key_len != current->key_len
+ while (current != NULL && (hash_code != current->hash_code || key_len != current->key_len
|| memcmp(key, current->key, key_len))) {
current = current->next;
}
current = current->next;
}
}
-
return NULL;
}
* \return the data that we are looking for
*
* Search the given \a key. Throws not_found_error when not found.
- * Check xbt_dict_get_or_null() for a version returning NULL without exception when
- * not found.
+ * Check xbt_dict_get_or_null() for a version returning NULL without exception when not found.
*/
inline void *xbt_dict_get(xbt_dict_t dict, const char *key)
{
return xbt_dict_get_elm(dict, key)->content;
}
+
/**
* \brief Retrieve element from the dict (null-terminated key)
*
* \return the s_xbt_dictelm_t that we are looking for
*
* Search the given \a key. Throws not_found_error when not found.
- * Check xbt_dict_get_or_null() for a version returning NULL without exception when
- * not found.
+ * Check xbt_dict_get_or_null() for a version returning NULL without exception when not found.
*/
inline xbt_dictelm_t xbt_dict_get_elm(xbt_dict_t dict, const char *key)
{
return current->content;
}
+
/**
* \brief like xbt_dict_get_elm(), but returning NULL when not found
*/
unsigned int hash_code = xbt_str_hash(key);
xbt_dictelm_t current = dict->table[hash_code & dict->table_size];
- while (current != NULL &&
- (hash_code != current->hash_code || strcmp(key, current->key)))
+ while (current != NULL && (hash_code != current->hash_code || strcmp(key, current->key)))
current = current->next;
return current;
}
-
/**
* \brief Remove data from the dict (arbitrary key)
*
xbt_dictelm_t previous = NULL;
xbt_dictelm_t current = dict->table[hash_code & dict->table_size];
- while (current != NULL &&
- (hash_code != current->hash_code || key_len != current->key_len
+ while (current != NULL && (hash_code != current->hash_code || key_len != current->key_len
|| strncmp(key, current->key, key_len))) {
previous = current; /* save the previous node */
current = current->next;
dict->count--;
}
-
-
/**
* \brief Remove data from the dict (null-terminated key)
*
* \param dict the exibitionist
* \param output a function to dump each data in the tree (check @ref xbt_dict_dump_output_string)
*
- * Outputs the content of the structure. (for debugging purpose). \a output is a
- * function to output the data. If NULL, data won't be displayed.
+ * Outputs the content of the structure. (for debugging purpose). \a output is a function to output the data. If NULL,
+ * data won't be displayed.
*/
-
void xbt_dict_dump(xbt_dict_t dict, void_f_pvoid_t output)
{
int i;
*/
void xbt_dict_preinit(void)
{
- dict_elm_mallocator = xbt_mallocator_new(256,
- dict_elm_mallocator_new_f,
- dict_elm_mallocator_free_f,
+ dict_elm_mallocator = xbt_mallocator_new(256, dict_elm_mallocator_new_f, dict_elm_mallocator_free_f,
dict_elm_mallocator_reset_f);
- dict_het_elm_mallocator = xbt_mallocator_new(256,
- dict_het_elm_mallocator_new_f,
- dict_het_elm_mallocator_free_f,
+ dict_het_elm_mallocator = xbt_mallocator_new(256, dict_het_elm_mallocator_new_f, dict_het_elm_mallocator_free_f,
dict_het_elm_mallocator_reset_f);
}
#include "xbt/ex.h"
#include "src/internal_config.h"
-
XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_dict);
XBT_TEST_SUITE("dict", "Dict data container");
-static void debuged_add_ext(xbt_dict_t head, const char *key,
- const char *data_to_fill, void_f_pvoid_t free_f)
+static void debuged_add_ext(xbt_dict_t head, const char *key, const char *data_to_fill, void_f_pvoid_t free_f)
{
char *data = xbt_strdup(data_to_fill);
debuged_add(*head, "123457", free_f);
}
-
static void search_ext(xbt_dict_t head, const char *key, const char *data)
{
char *found;
found = xbt_dict_get(head, key);
xbt_test_log("Found %s", found);
if (data) {
- xbt_test_assert(found,
- "data do not match expectations: found NULL while searching for %s",
- data);
+ xbt_test_assert(found, "data do not match expectations: found NULL while searching for %s", data);
if (found)
- xbt_test_assert(!strcmp(data, found),
- "data do not match expectations: found %s while searching for %s",
+ xbt_test_assert(!strcmp(data, found), "data do not match expectations: found %s while searching for %s",
found, data);
} else {
- xbt_test_assert(!found,
- "data do not match expectations: found %s while searching for NULL",
- found);
+ xbt_test_assert(!found, "data do not match expectations: found %s while searching for NULL", found);
}
}
static void debuged_remove(xbt_dict_t head, const char *key)
{
-
xbt_test_add("Remove '%s'", key);
xbt_dict_remove(head, key);
/* xbt_dict_dump(head,(void (*)(void*))&printf); */
}
-
static void traverse(xbt_dict_t head)
{
xbt_dict_cursor_t cursor = NULL;
} else {
xbt_test_log("Seen #%d: %s", ++i, key);
}
- xbt_test_assert(!data || !strcmp(key, data),
- "Key(%s) != value(%s). Aborting", key, data);
+ xbt_test_assert(!data || !strcmp(key, data), "Key(%s) != value(%s). Aborting", key, data);
}
}
TRY {
data = xbt_dict_get(head, data);
- THROWF(unknown_error, 0,
- "Found something which shouldn't be there (%s)", data);
- }
- CATCH(e) {
+ THROWF(unknown_error, 0, "Found something which shouldn't be there (%s)", data);
+ } CATCH(e) {
if (e.category != not_found_error)
xbt_test_exception(e);
xbt_ex_free(e);
void *data;
int effective = 0;
-
xbt_test_add("Count elements (expecting %d)", length);
- xbt_test_assert(xbt_dict_length(dict) == length,
- "Announced length(%d) != %d.", xbt_dict_length(dict),
- length);
+ xbt_test_assert(xbt_dict_length(dict) == length, "Announced length(%d) != %d.", xbt_dict_length(dict), length);
xbt_dict_foreach(dict, cursor, key, data)
effective++;
- xbt_test_assert(effective == length, "Effective length(%d) != %d.",
- effective, length);
-
+ xbt_test_assert(effective == length, "Effective length(%d) != %d.", effective, length);
}
static void count_check_get_key(xbt_dict_t dict, int length)
void *data;
int effective = 0;
-
- xbt_test_add
- ("Count elements (expecting %d), and test the getkey function",
- length);
- xbt_test_assert(xbt_dict_length(dict) == length,
- "Announced length(%d) != %d.", xbt_dict_length(dict),
- length);
+ xbt_test_add("Count elements (expecting %d), and test the getkey function", length);
+ xbt_test_assert(xbt_dict_length(dict) == length, "Announced length(%d) != %d.", xbt_dict_length(dict), length);
xbt_dict_foreach(dict, cursor, key, data) {
effective++;
key2 = xbt_dict_get_key(dict, data);
- xbt_assert(!strcmp(key, key2),
- "The data was registered under %s instead of %s as expected",
- key2, key);
+ xbt_assert(!strcmp(key, key2), "The data was registered under %s instead of %s as expected", key2, key);
}
- xbt_test_assert(effective == length, "Effective length(%d) != %d.",
- effective, length);
-
+ xbt_test_assert(effective == length, "Effective length(%d) != %d.", effective, length);
}
xbt_ex_t e;
traverse(head);
TRY {
debuged_remove(head, "12346");
- }
- CATCH(e) {
+ } CATCH(e) {
if (e.category != not_found_error)
xbt_test_exception(e);
xbt_ex_free(e);
xbt_test_add("Remove non existing data");
TRY {
debuged_remove(head, "Does not exist");
- }
- CATCH(e) {
+ } CATCH(e) {
if (e.category != not_found_error)
xbt_test_exception(e);
xbt_ex_free(e);
xbt_dict_free(&head);
- xbt_test_add
- ("Remove each data manually (traversing the resulting dictionary each time)");
+ xbt_test_add("Remove each data manually (traversing the resulting dictionary each time)");
fill(&head, homogeneous);
debuged_remove(head, "12a");
traverse(head);
count(head, 3);
TRY {
debuged_remove(head, "12346");
- }
- CATCH(e) {
+ } CATCH(e) {
if (e.category != not_found_error)
xbt_test_exception(e);
xbt_ex_free(e);
traverse(head);
TRY {
debuged_remove(head, "12346");
- }
- CATCH(e) {
+ } CATCH(e) {
if (e.category != not_found_error)
xbt_test_exception(e);
xbt_ex_free(e);
}
traverse(head);
- xbt_test_add
- ("Free dict, create new fresh one, and then reset the dict");
+ xbt_test_add("Free dict, create new fresh one, and then reset the dict");
xbt_dict_free(&head);
fill(&head, homogeneous);
xbt_dict_reset(head);
if (!strcmp(key, "null"))
found = 1;
}
- xbt_test_assert(found,
- "the key 'null', associated to NULL is not found");
+ xbt_test_assert(found, "the key 'null', associated to NULL is not found");
}
xbt_dict_free(&head);
}
for (i = 0; i < 10; i++) {
xbt_test_add("CRASH test number %d (%d to go)", i + 1, 10 - i - 1);
- xbt_test_log
- ("Fill the struct, count its elems and frees the structure");
- xbt_test_log
- ("using 1000 elements with %d chars long randomized keys.",
- SIZEOFKEY);
+ xbt_test_log("Fill the struct, count its elems and frees the structure");
+ xbt_test_log("using 1000 elements with %d chars long randomized keys.", SIZEOFKEY);
head = xbt_dict_new();
/* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
for (j = 0; j < 1000; j++) {
xbt_dict_set(head, key, key, &free);
data = xbt_dict_get(head, key);
- xbt_test_assert(!strcmp(key, data),
- "Retrieved value (%s) != Injected value (%s)", key,
- data);
+ xbt_test_assert(!strcmp(key, data), "Retrieved value (%s) != Injected value (%s)", key, data);
count(head, j + 1);
}
xbt_dict_free(&head);
}
-
head = xbt_dict_new();
- xbt_test_add("Fill %d elements, with keys being the number of element",
- NB_ELM);
+ xbt_test_add("Fill %d elements, with keys being the number of element", NB_ELM);
for (j = 0; j < NB_ELM; j++) {
/* if (!(j%1000)) { printf("."); fflush(stdout); } */
-
key = xbt_malloc(10);
sprintf(key, "%d", j);
}
/*xbt_dict_dump(head,(void (*)(void*))&printf); */
- xbt_test_add
- ("Count the elements (retrieving the key and data for each)");
+ xbt_test_add("Count the elements (retrieving the key and data for each)");
i = countelems(head);
xbt_test_log("There is %d elements", i);
void *data;
/* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
for (j = 0; j < NB_ELM; j++) {
-
sprintf(key, "%d", j);
data = xbt_dict_get(head, key);
- xbt_test_assert(!strcmp(key, (char *) data),
- "with get, key=%s != data=%s", key, (char *) data);
+ xbt_test_assert(!strcmp(key, (char *) data), "with get, key=%s != data=%s", key, (char *) data);
data = xbt_dict_get_ext(head, key, strlen(key));
- xbt_test_assert(!strcmp(key, (char *) data),
- "with get_ext, key=%s != data=%s", key,
- (char *) data);
+ xbt_test_assert(!strcmp(key, (char *) data), "with get_ext, key=%s != data=%s", key, (char *) data);
}
}
free(key);
key = xbt_malloc(10);
for (j = 0; j < NB_ELM; j++) {
/* if (!(j%10000)) printf("."); fflush(stdout); */
-
sprintf(key, "%d", j);
xbt_dict_remove(head, key);
}
free(key);
-
xbt_test_add("Free the structure (twice)");
xbt_dict_free(&head);
xbt_dict_free(&head);
int i;
for (i = 0; i < count; ++i)
xbt_dict_set_ext(dict, (char*) &i, sizeof(i), (void*) (intptr_t) i, NULL);
- xbt_test_assert(xbt_dict_size(dict) == count,
- "Bad number of elements in the dictionnary");
+ xbt_test_assert(xbt_dict_size(dict) == count, "Bad number of elements in the dictionnary");
xbt_test_add("Check elements");
for (i = 0; i < count; ++i) {
int res = (int) (intptr_t) xbt_dict_get_ext(dict, (char*) &i, sizeof(i));
- xbt_test_assert(xbt_dict_size(dict) == count,
- "Unexpected value at index %i, expected %i but was %i", i, i, res);
+ xbt_test_assert(xbt_dict_size(dict) == count, "Unexpected value at index %i, expected %i but was %i", i, i, res);
}
xbt_test_add("Free the array");
xbt_dict_free(&dict);
}
-
#endif /* SIMGRID_TEST */
-/* dict_cursor - iterators over dictionnaries */
+/* dict_cursor - iterators over dictionaries */
/* Copyright (c) 2004-2014. The SimGrid Team.
* All rights reserved. */
#include <string.h> /* strlen() */
-XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict_cursor, xbt_dict,
- "To traverse dictionaries");
-
+XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict_cursor, xbt_dict, "To traverse dictionaries");
/*####[ Dict cursor functions ]#############################################*/
/* To traverse (simple) dicts */
xbt_assert(cursor, "Null cursor");
}
-
/** @brief Reinitialize the cursor. Mandatory after removal or add in dict. */
inline void xbt_dict_cursor_rewind(xbt_dict_cursor_t cursor)
{
* @param dict on what to let the cursor iterate
* @param[out] cursor dest address
*/
-inline void xbt_dict_cursor_first(const xbt_dict_t dict,
- xbt_dict_cursor_t * cursor)
+inline void xbt_dict_cursor_first(const xbt_dict_t dict, xbt_dict_cursor_t * cursor)
{
XBT_CDEBUG(xbt_dict_cursor, "xbt_dict_cursor_first");
if (!*cursor) {
}
}
-
-/**
- * \brief Move to the next element.
- */
+/** \brief Move to the next element. */
inline void xbt_dict_cursor_step(xbt_dict_cursor_t cursor)
{
xbt_dictelm_t current;
line = cursor->line;
if (cursor->dict != NULL) {
-
if (current != NULL) {
XBT_CDEBUG(xbt_dict_cursor, "current is not null, take the next element");
current = current->next;
*
* @returns true if it's ok, false if there is no more data
*/
-inline int xbt_dict_cursor_get_or_free(xbt_dict_cursor_t * cursor,
- char **key, void **data)
+inline int xbt_dict_cursor_get_or_free(xbt_dict_cursor_t * cursor, char **key, void **data)
{
-
xbt_dictelm_t current;
XBT_CDEBUG(xbt_dict_cursor, "xbt_dict_get_or_free");
-
if (!cursor || !(*cursor))
return FALSE;
* @param data the new data
* @param free_ctn the function to free the new data
*/
-inline void xbt_dict_cursor_set_data(xbt_dict_cursor_t cursor,
- void *data,
- void_f_pvoid_t free_ctn)
+inline void xbt_dict_cursor_set_data(xbt_dict_cursor_t cursor, void *data, void_f_pvoid_t free_ctn)
{
__cursor_not_null(cursor);
xbt_dictelm_set_data(cursor->dict, cursor->current, data, free_ctn);
#include "dict_private.h" /* prototypes of this module */
-XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict_elm, xbt_dict,
- "Dictionaries internals");
+XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict_elm, xbt_dict, "Dictionaries internals");
xbt_mallocator_t dict_elm_mallocator = NULL;
xbt_mallocator_t dict_het_elm_mallocator = NULL;
-xbt_dictelm_t xbt_dictelm_new(xbt_dict_t dict, const char *key, int key_len,
- unsigned int hash_code, void *content,
+xbt_dictelm_t xbt_dictelm_new(xbt_dict_t dict, const char *key, int key_len, unsigned int hash_code, void *content,
void_f_pvoid_t free_f)
{
xbt_dictelm_t element;
if (dict->homogeneous) {
- xbt_assert(!free_f,
- "Cannot set an individual free function in homogeneous dicts.");
+ xbt_assert(!free_f, "Cannot set an individual free function in homogeneous dicts.");
element = xbt_mallocator_get(dict_elm_mallocator);
} else {
xbt_het_dictelm_t het_element = xbt_mallocator_get(dict_het_elm_mallocator);
}
}
-void xbt_dictelm_set_data(xbt_dict_t dict, xbt_dictelm_t element,
- void *data, void_f_pvoid_t free_ctn)
+void xbt_dictelm_set_data(xbt_dict_t dict, xbt_dictelm_t element, void *data, void_f_pvoid_t free_ctn)
{
void_f_pvoid_t free_f;
if (dict->homogeneous) {
free_f = dict->free_f;
- xbt_assert(!free_ctn,
- "Cannot set an individual free function in homogeneous dicts.");
+ xbt_assert(!free_ctn, "Cannot set an individual free function in homogeneous dicts.");
} else {
xbt_het_dictelm_t het_element = (xbt_het_dictelm_t)element;
free_f = het_element->free_f;
#define MAX_FILL_PERCENT 80
-
typedef struct s_xbt_het_dictelm {
s_xbt_dictelm_t element;
void_f_pvoid_t free_f;
/*####[ Function prototypes ]################################################*/
XBT_PRIVATE xbt_dictelm_t xbt_dictelm_new(xbt_dict_t dict, const char *key, int key_len,
- unsigned int hash_code, void *content,
- void_f_pvoid_t free_f);
+ unsigned int hash_code, void *content, void_f_pvoid_t free_f);
XBT_PRIVATE void xbt_dictelm_free(xbt_dict_t dict, xbt_dictelm_t element);
-XBT_PRIVATE void xbt_dictelm_set_data(xbt_dict_t dict, xbt_dictelm_t element,
- void *data, void_f_pvoid_t free_ctn);
+XBT_PRIVATE void xbt_dictelm_set_data(xbt_dict_t dict, xbt_dictelm_t element, void *data, void_f_pvoid_t free_ctn);
#endif /* _XBT_DICT_PRIVATE_H_ */
static inline void _check_inbound_idx(xbt_dynar_t dynar, int idx)
{
if (idx < 0 || idx >= (int)dynar->used) {
- THROWF(bound_error, idx,
- "dynar is not that long. You asked %d, but it's only %lu long",
+ THROWF(bound_error, idx, "dynar is not that long. You asked %d, but it's only %lu long",
(int) (idx), (unsigned long) dynar->used);
}
}
}
}
-static inline
-void _xbt_dynar_resize(xbt_dynar_t dynar, unsigned long new_size)
+static inline void _xbt_dynar_resize(xbt_dynar_t dynar, unsigned long new_size)
{
if (new_size != dynar->size) {
dynar->size = new_size;
}
}
-static inline
- void _xbt_dynar_expand(xbt_dynar_t const dynar, const unsigned long nb)
+static inline void _xbt_dynar_expand(xbt_dynar_t const dynar, const unsigned long nb)
{
const unsigned long old_size = dynar->size;
if (nb > old_size) {
const unsigned long expand = 2 * (old_size + 1);
_xbt_dynar_resize(dynar, (nb > expand ? nb : expand));
- XBT_DEBUG("expand %p from %lu to %lu elements",
- dynar, old_size, dynar->size);
+ XBT_DEBUG("expand %p from %lu to %lu elements", dynar, old_size, dynar->size);
}
}
-static inline
- void *_xbt_dynar_elm(const xbt_dynar_t dynar, const unsigned long idx)
+static inline void *_xbt_dynar_elm(const xbt_dynar_t dynar, const unsigned long idx)
{
char *const data = (char *) dynar->data;
const unsigned long elmsize = dynar->elmsize;
return data + idx * elmsize;
}
-static inline
- void
-_xbt_dynar_get_elm(void *const dst,
- const xbt_dynar_t dynar, const unsigned long idx)
+static inline void _xbt_dynar_get_elm(void *const dst, const xbt_dynar_t dynar, const unsigned long idx)
{
void *const elm = _xbt_dynar_elm(dynar, idx);
void xbt_dynar_dump(xbt_dynar_t dynar)
{
XBT_INFO("Dynar dump: size=%lu; used=%lu; elmsize=%lu; data=%p; free_f=%p",
- dynar->size, dynar->used, dynar->elmsize, dynar->data,
- dynar->free_f);
+ dynar->size, dynar->used, dynar->elmsize, dynar->data, dynar->free_f);
}
/** @brief Constructor
* \param elmsize size of each element in the dynar
* \param free_f function to call each time we want to get rid of an element (or NULL if nothing to do).
*
- * Creates a new dynar. If a free_func is provided, the elements have to be
- * pointer of pointer. That is to say that dynars can contain either base
- * types (int, char, double, etc) or pointer of pointers (struct **).
+ * Creates a new dynar. If a free_func is provided, the elements have to be pointer of pointer. That is to say that
+ * dynars can contain either base types (int, char, double, etc) or pointer of pointers (struct **).
*/
-xbt_dynar_t
-xbt_dynar_new(const unsigned long elmsize, void_f_pvoid_t const free_f)
+xbt_dynar_t xbt_dynar_new(const unsigned long elmsize, void_f_pvoid_t const free_f)
{
-
xbt_dynar_t dynar = xbt_new0(s_xbt_dynar_t, 1);
dynar->size = 0;
*
* \param dynar poor victim
*
- * kilkil a dynar BUT NOT its content. Ie, the array is freed, but the content
- * is not touched (the \a free_f function is not used)
+ * kilkil a dynar BUT NOT its content. Ie, the array is freed, but the content is not touched (the \a free_f function
+ * is not used)
*/
void xbt_dynar_free_container(xbt_dynar_t * dynar)
{
/**
* \brief Shrink the dynar by removing empty slots at the end of the internal array
* \param dynar a dynar
- * \param empty_slots_wanted number of empty slots you want to keep at the end of the
- * internal array for further insertions
+ * \param empty_slots_wanted number of empty slots you want to keep at the end of the internal array for further
+ * insertions
*
- * Reduces the internal array size of the dynar to the number of elements plus
- * \a empty_slots_wanted.
- * After removing elements from the dynar, you can call this function to make
- * the dynar use less memory.
- * Set \a empty_slots_wanted to zero to reduce the dynar internal array as much
- * as possible.
- * Note that if \a empty_slots_wanted is greater than the array size, the internal
- * array is expanded instead of shriked.
+ * Reduces the internal array size of the dynar to the number of elements plus \a empty_slots_wanted.
+ * After removing elements from the dynar, you can call this function to make the dynar use less memory.
+ * Set \a empty_slots_wanted to zero to reduce the dynar internal array as much as possible.
+ * Note that if \a empty_slots_wanted is greater than the array size, the internal array is expanded instead of shrunk.
*/
void xbt_dynar_shrink(xbt_dynar_t dynar, int empty_slots_wanted)
{
*
* kilkil a dynar and its content
*/
-
inline void xbt_dynar_free(xbt_dynar_t * dynar)
{
if (dynar && *dynar) {
* \param idx index of the slot we want to retrieve
* \param[out] dst where to put the result to.
*/
-inline void
-xbt_dynar_get_cpy(const xbt_dynar_t dynar,
- const unsigned long idx, void *const dst)
+inline void xbt_dynar_get_cpy(const xbt_dynar_t dynar, const unsigned long idx, void *const dst)
{
_sanity_check_dynar(dynar);
_check_inbound_idx(dynar, idx);
* \warning The returned value is the actual content of the dynar.
* Make a copy before fooling with it.
*/
-inline void *xbt_dynar_get_ptr(const xbt_dynar_t dynar,
- const unsigned long idx)
+inline void *xbt_dynar_get_ptr(const xbt_dynar_t dynar, const unsigned long idx)
{
-
void *res;
_sanity_check_dynar(dynar);
_check_inbound_idx(dynar, idx);
return res;
}
-inline void *xbt_dynar_set_at_ptr(const xbt_dynar_t dynar,
- const unsigned long idx)
+inline void *xbt_dynar_set_at_ptr(const xbt_dynar_t dynar, const unsigned long idx)
{
_sanity_check_dynar(dynar);
if (idx >= dynar->used) {
_xbt_dynar_expand(dynar, idx + 1);
if (idx > dynar->used) {
- memset(_xbt_dynar_elm(dynar, dynar->used), 0,
- (idx - dynar->used) * dynar->elmsize);
+ memset(_xbt_dynar_elm(dynar, dynar->used), 0, (idx - dynar->used) * dynar->elmsize);
}
dynar->used = idx + 1;
}
*
* If you want to free the previous content, use xbt_dynar_replace().
*/
-inline void xbt_dynar_set(xbt_dynar_t dynar, const int idx,
- const void *const src)
+inline void xbt_dynar_set(xbt_dynar_t dynar, const int idx, const void *const src)
{
-
memcpy(xbt_dynar_set_at_ptr(dynar, idx), src, dynar->elmsize);
}
* \param idx
* \param object
*
- * Set the Nth element of a dynar, expanding the dynar if needed, AND DO
- * free the previous value at this position. If you don't want to free the
- * previous content, use xbt_dynar_set().
+ * Set the Nth element of a dynar, expanding the dynar if needed, AND DO free the previous value at this position. If
+ * you don't want to free the previous content, use xbt_dynar_set().
*/
-void
-xbt_dynar_replace(xbt_dynar_t dynar,
- const unsigned long idx, const void *const object)
+void xbt_dynar_replace(xbt_dynar_t dynar, const unsigned long idx, const void *const object)
{
_sanity_check_dynar(dynar);
/** @brief Make room for a new element, and return a pointer to it
*
- * You can then use regular affectation to set its value instead of relying
- * on the slow memcpy. This is what xbt_dynar_insert_at_as() does.
+ * You can then use regular affectation to set its value instead of relying on the slow memcpy. This is what
+ * xbt_dynar_insert_at_as() does.
*/
void *xbt_dynar_insert_at_ptr(xbt_dynar_t const dynar, const int idx)
{
nb_shift = old_used - idx;
if (nb_shift>0) {
- memmove(_xbt_dynar_elm(dynar, idx + 1),
- _xbt_dynar_elm(dynar, idx), nb_shift * dynar->elmsize);
+ memmove(_xbt_dynar_elm(dynar, idx + 1), _xbt_dynar_elm(dynar, idx), nb_shift * dynar->elmsize);
}
dynar->used = new_used;
/** @brief Set the Nth dynar's element, expanding the dynar and sliding the previous values to the right
*
- * Set the Nth element of a dynar, expanding the dynar if needed, and
- * moving the previously existing value and all subsequent ones to one
- * position right in the dynar.
+ * Set the Nth element of a dynar, expanding the dynar if needed, and moving the previously existing value and all
+ * subsequent ones to one position right in the dynar.
*/
-inline void
-xbt_dynar_insert_at(xbt_dynar_t const dynar,
- const int idx, const void *const src)
+inline void xbt_dynar_insert_at(xbt_dynar_t const dynar, const int idx, const void *const src)
{
-
/* checks done in xbt_dynar_insert_at_ptr */
memcpy(xbt_dynar_insert_at_ptr(dynar, idx), src, dynar->elmsize);
}
/** @brief Remove the Nth dynar's element, sliding the previous values to the left
*
- * Get the Nth element of a dynar, removing it from the dynar and moving
- * all subsequent values to one position left in the dynar.
+ * Get the Nth element of a dynar, removing it from the dynar and moving all subsequent values to one position left in
+ * the dynar.
*
- * If the object argument of this function is a non-null pointer, the removed
- * element is copied to this address. If not, the element is freed using the
- * free_f function passed at dynar creation.
+ * If the object argument of this function is a non-null pointer, the removed element is copied to this address. If not,
+ * the element is freed using the free_f function passed at dynar creation.
*/
-void
-xbt_dynar_remove_at(xbt_dynar_t const dynar,
- const int idx, void *const object)
+void xbt_dynar_remove_at(xbt_dynar_t const dynar, const int idx, void *const object)
{
unsigned long nb_shift;
unsigned long offset;
if (nb_shift) {
offset = nb_shift * dynar->elmsize;
- memmove(_xbt_dynar_elm(dynar, idx), _xbt_dynar_elm(dynar, idx + 1),
- offset);
+ memmove(_xbt_dynar_elm(dynar, idx), _xbt_dynar_elm(dynar, idx + 1), offset);
}
dynar->used--;
/** @brief Remove a slice of the dynar, sliding the rest of the values to the left
*
- * This function removes an n-sized slice that starts at element idx. It is equivalent
- * to xbt_dynar_remove_at with a NULL object argument if n equals to 1.
+ * This function removes an n-sized slice that starts at element idx. It is equivalent to xbt_dynar_remove_at with a
+ * NULL object argument if n equals to 1.
*
- * Each of the removed elements is freed using the free_f function passed at dynar
- * creation.
+ * Each of the removed elements is freed using the free_f function passed at dynar creation.
*/
-void
-xbt_dynar_remove_n_at(xbt_dynar_t const dynar,
- const unsigned int n, const int idx)
+void xbt_dynar_remove_n_at(xbt_dynar_t const dynar, const unsigned int n, const int idx)
{
unsigned long nb_shift;
unsigned long offset;
if (nb_shift) {
offset = nb_shift * dynar->elmsize;
- memmove(_xbt_dynar_elm(dynar, idx), _xbt_dynar_elm(dynar, idx + n),
- offset);
+ memmove(_xbt_dynar_elm(dynar, idx), _xbt_dynar_elm(dynar, idx + n), offset);
}
dynar->used -= n;
/** @brief Returns the position of the element in the dynar
*
- * Beware that if your dynar contains pointed values (such as strings) instead
- * of scalar, this function compares the pointer value, not what's pointed. The only
- * solution to search for a pointed value is then to write the foreach loop yourself:
+ * Beware that if your dynar contains pointed values (such as strings) instead of scalar, this function compares the
+ * pointer value, not what's pointed. The only solution to search for a pointed value is then to write the foreach loop
+ * yourself:
* \code
* signed int position = -1;
* xbt_dynar_foreach(dynar, iter, elem) {
* }
* \endcode
*
- * Raises not_found_error if not found. If you have less than 2 millions elements,
- * you probably want to use #xbt_dynar_search_or_negative() instead, so that you
- * don't have to TRY/CATCH on element not found.
+ * Raises not_found_error if not found. If you have less than 2 millions elements, you probably want to use
+ * #xbt_dynar_search_or_negative() instead, so that you don't have to TRY/CATCH on element not found.
*/
unsigned int xbt_dynar_search(xbt_dynar_t const dynar, void *const elem)
{
/** @brief Returns the position of the element in the dynar (or -1 if not found)
*
- * Beware that if your dynar contains pointed values (such as
- * strings) instead of scalar, this function is probably not what you
- * want. Check the documentation of xbt_dynar_search() for more info.
+ * Beware that if your dynar contains pointed values (such as strings) instead of scalar, this function is probably not
+ * what you want. Check the documentation of xbt_dynar_search() for more info.
*
- * Note that usually, the dynar indices are unsigned integers. If you have more
- * than 2 million elements in your dynar, this very function will not work (but the other will).
+ * Note that usually, the dynar indices are unsigned integers. If you have more than 2 million elements in your dynar,
+ * this very function will not work (but the other will).
*/
signed int xbt_dynar_search_or_negative(xbt_dynar_t const dynar, void *const elem)
{
/** @brief Returns a boolean indicating whether the element is part of the dynar
*
- * Beware that if your dynar contains pointed values (such as
- * strings) instead of scalar, this function is probably not what you
- * want. Check the documentation of xbt_dynar_search() for more info.
+ * Beware that if your dynar contains pointed values (such as strings) instead of scalar, this function is probably not
+ * what you want. Check the documentation of xbt_dynar_search() for more info.
*/
int xbt_dynar_member(xbt_dynar_t const dynar, void *const elem)
{
-
xbt_ex_t e;
TRY {
xbt_dynar_search(dynar, elem);
- }
- CATCH(e) {
+ } CATCH(e) {
if (e.category == not_found_error) {
xbt_ex_free(e);
return 0;
/** @brief Make room at the end of the dynar for a new element, and return a pointer to it.
*
- * You can then use regular affectation to set its value instead of relying
- * on the slow memcpy. This is what xbt_dynar_push_as() does.
+ * You can then use regular affectation to set its value instead of relying on the slow memcpy. This is what
+ * xbt_dynar_push_as() does.
*/
inline void *xbt_dynar_push_ptr(xbt_dynar_t const dynar)
{
}
/** @brief Add an element at the end of the dynar */
-inline void xbt_dynar_push(xbt_dynar_t const dynar,
- const void *const src)
+inline void xbt_dynar_push(xbt_dynar_t const dynar, const void *const src)
{
/* checks done in xbt_dynar_insert_at_ptr */
memcpy(xbt_dynar_insert_at_ptr(dynar, dynar->used), src, dynar->elmsize);
/** @brief Mark the last dynar's element as unused and return a pointer to it.
*
- * You can then use regular affectation to set its value instead of relying
- * on the slow memcpy. This is what xbt_dynar_pop_as() does.
+ * You can then use regular affectation to set its value instead of relying on the slow memcpy. This is what
+ * xbt_dynar_pop_as() does.
*/
inline void *xbt_dynar_pop_ptr(xbt_dynar_t const dynar)
{
/** @brief Get and remove the last element of the dynar */
inline void xbt_dynar_pop(xbt_dynar_t const dynar, void *const dst)
{
-
/* sanity checks done by remove_at */
XBT_CDEBUG(xbt_dyn, "Pop %p", (void *) dynar);
xbt_dynar_remove_at(dynar, dynar->used - 1, dst);
*
* This is less efficient than xbt_dynar_push()
*/
-inline void xbt_dynar_unshift(xbt_dynar_t const dynar,
- const void *const src)
+inline void xbt_dynar_unshift(xbt_dynar_t const dynar, const void *const src)
{
-
/* sanity checks done by insert_at */
xbt_dynar_insert_at(dynar, 0, src);
}
*/
inline void xbt_dynar_shift(xbt_dynar_t const dynar, void *const dst)
{
-
/* sanity checks done by remove_at */
xbt_dynar_remove_at(dynar, 0, dst);
}
/** @brief Apply a function to each member of a dynar
*
- * The mapped function may change the value of the element itself,
- * but should not mess with the structure of the dynar.
+ * The mapped function may change the value of the element itself, but should not mess with the structure of the dynar.
*/
-inline void xbt_dynar_map(const xbt_dynar_t dynar,
- void_f_pvoid_t const op)
+inline void xbt_dynar_map(const xbt_dynar_t dynar, void_f_pvoid_t const op)
{
char *const data = (char *) dynar->data;
const unsigned long elmsize = dynar->elmsize;
}
}
-
/** @brief Removes and free the entry pointed by the cursor
*
* This function can be used while traversing without problem.
*/
-inline void xbt_dynar_cursor_rm(xbt_dynar_t dynar,
- unsigned int *const cursor)
+inline void xbt_dynar_cursor_rm(xbt_dynar_t dynar, unsigned int *const cursor)
{
-
xbt_dynar_remove_at(dynar, (*cursor)--, NULL);
}
* \param dynar the dynar to sort
* \param compar_fn comparison function of type (int (compar_fn*) (void*) (void*)).
*
- * Remark: if the elements stored in the dynar are structures, the compar_fn
- * function has to retrieve the field to sort first.
+ * Remark: if the elements stored in the dynar are structures, the compar_fn function has to retrieve the field to sort
+ * first.
*/
-inline void xbt_dynar_sort(xbt_dynar_t dynar,
- int_f_cpvoid_cpvoid_t compar_fn)
+inline void xbt_dynar_sort(xbt_dynar_t dynar, int_f_cpvoid_cpvoid_t compar_fn)
{
qsort(dynar->data, dynar->used, dynar->elmsize, compar_fn);
}
static int strcmp_voidp(const void *pa, const void *pb) {
return strcmp(*(const char **)pa, *(const char **)pb);
}
+
/** @brief Sorts a dynar of strings (ie, char* data) */
xbt_dynar_t xbt_dynar_sort_strings(xbt_dynar_t dynar)
{
* See for example http://en.wikipedia.org/wiki/Dutch_national_flag_problem
*
* \param dynar the dynar to sort
- * \param color the color function of type (int (compar_fn*) (void*) (void*)). The return value of color is assumed to be 0, 1, or 2.
+ * \param color the color function of type (int (compar_fn*) (void*) (void*)). The return value of color is assumed to
+ * be 0, 1, or 2.
*
- * At the end of the call, elements with color 0 are at the beginning of the dynar, elements with color 2 are at the end and elements with color 1 are in the middle.
+ * At the end of the call, elements with color 0 are at the beginning of the dynar, elements with color 2 are at the
+ * end and elements with color 1 are in the middle.
*
- * Remark: if the elements stored in the dynar are structures, the color
- * function has to retrieve the field to sort first.
+ * Remark: if the elements stored in the dynar are structures, the color function has to retrieve the field to sort
+ * first.
*/
-XBT_PUBLIC(void) xbt_dynar_three_way_partition(xbt_dynar_t const dynar,
- int_f_pvoid_t color)
+XBT_PUBLIC(void) xbt_dynar_three_way_partition(xbt_dynar_t const dynar, int_f_pvoid_t color)
{
unsigned long int i;
unsigned long int p = -1;
* \param compar function to use to compare elements
* \return 0 if d1 and d2 are equal and 1 if not equal
*
- * d1 and d2 should be dynars of pointers. The compar function takes two
- * elements and returns 0 when they are considered equal, and a value different
- * of zero when they are considered different. Finally, d2 is destroyed
+ * d1 and d2 should be dynars of pointers. The compar function takes two elements and returns 0 when they are
+ * considered equal, and a value different of zero when they are considered different. Finally, d2 is destroyed
* afterwards.
*/
-int xbt_dynar_compare(xbt_dynar_t d1, xbt_dynar_t d2,
- int(*compar)(const void *, const void *))
+int xbt_dynar_compare(xbt_dynar_t d1, xbt_dynar_t d2, int(*compar)(const void *, const void *))
{
int i ;
int size;
xbt_dynar_free(&d2);
return 1;
}
- if((d1->elmsize)!=(d2->elmsize))
- {
+ if((d1->elmsize)!=(d2->elmsize)) {
XBT_DEBUG("Size of elmsize d1=%lu d2=%lu",d1->elmsize,d2->elmsize);
xbt_dynar_free(&d2);
return 1; // xbt_die
}
- if(xbt_dynar_length(d1) != xbt_dynar_length(d2))
- {
+ if(xbt_dynar_length(d1) != xbt_dynar_length(d2)) {
XBT_DEBUG("Size of dynar d1=%lu d2=%lu",xbt_dynar_length(d1),xbt_dynar_length(d2));
xbt_dynar_free(&d2);
return 1;
}
size = xbt_dynar_length(d1);
- for(i=0;i<size;i++)
- {
+ for(i=0;i<size;i++) {
void *data1 = xbt_dynar_get_as(d1, i, void *);
void *data2 = xbt_dynar_get_as(d2, i, void *);
XBT_DEBUG("link[%d] d1=%p d2=%p",i,data1,data2);
xbt_dynar_free(&d); /* free the struct twice here to check that it's ok, but freeing it only once */
/* in your code is naturally the way to go outside a regression test */
- xbt_test_add
- ("==== Push %d int, set them again 3 times, traverse them, shift them",
- NB_ELEM);
+ xbt_test_add("==== Push %d int, set them again 3 times, traverse them, shift them", NB_ELEM);
/* Populate_ints [doxygen cruft] */
/* 1. Populate the dynar */
d = xbt_dynar_new(sizeof(int), NULL);
/* 2. Traverse manually the dynar */
for (cursor = 0; cursor < NB_ELEM; cursor++) {
iptr = xbt_dynar_get_ptr(d, cursor);
- xbt_test_assert(cursor == *iptr,
- "The retrieved value is not the same than the injected one (%u!=%d)",
- cursor, cpt);
+ xbt_test_assert(cursor == *iptr, "The retrieved value is not the same than the injected one (%u!=%d)", cursor, cpt);
}
/* 3. Traverse the dynar using the neat macro to that extend */
xbt_dynar_foreach(d, cursor, cpt) {
- xbt_test_assert(cursor == cpt,
- "The retrieved value is not the same than the injected one (%u!=%d)",
- cursor, cpt);
+ xbt_test_assert(cursor == cpt, "The retrieved value is not the same than the injected one (%u!=%d)", cursor, cpt);
}
/* end_of_traversal */
cpt = 0;
xbt_dynar_foreach(d, cursor, i) {
- xbt_test_assert(i == cpt,
- "The retrieved value is not the same than the injected one (%d!=%d)",
- i, cpt);
+ xbt_test_assert(i == cpt, "The retrieved value is not the same than the injected one (%d!=%d)", i, cpt);
cpt++;
}
- xbt_test_assert(cpt == NB_ELEM,
- "Cannot retrieve my %d values. Last got one is %d",
- NB_ELEM, cpt);
+ xbt_test_assert(cpt == NB_ELEM, "Cannot retrieve my %d values. Last got one is %d", NB_ELEM, cpt);
/* shifting [doxygen cruft] */
/* 4. Shift all the values */
for (cpt = 0; cpt < NB_ELEM; cpt++) {
xbt_dynar_shift(d, &i);
- xbt_test_assert(i == cpt,
- "The retrieved value is not the same than the injected one (%d!=%d)",
- i, cpt);
+ xbt_test_assert(i == cpt, "The retrieved value is not the same than the injected one (%d!=%d)", i, cpt);
xbt_test_log("Pop %d, length=%lu", cpt, xbt_dynar_length(d));
}
}
for (cpt = 0; cpt < NB_ELEM; cpt++) {
i = xbt_dynar_pop_as(d, int);
- xbt_test_assert(i == cpt,
- "The retrieved value is not the same than the injected one (%d!=%d)",
- i, cpt);
+ xbt_test_assert(i == cpt, "The retrieved value is not the same than the injected one (%d!=%d)", i, cpt);
xbt_test_log("Pop %d, length=%lu", cpt, xbt_dynar_length(d));
}
xbt_dynar_free(&d); /* This code is used both as example and as regression test, so we try to */
xbt_dynar_free(&d); /* free the struct twice here to check that it's ok, but freeing it only once */
/* in your code is naturally the way to go outside a regression test */
-
- xbt_test_add
- ("==== Push %d int, insert 1000 int in the middle, shift everything",
- NB_ELEM);
+ xbt_test_add ("==== Push %d int, insert 1000 int in the middle, shift everything", NB_ELEM);
d = xbt_dynar_new(sizeof(int), NULL);
for (cpt = 0; cpt < NB_ELEM; cpt++) {
xbt_dynar_push_as(d, int, cpt);
for (cpt = 0; cpt < NB_ELEM/2; cpt++) {
xbt_dynar_shift(d, &i);
- xbt_test_assert(i == cpt,
- "The retrieved value is not the same than the injected one at the begining (%d!=%d)",
+ xbt_test_assert(i == cpt, "The retrieved value is not the same than the injected one at the begining (%d!=%d)",
i, cpt);
XBT_DEBUG("Pop %d, length=%lu", cpt, xbt_dynar_length(d));
}
for (cpt = 999; cpt >= 0; cpt--) {
xbt_dynar_shift(d, &i);
- xbt_test_assert(i == cpt,
- "The retrieved value is not the same than the injected one in the middle (%d!=%d)",
+ xbt_test_assert(i == cpt, "The retrieved value is not the same than the injected one in the middle (%d!=%d)",
i, cpt);
}
for (cpt = 2500; cpt < NB_ELEM; cpt++) {
xbt_dynar_shift(d, &i);
- xbt_test_assert(i == cpt,
- "The retrieved value is not the same than the injected one at the end (%d!=%d)",
- i, cpt);
+ xbt_test_assert(i == cpt, "The retrieved value is not the same than the injected one at the end (%d!=%d)", i, cpt);
}
xbt_dynar_free(&d); /* This code is used both as example and as regression test, so we try to */
xbt_dynar_free(&d); /* free the struct twice here to check that it's ok, but freeing it only once */
/* in your code is naturally the way to go outside a regression test */
- xbt_test_add("==== Push %d int, remove 2000-4000. free the rest",
- NB_ELEM);
+ xbt_test_add("==== Push %d int, remove 2000-4000. free the rest", NB_ELEM);
d = xbt_dynar_new(sizeof(int), NULL);
for (cpt = 0; cpt < NB_ELEM; cpt++)
xbt_dynar_push_as(d, int, cpt);
for (cpt = 2000; cpt < 4000; cpt++) {
xbt_dynar_remove_at(d, 2000, &i);
- xbt_test_assert(i == cpt,
- "Remove a bad value. Got %d, expected %d", i, cpt);
+ xbt_test_assert(i == cpt, "Remove a bad value. Got %d, expected %d", i, cpt);
XBT_DEBUG("remove %d, length=%lu", cpt, xbt_dynar_length(d));
}
xbt_dynar_free(&d); /* This code is used both as example and as regression test, so we try to */
/* in your code is naturally the way to go outside a regression test */
}
-/*******************************************************************************/
-/*******************************************************************************/
/*******************************************************************************/
XBT_TEST_UNIT("insert",test_dynar_insert,"Using the xbt_dynar_insert and xbt_dynar_remove functions")
{
/* 3. Traverse the dynar */
xbt_dynar_foreach(d, cursor, cpt) {
- xbt_test_assert(cursor == cpt,
- "The retrieved value is not the same than the injected one (%u!=%d)",
- cursor, cpt);
+ xbt_test_assert(cursor == cpt, "The retrieved value is not the same than the injected one (%u!=%d)", cursor, cpt);
}
/* end_of_traversal */
for (cpt = 0; cpt < NB_ELEM; cpt++)
xbt_dynar_set_as(d, cpt, int, cpt);
xbt_dynar_foreach(d, cursor, cpt)
- xbt_test_assert(cursor == cpt,
- "The retrieved value is not the same than the injected one (%u!=%d)",
- cursor, cpt);
+ xbt_test_assert(cursor == cpt, "The retrieved value is not the same than the injected one (%u!=%d)", cursor, cpt);
for (cpt = 0; cpt < NB_ELEM; cpt++) {
int val;
xbt_dynar_remove_at(d,0,&val);
- xbt_test_assert(cpt == val,
- "The retrieved value is not the same than the injected one (%u!=%d)",
- cursor, cpt);
+ xbt_test_assert(cpt == val, "The retrieved value is not the same than the injected one (%u!=%d)", cursor, cpt);
}
- xbt_test_assert(xbt_dynar_is_empty(d),
- "There is still %lu elements in the dynar after removing everything",
+ xbt_test_assert(xbt_dynar_is_empty(d), "There is still %lu elements in the dynar after removing everything",
xbt_dynar_length(d));
xbt_dynar_free(&d);
/* 3. Traverse the dynar */
xbt_dynar_foreach(d, cursor, cpt) {
- xbt_test_assert(cursor == cpt,
- "The retrieved value is not the same than the injected one (%u!=%d)",
- cursor, cpt);
+ xbt_test_assert(cursor == cpt, "The retrieved value is not the same than the injected one (%u!=%d)", cursor, cpt);
}
/* end_of_traversal */
for (cpt =NB_ELEM-1; cpt >=0; cpt--) {
int val;
xbt_dynar_remove_at(d,xbt_dynar_length(d)-1,&val);
- xbt_test_assert(cpt == val,
- "The retrieved value is not the same than the injected one (%u!=%d)",
- cursor, cpt);
+ xbt_test_assert(cpt == val, "The retrieved value is not the same than the injected one (%u!=%d)", cursor, cpt);
}
- xbt_test_assert(xbt_dynar_is_empty(d),
- "There is still %lu elements in the dynar after removing everything",
+ xbt_test_assert(xbt_dynar_is_empty(d), "There is still %lu elements in the dynar after removing everything",
xbt_dynar_length(d));
xbt_dynar_free(&d);
}
-/*******************************************************************************/
-/*******************************************************************************/
/*******************************************************************************/
XBT_TEST_UNIT("double", test_dynar_double, "Dynars of doubles")
{
xbt_test_add("==== Traverse the empty dynar");
d = xbt_dynar_new(sizeof(int), NULL);
xbt_dynar_foreach(d, cursor, cpt) {
- xbt_test_assert(FALSE,
- "Damnit, there is something in the empty dynar");
+ xbt_test_assert(FALSE, "Damnit, there is something in the empty dynar");
}
xbt_dynar_free(&d); /* This code is used both as example and as regression test, so we try to */
xbt_dynar_free(&d); /* free the struct twice here to check that it's ok, but freeing it only once */
}
xbt_dynar_foreach(d, cursor, d2) {
d1 = (double) cursor;
- xbt_test_assert(d1 == d2,
- "The retrieved value is not the same than the injected one (%f!=%f)",
- d1, d2);
+ xbt_test_assert(d1 == d2, "The retrieved value is not the same than the injected one (%f!=%f)", d1, d2);
}
for (cpt = 0; cpt < 5000; cpt++) {
d1 = (double) cpt;
xbt_dynar_shift(d, &d2);
- xbt_test_assert(d1 == d2,
- "The retrieved value is not the same than the injected one (%f!=%f)",
- d1, d2);
+ xbt_test_assert(d1 == d2, "The retrieved value is not the same than the injected one (%f!=%f)", d1, d2);
}
xbt_dynar_free(&d); /* This code is used both as example and as regression test, so we try to */
xbt_dynar_free(&d); /* free the struct twice here to check that it's ok, but freeing it only once */
for (cpt = 0; cpt < 5000; cpt++) {
d1 = (double) cpt;
xbt_dynar_pop(d, &d2);
- xbt_test_assert(d1 == d2,
- "The retrieved value is not the same than the injected one (%f!=%f)",
- d1, d2);
+ xbt_test_assert(d1 == d2, "The retrieved value is not the same than the injected one (%f!=%f)", d1, d2);
}
xbt_dynar_free(&d); /* This code is used both as example and as regression test, so we try to */
xbt_dynar_free(&d); /* free the struct twice here to check that it's ok, but freeing it only once */
/* in your code is naturally the way to go outside a regression test */
-
-
- xbt_test_add
- ("==== Push 5000 doubles, insert 1000 doubles in the middle, shift everything");
+ xbt_test_add("==== Push 5000 doubles, insert 1000 doubles in the middle, shift everything");
d = xbt_dynar_new(sizeof(double), NULL);
for (cpt = 0; cpt < 5000; cpt++) {
d1 = (double) cpt;
for (cpt = 0; cpt < 2500; cpt++) {
d1 = (double) cpt;
xbt_dynar_shift(d, &d2);
- xbt_test_assert(d1 == d2,
- "The retrieved value is not the same than the injected one at the begining (%f!=%f)",
+ xbt_test_assert(d1 == d2, "The retrieved value is not the same than the injected one at the begining (%f!=%f)",
d1, d2);
XBT_DEBUG("Pop %d, length=%lu", cpt, xbt_dynar_length(d));
}
for (cpt = 999; cpt >= 0; cpt--) {
d1 = (double) cpt;
xbt_dynar_shift(d, &d2);
- xbt_test_assert(d1 == d2,
- "The retrieved value is not the same than the injected one in the middle (%f!=%f)",
+ xbt_test_assert(d1 == d2, "The retrieved value is not the same than the injected one in the middle (%f!=%f)",
d1, d2);
}
for (cpt = 2500; cpt < 5000; cpt++) {
d1 = (double) cpt;
xbt_dynar_shift(d, &d2);
- xbt_test_assert(d1 == d2,
- "The retrieved value is not the same than the injected one at the end (%f!=%f)",
- d1, d2);
+ xbt_test_assert(d1 == d2, "The retrieved value is not the same than the injected one at the end (%f!=%f)", d1, d2);
}
xbt_dynar_free(&d); /* This code is used both as example and as regression test, so we try to */
xbt_dynar_free(&d); /* free the struct twice here to check that it's ok, but freeing it only once */
/* in your code is naturally the way to go outside a regression test */
-
xbt_test_add("==== Push 5000 double, remove 2000-4000. free the rest");
d = xbt_dynar_new(sizeof(double), NULL);
for (cpt = 0; cpt < 5000; cpt++) {
for (cpt = 2000; cpt < 4000; cpt++) {
d1 = (double) cpt;
xbt_dynar_remove_at(d, 2000, &d2);
- xbt_test_assert(d1 == d2,
- "Remove a bad value. Got %f, expected %f", d2, d1);
+ xbt_test_assert(d1 == d2, "Remove a bad value. Got %f, expected %f", d2, d1);
}
xbt_dynar_free(&d); /* This code is used both as example and as regression test, so we try to */
xbt_dynar_free(&d); /* free the struct twice here to check that it's ok, but freeing it only once */
/* in your code is naturally the way to go outside a regression test */
}
-
/* doxygen_string_cruft */
-/*******************************************************************************/
-/*******************************************************************************/
/*******************************************************************************/
XBT_TEST_UNIT("string", test_dynar_string, "Dynars of strings")
{
xbt_test_add("==== Traverse the empty dynar");
d = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
xbt_dynar_foreach(d, iter, s1) {
- xbt_test_assert(FALSE,
- "Damnit, there is something in the empty dynar");
+ xbt_test_assert(FALSE, "Damnit, there is something in the empty dynar");
}
xbt_dynar_free(&d); /* This code is used both as example and as regression test, so we try to */
xbt_dynar_free(&d); /* free the struct twice here to check that it's ok, but freeing it only once */
/* in your code is naturally the way to go outside a regression test */
- xbt_test_add("==== Push %d strings, set them again 3 times, shift them",
- NB_ELEM);
+ xbt_test_add("==== Push %d strings, set them again 3 times, shift them", NB_ELEM);
/* Populate_str [doxygen cruft] */
d = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
/* 1. Populate the dynar */
for (cpt = 0; cpt < NB_ELEM; cpt++) {
sprintf(buf, "%d", cpt);
xbt_dynar_shift(d, &s2);
- xbt_test_assert(!strcmp(buf, s2),
- "The retrieved value is not the same than the injected one (%s!=%s)",
- buf, s2);
+ xbt_test_assert(!strcmp(buf, s2), "The retrieved value is not the same than the injected one (%s!=%s)", buf, s2);
free(s2);
}
xbt_dynar_free(&d); /* This code is used both as example and as regression test, so we try to */
/* 2. Traverse the dynar with the macro */
xbt_dynar_foreach(d, iter, s1) {
sprintf(buf, "%u", NB_ELEM - iter - 1);
- xbt_test_assert(!strcmp(buf, s1),
- "The retrieved value is not the same than the injected one (%s!=%s)",
- buf, s1);
+ xbt_test_assert(!strcmp(buf, s1), "The retrieved value is not the same than the injected one (%s!=%s)", buf, s1);
}
/* 3. Traverse the dynar with the macro */
for (cpt = 0; cpt < NB_ELEM; cpt++) {
sprintf(buf, "%d", cpt);
xbt_dynar_pop(d, &s2);
- xbt_test_assert(!strcmp(buf, s2),
- "The retrieved value is not the same than the injected one (%s!=%s)",
- buf, s2);
+ xbt_test_assert(!strcmp(buf, s2), "The retrieved value is not the same than the injected one (%s!=%s)", buf, s2);
free(s2);
}
/* 4. Free the resources */
xbt_dynar_free(&d); /* free the struct twice here to check that it's ok, but freeing it only once */
/* in your code is naturally the way to go outside a regression test */
-
- xbt_test_add
- ("==== Push %d strings, insert %d strings in the middle, shift everything",
- NB_ELEM, NB_ELEM / 5);
+ xbt_test_add("==== Push %d strings, insert %d strings in the middle, shift everything", NB_ELEM, NB_ELEM / 5);
d = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
for (cpt = 0; cpt < NB_ELEM; cpt++) {
sprintf(buf, "%d", cpt);
sprintf(buf, "%d", cpt);
xbt_dynar_shift(d, &s2);
xbt_test_assert(!strcmp(buf, s2),
- "The retrieved value is not the same than the injected one at the begining (%s!=%s)",
- buf, s2);
+ "The retrieved value is not the same than the injected one at the begining (%s!=%s)", buf, s2);
free(s2);
}
for (cpt = (NB_ELEM / 5) - 1; cpt >= 0; cpt--) {
sprintf(buf, "%d", cpt);
xbt_dynar_shift(d, &s2);
xbt_test_assert(!strcmp(buf, s2),
- "The retrieved value is not the same than the injected one in the middle (%s!=%s)",
- buf, s2);
+ "The retrieved value is not the same than the injected one in the middle (%s!=%s)", buf, s2);
free(s2);
}
for (cpt = NB_ELEM / 2; cpt < NB_ELEM; cpt++) {
sprintf(buf, "%d", cpt);
xbt_dynar_shift(d, &s2);
- xbt_test_assert(!strcmp(buf, s2),
- "The retrieved value is not the same than the injected one at the end (%s!=%s)",
+ xbt_test_assert(!strcmp(buf, s2), "The retrieved value is not the same than the injected one at the end (%s!=%s)",
buf, s2);
free(s2);
}
xbt_dynar_free(&d); /* free the struct twice here to check that it's ok, but freeing it only once */
/* in your code is naturally the way to go outside a regression test */
-
- xbt_test_add("==== Push %d strings, remove %d-%d. free the rest",
- NB_ELEM, 2 * (NB_ELEM / 5), 4 * (NB_ELEM / 5));
+ xbt_test_add("==== Push %d strings, remove %d-%d. free the rest", NB_ELEM, 2 * (NB_ELEM / 5), 4 * (NB_ELEM / 5));
d = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
for (cpt = 0; cpt < NB_ELEM; cpt++) {
sprintf(buf, "%d", cpt);
for (cpt = 2 * (NB_ELEM / 5); cpt < 4 * (NB_ELEM / 5); cpt++) {
sprintf(buf, "%d", cpt);
xbt_dynar_remove_at(d, 2 * (NB_ELEM / 5), &s2);
- xbt_test_assert(!strcmp(buf, s2),
- "Remove a bad value. Got %s, expected %s", s2, buf);
+ xbt_test_assert(!strcmp(buf, s2), "Remove a bad value. Got %s, expected %s", s2, buf);
free(s2);
}
xbt_dynar_free(&d); /* end_of_doxygen */
# define HAVE_BACKTRACE 1 /* Hello x86 windows box */
#endif
-
XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_ex, xbt, "Exception mecanism");
XBT_EXPORT_NO_IMPORT(const xbt_running_ctx_t) __xbt_ex_ctx_initializer = XBT_RUNNING_CTX_INITIALIZER;
if (e->pid != xbt_getpid())
thrower = bprintf(" on process %d",e->pid);
- fprintf(stderr,
- "** SimGrid: UNCAUGHT EXCEPTION received on %s(%d): category: %s; value: %d\n"
+ fprintf(stderr, "** SimGrid: UNCAUGHT EXCEPTION received on %s(%d): category: %s; value: %d\n"
"** %s\n"
"** Thrown by %s()%s\n",
- xbt_binary_name, xbt_getpid(),
- xbt_ex_catname(e->category), e->value, e->msg,
+ xbt_binary_name, xbt_getpid(), xbt_ex_catname(e->category), e->value, e->msg,
e->procname, thrower ? thrower : " in this process");
XBT_CRITICAL("%s", e->msg);
xbt_free(thrower);
fprintf(stderr, "%s\n", e->bt_strings[i]);
}
}
-
} else
#endif
fprintf(stderr, "\n"
"** (no backtrace available)\n", e->func, e->file, e->line);
}
-
/* default __ex_terminate callback function */
void __xbt_ex_terminate_default(xbt_ex_t * e)
{
XBT_EXPORT_NO_IMPORT(xbt_running_ctx_fetcher_t) __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
XBT_EXPORT_NO_IMPORT(ex_term_cb_t) __xbt_ex_terminate = &__xbt_ex_terminate_default;
-
void xbt_ex_free(xbt_ex_t e)
{
free(e.msg);
return "io error";
case vm_error:
return "vm error";
-
}
return "INVALID ERROR";
}
-
#ifdef SIMGRID_TEST
#include <stdio.h>
#include "xbt/ex.h"
xbt_test_fail("M2: n=%d (!= 2)", n);
n++;
THROWF(unknown_error, 0, "something");
- }
- CATCH(ex) {
+ } CATCH(ex) {
if (n != 3)
xbt_test_fail("M3: n=%d (!= 3)", n);
n++;
xbt_test_fail("M2: n=%d (!= 5)", n);
n++;
THROWF(unknown_error, 0, "something");
- }
- CATCH_ANONYMOUS {
+ } CATCH_ANONYMOUS {
if (n != 6)
xbt_test_fail("M3: n=%d (!= 6)", n);
n++;
n++;
}
xbt_test_fail("MX: n=%d (shouldn't reach this point)", n);
- }
- CATCH(ex) {
+ } CATCH(ex) {
if (n != 7)
xbt_test_fail("M4: n=%d (!= 7)", n);
n++;
TRY {
THROWF(unknown_error, 2, "toto");
- }
- CATCH(ex) {
+ } CATCH(ex) {
xbt_test_add("exception value passing");
if (ex.category != unknown_error)
xbt_test_fail("category=%d (!= 1)", (int)ex.category);
r2 = 5678;
v2 = 5678;
THROWF(unknown_error, 0, "toto");
- }
- CATCH(ex) {
+ } CATCH(ex) {
xbt_test_add("variable preservation");
if (r1 != 1234)
xbt_test_fail("r1=%d (!= 1234)", r1);
if (v1 != 5678)
xbt_test_fail("v1 = %d (!= 5678)", v1);
c = 1;
- }
- CATCH(ex) {
+ } CATCH(ex) {
if (v1 != 5678)
xbt_test_fail("v1 = %d (!= 5678)", v1);
if (!(ex.category == 1 && ex.value == 2 && !strcmp(ex.msg, "blah")))
xbt_test_fail("xbt_ex_free not executed");
}
-
/*
* The following is the example included in the documentation. It's a good
* idea to check its syntax even if we don't try to run it.
return fifo;
}
-
/** Destructor
* \param l poor victim
*
{
xbt_fifo_item_t current, current_next;
-
for (current = l->head; current; current = current_next) {
current_next = current->next;
if (current->content != t)
return 0;
}
-
/**
* \param l
* \param t an objet
* This function allows to search an item with a user provided function instead
* of the pointer comparison used elsewhere in this module. Assume for example that you have a fifo of
* strings. You cannot use xbt_fifo_remove() to remove, say, "TOTO" from it because internally, xbt_fifo_remove()
- * will do something like "if (item->content == "toto"), then remove it". And the pointer to the item content
- * and the pointer to "toto" will never match. As a solution, the current function provides a way to search elements
- * that are semanticaly equivalent instead of only syntaxically. So, removing "Toto" from a fifo can be
- * achieved this way:
+ * will do something like "if (item->content == "toto"), then remove it". And the pointer to the item content and the
+ * pointer to "toto" will never match. As a solution, the current function provides a way to search elements that are
+ * semantically equivalent instead of only syntactically. So, removing "Toto" from a fifo can be achieved this way:
*
* @verbatim
int my_comparison_function(void *searched, void *seen) {
return !strcmp(searched, seen);
}
- xbt_fifo_remove_item(fifo,
- xbt_fifo_search_item(fifo, my_comparison_function, "Toto"));
+ xbt_fifo_remove_item(fifo, xbt_fifo_search_item(fifo, my_comparison_function, "Toto"));
@endverbatim
*
* \param f a fifo list
item = item->next;
}
return NULL;
-
}
/**
*/
void xbt_fifo_preinit(void)
{
- item_mallocator = xbt_mallocator_new(65536,
- fifo_item_mallocator_new_f,
- fifo_item_mallocator_free_f,
- fifo_item_mallocator_reset_f);
+ item_mallocator = xbt_mallocator_new(65536, fifo_item_mallocator_new_f,
+ fifo_item_mallocator_free_f, fifo_item_mallocator_reset_f);
}
void xbt_fifo_postexit(void)
item_mallocator = NULL;
}
}
-
/* @} */
xbt_fifo_item_t tail;
} s_xbt_fifo_t;
-
#define xbt_fifo_getFirstitem(l) ((l)?(l)->head:NULL)
#define xbt_fifo_getNextitem(i) ((i)?(i)->next:NULL)
#define xbt_fifo_getPrevitem(i) ((i)?(i)->prev:NULL)
#include <errno.h>
#include <stdlib.h>
-
XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_graph, xbt, "Graph");
-
-
/** @brief Constructor
* @return a new graph
*/
*
* Free the graph structure.
*/
-void xbt_graph_free_graph(xbt_graph_t g,
- void_f_pvoid_t node_free_function,
- void_f_pvoid_t edge_free_function,
+void xbt_graph_free_graph(xbt_graph_t g, void_f_pvoid_t node_free_function, void_f_pvoid_t edge_free_function,
void_f_pvoid_t graph_free_function)
{
unsigned int cursor;
free(g);
}
-
/** @brief Retrieve the graph's nodes as a dynar */
xbt_dynar_t xbt_graph_get_nodes(xbt_graph_t g)
{
*
* From wikipedia:
*
- * The Floyd–Warshall algorithm takes as input an adjacency matrix
- * representation of a weighted, directed graph (V, E). The weight of a
- * path between two vertices is the sum of the weights of the edges along
- * that path. The edges E of the graph may have negative weights, but the
- * graph must not have any negative weight cycles. The algorithm computes,
- * for each pair of vertices, the minimum weight among all paths between
- * the two vertices. The running time complexity is Θ(|V|3).
+ * The Floyd–Warshall algorithm takes as input an adjacency matrix representation of a weighted, directed graph (V, E).
+ * The weight of a path between two vertices is the sum of the weights of the edges along that path. The edges E of the
+ * graph may have negative weights, but the graph must not have any negative weight cycles. The algorithm computes, for
+ * each pair of vertices, the minimum weight among all paths between the two vertices. The running time complexity is
+ * Θ(|V|3).
*/
-void xbt_floyd_algorithm(xbt_graph_t g, double *adj, double *d,
- xbt_node_t * p)
+void xbt_floyd_algorithm(xbt_graph_t g, double *adj, double *d, xbt_node_t * p)
{
unsigned long i, j, k;
unsigned long n;
d[i] = adj[i];
}
-
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (D(i, j) != -1) {
}
/** @brief Export the given graph in the GraphViz formatting for visualization */
-void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename,
- const char *(node_name) (xbt_node_t),
+void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename, const char *(node_name) (xbt_node_t),
const char *(edge_name) (xbt_edge_t))
{
unsigned int cursor = 0;
fprintf(file, " graph [overlap=scale]\n");
fprintf(file, " node [shape=box, style=filled]\n");
- fprintf(file,
- " node [width=.3, height=.3, style=filled, color=skyblue]\n\n");
+ fprintf(file, " node [width=.3, height=.3, style=filled, color=skyblue]\n\n");
xbt_dynar_foreach(g->nodes, cursor, node) {
if (node_name){
/**
* @brief Creates a new heap.
* \param init_size initial size of the heap
- * \param free_func function to call on each element when you want to free
- * the whole heap (or NULL if nothing to do).
+ * \param free_func function to call on each element when you want to free the whole heap (or NULL if nothing to do).
*
* Creates a new heap.
*/
-inline xbt_heap_t xbt_heap_new(int init_size,
- void_f_pvoid_t const free_func)
+inline xbt_heap_t xbt_heap_new(int init_size, void_f_pvoid_t const free_func)
{
xbt_heap_t H = xbt_new0(struct xbt_heap, 1);
H->size = init_size;
* @param H the heap we're working on
* \param update_callback function to call on each element to update its index when needed.
*/
-inline void xbt_heap_set_update_callback(xbt_heap_t H,
- void (*update_callback) (void
- *,
- int))
+inline void xbt_heap_set_update_callback(xbt_heap_t H, void (*update_callback) (void*, int))
{
H->update_callback = update_callback;
}
-
/**
* @brief kilkil a heap and its content
* @param H poor victim
if (count > size) {
H->size = (size << 1) + 1;
- H->items =
- (void *) xbt_realloc(H->items,
- (H->size) * sizeof(struct xbt_heap_item));
+ H->items = (void *) xbt_realloc(H->items, (H->size) * sizeof(struct xbt_heap_item));
}
item = &(H->items[count - 1]);
* \param H the heap we're working on
* \return the element with the smallest key
*
- * Extracts from the heap and returns the element with the smallest
- * key. The element with the next smallest key is automatically moved
- * at the top of the heap.
+ * Extracts from the heap and returns the element with the smallest key. The element with the next smallest key is
+ * automatically moved at the top of the heap.
*/
void *xbt_heap_pop(xbt_heap_t H)
{
xbt_heap_max_heapify(H,0);
if (H->count < size >> 2 && size > 16) {
size = (size >> 1) + 1;
- H->items =
- (void *) xbt_realloc(items,
- size * sizeof(struct xbt_heap_item));
+ H->items = (void *) xbt_realloc(items, size * sizeof(struct xbt_heap_item));
H->size = size;
}
* \param i element position
* \return the element at position i if ok, NULL otherwise
*
- * Extracts from the heap and returns the element at position i. The heap is automatically reorded.
+ * Extracts from the heap and returns the element at position i. The heap is automatically reordered.
*/
void *xbt_heap_remove(xbt_heap_t H, int i)
{
* \param H the heap we're working on
* \param i an item position in the heap
*
- * Moves up an item at position i to its correct position. Works only
- * when called from xbt_heap_push. Do not use otherwise.
+ * Moves up an item at position i to its correct position. Works only when called from xbt_heap_push.
+ * Do not use otherwise.
*/
static void xbt_heap_increase_key(xbt_heap_t H, int i)
{
#include <xbt/log.h>
#include <xbt/lib.h>
-XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_lib, xbt,
- "A dict with keys of type (name, level)");
+XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_lib, xbt, "A dict with keys of type (name, level)");
xbt_lib_t xbt_lib_new(void)
{
}
}
-static void _xbt_log_cat_apply_set(xbt_log_category_t category,
- xbt_log_setting_t setting);
+static void _xbt_log_cat_apply_set(xbt_log_category_t category, xbt_log_setting_t setting);
const char *xbt_log_priority_names[8] = {
"NONE",
0 /* additivity */
};
-XBT_LOG_NEW_DEFAULT_SUBCATEGORY(log, xbt,
- "Loggings from the logging mechanism itself");
+XBT_LOG_NEW_DEFAULT_SUBCATEGORY(log, xbt, "Loggings from the logging mechanism itself");
/* create the default appender and install it in the root category,
which were already created (damnit. Too slow little beetle) */
{
xbt_log_category_t cat = ev->cat;
- xbt_assert(ev->priority >= 0,
- "Negative logging priority naturally forbidden");
- xbt_assert(ev->priority < sizeof(xbt_log_priority_names),
- "Priority %d is greater than the biggest allowed value",
+ xbt_assert(ev->priority >= 0, "Negative logging priority naturally forbidden");
+ xbt_assert(ev->priority < sizeof(xbt_log_priority_names), "Priority %d is greater than the biggest allowed value",
ev->priority);
do {
if (!appender)
continue; /* No appender, try next */
- xbt_assert(cat->layout,
- "No valid layout for the appender of category %s", cat->name);
+ xbt_assert(cat->layout, "No valid layout for the appender of category %s", cat->name);
/* First, try with a static buffer */
if (XBT_LOG_STATIC_BUFFER_SIZE) {
/* NOTE:
*
- * The standard logging macros use _XBT_LOG_ISENABLED, which calls
- * _xbt_log_cat_init(). Thus, if we want to avoid an infinite
- * recursion, we can not use the standard logging macros in
- * _xbt_log_cat_init(), and in all functions called from it.
+ * The standard logging macros use _XBT_LOG_ISENABLED, which calls _xbt_log_cat_init(). Thus, if we want to avoid an
+ * infinite recursion, we can not use the standard logging macros in _xbt_log_cat_init(), and in all functions called
+ * from it.
*
- * To circumvent the problem, we define the macro_xbt_log_init() as
- * (0) for the length of the affected functions, and we do not forget
- * to undefine it at the end!
+ * To circumvent the problem, we define the macro_xbt_log_init() as (0) for the length of the affected functions, and
+ * we do not forget to undefine it at the end!
*/
-static void _xbt_log_cat_apply_set(xbt_log_category_t category,
- xbt_log_setting_t setting)
+static void _xbt_log_cat_apply_set(xbt_log_category_t category, xbt_log_setting_t setting)
{
#define _xbt_log_cat_init(a, b) (0)
xbt_log_threshold_set(category, setting->thresh);
XBT_DEBUG("Apply settings for category '%s': set threshold to %s (=%d)",
- category->name, xbt_log_priority_names[category->threshold],
- category->threshold);
+ category->name, xbt_log_priority_names[category->threshold], category->threshold);
}
if (setting->fmt) {
if (!category->layout)
xbt_log_layout_set(category, xbt_log_layout_simple_new(NULL));
category->additivity = 0;
- XBT_DEBUG("Set %p as appender of category '%s'",
- setting->appender, category->name);
+ XBT_DEBUG("Set %p as appender of category '%s'", setting->appender, category->name);
}
#undef _xbt_log_cat_init
}
/*
- * This gets called the first time a category is referenced and performs the
- * initialization.
+ * This gets called the first time a category is referenced and performs the initialization.
* Also resets threshold to inherited!
*/
-int _xbt_log_cat_init(xbt_log_category_t category,
- e_xbt_log_priority_t priority)
+int _xbt_log_cat_init(xbt_log_category_t category, e_xbt_log_priority_t priority)
{
#define _xbt_log_cat_init(a, b) (0)
xbt_log_setting_t setting = NULL;
int found = 0;
- XBT_DEBUG("Initializing category '%s' (firstChild=%s, nextSibling=%s)",
- category->name,
+ XBT_DEBUG("Initializing category '%s' (firstChild=%s, nextSibling=%s)", category->name,
(category->firstChild ? category->firstChild->name : "none"),
(category->nextSibling ? category->nextSibling->name : "none"));
category->appender = xbt_log_default_appender;
category->layout = xbt_log_default_layout;
} else {
-
if (!category->parent)
category->parent = &_XBT_LOGV(XBT_LOG_ROOT_CAT);
- XBT_DEBUG("Set %s (%s) as father of %s ",
- category->parent->name,
- (category->parent->initialized ?
- xbt_log_priority_names[category->parent->threshold] : "uninited"),
+ XBT_DEBUG("Set %s (%s) as father of %s ", category->parent->name,
+ (category->parent->initialized ? xbt_log_priority_names[category->parent->threshold] : "uninited"),
category->name);
xbt_log_parent_set(category, category->parent);
cpp = cpp->nextSibling;
}
- XBT_DEBUG("Children of %s: %s; nextSibling: %s",
- category->parent->name, res,
- (category->parent->nextSibling ?
- category->parent->nextSibling->name : "none"));
+ XBT_DEBUG("Children of %s: %s; nextSibling: %s", category->parent->name, res,
+ (category->parent->nextSibling ? category->parent->nextSibling->name : "none"));
free(res);
}
-
}
/* Apply the control */
xbt_dynar_foreach(xbt_log_settings, cursor, setting) {
xbt_assert(setting, "Damnit, NULL cat in the list");
- xbt_assert(setting->catname, "NULL setting(=%p)->catname",
- (void *) setting);
+ xbt_assert(setting->catname, "NULL setting(=%p)->catname", (void *) setting);
if (!strcmp(setting->catname, category->name)) {
found = 1;
if (!found)
XBT_DEBUG("Category '%s': inherited threshold = %s (=%d)",
- category->name, xbt_log_priority_names[category->threshold],
- category->threshold);
+ category->name, xbt_log_priority_names[category->threshold], category->threshold);
}
category->initialized = 1;
/* if the category is initialized, unlink from current parent */
if (cat->initialized) {
-
xbt_log_category_t *cpp = &cat->parent->firstChild;
while (*cpp != cat && *cpp != NULL) {
static void _set_inherited_thresholds(xbt_log_category_t cat)
{
-
xbt_log_category_t child = cat->firstChild;
for (; child != NULL; child = child->nextSibling) {
if (child->isThreshInherited) {
if (cat != &_XBT_LOGV(log))
XBT_VERB("Set category threshold of %s to %s (=%d)",
- child->name, xbt_log_priority_names[cat->threshold],
- cat->threshold);
+ child->name, xbt_log_priority_names[cat->threshold], cat->threshold);
child->threshold = cat->threshold;
_set_inherited_thresholds(child);
}
}
-void xbt_log_threshold_set(xbt_log_category_t cat,
- e_xbt_log_priority_t threshold)
+void xbt_log_threshold_set(xbt_log_category_t cat, e_xbt_log_priority_t threshold)
{
cat->threshold = threshold;
cat->isThreshInherited = 0;
_set_inherited_thresholds(cat);
-
}
static xbt_log_setting_t _xbt_log_parse_setting(const char *control_string)
set->thresh = (e_xbt_log_priority_t) i;
} else {
THROWF(arg_error, 0,
- "Unknown priority name: %s (must be one of: trace,debug,verbose,info,warning,error,critical)",
- eq + 1);
+ "Unknown priority name: %s (must be one of: trace,debug,verbose,info,warning,error,critical)", eq + 1);
}
free(neweq);
} else if (!strncmp(dot + 1, "add", (size_t) (eq - dot - 1)) ||
!strncmp(dot + 1, "additivity", (size_t) (eq - dot - 1))) {
-
char *neweq = xbt_strdup(eq + 1);
char *p = neweq - 1;
*p -= 'a' - 'A';
}
}
- if (!strcmp(neweq, "ON") || !strcmp(neweq, "YES")
- || !strcmp(neweq, "1")) {
+ if (!strcmp(neweq, "ON") || !strcmp(neweq, "YES") || !strcmp(neweq, "1")) {
set->additivity = 1;
} else {
set->additivity = 0;
free(neweq);
} else if (!strncmp(dot + 1, "app", (size_t) (eq - dot - 1)) ||
!strncmp(dot + 1, "appender", (size_t) (eq - dot - 1))) {
-
char *neweq = xbt_strdup(eq + 1);
if (!strncmp(neweq, "file:", 5)) {
} else {
char buff[512];
snprintf(buff, MIN(512, eq - dot), "%s", dot + 1);
- THROWF(arg_error, 0, "Unknown setting of the log category: '%s'",
- buff);
+ THROWF(arg_error, 0, "Unknown setting of the log category: '%s'", buff);
}
set->catname = (char *) xbt_malloc(dot - name + 1);
return set;
}
-static xbt_log_category_t _xbt_log_cat_searchsub(xbt_log_category_t cat,
- char *name)
+static xbt_log_category_t _xbt_log_cat_searchsub(xbt_log_category_t cat, char *name)
{
xbt_log_category_t child, res;
*
* ( [category] "." [keyword] ":" value (" ")... )...
*
- * where [category] is one the category names (see \ref XBT_log_cats for
- * a complete list of the ones defined in the SimGrid library)
- * and keyword is one of the following:
+ * where [category] is one the category names (see \ref XBT_log_cats for a complete list of the ones defined in the
+ * SimGrid library) and keyword is one of the following:
*
* - thres: category's threshold priority. Possible values:
* TRACE,DEBUG,VERBOSE,INFO,WARNING,ERROR,CRITICAL
- * - add or additivity: whether the logging actions must be passed to
- * the parent category.
+ * - add or additivity: whether the logging actions must be passed to the parent category.
* Possible values: 0, 1, no, yes, on, off.
* Default value: yes.
* - fmt: the format to use. See \ref log_use_conf_fmt for more information.
- * - app or appender: the appender to use. See \ref log_use_conf_app for more
- * information.
- *
+ * - app or appender: the appender to use. See \ref log_use_conf_app for more information.
*/
void xbt_log_control_set(const char *control_string)
{
}
/* some initialization if this is the first time that this get called */
if (xbt_log_settings == NULL)
- xbt_log_settings = xbt_dynar_new(sizeof(xbt_log_setting_t),
- _free_setting);
+ xbt_log_settings = xbt_dynar_new(sizeof(xbt_log_setting_t), _free_setting);
/* split the string, and remove empty entries */
set_strings = xbt_str_split_quoted(control_string);
xbt_log_category_t cat = NULL;
set = _xbt_log_parse_setting(str);
- cat =
- _xbt_log_cat_searchsub(&_XBT_LOGV(XBT_LOG_ROOT_CAT), set->catname);
+ cat = _xbt_log_cat_searchsub(&_XBT_LOGV(XBT_LOG_ROOT_CAT), set->catname);
if (cat) {
XBT_DEBUG("Apply directly");
_xbt_log_cat_apply_set(cat, set);
_free_setting((void *) &set);
} else {
-
XBT_DEBUG("Store for further application");
XBT_DEBUG("push %p to the settings", (void *) set);
xbt_dynar_push(xbt_log_settings, &set);
{
#define _xbt_log_cat_init(a, b) (0)
if (!cat->appender) {
- XBT_VERB
- ("No appender to category %s. Setting the file appender as default",
- cat->name);
+ XBT_VERB ("No appender to category %s. Setting the file appender as default", cat->name);
xbt_log_appender_set(cat, xbt_log_appender_file_new(NULL));
}
if (cat->layout) {
return strcmp(a->name, b->name);
}
-static void xbt_log_help_categories_rec(xbt_log_category_t category,
- const char *prefix)
+static void xbt_log_help_categories_rec(xbt_log_category_t category, const char *prefix)
{
char *this_prefix;
char *child_prefix;
};
struct xbt_log_layout_s {
- int (*do_layout) (xbt_log_layout_t l,
- xbt_log_event_t event, const char *fmt);
+ int (*do_layout) (xbt_log_layout_t l, xbt_log_event_t event, const char *fmt);
void (*free_) (xbt_log_layout_t l);
void *data;
};
*
* Programatically alter a category's parent (don't use).
*/
-XBT_PUBLIC(void) xbt_log_parent_set(xbt_log_category_t cat,
- xbt_log_category_t parent);
+XBT_PUBLIC(void) xbt_log_parent_set(xbt_log_category_t cat, xbt_log_category_t parent);
#endif /* LOG_PRIVATE_H */
/** Implementation note on the mallocators:
*
- * Mallocators and memory mess introduced by model-checking do not mix well
- * together: the mallocator will give standard memory when we are using raw
- * memory (so these blocks are killed on restore) and the contrary (so these
+ * Mallocators and memory mess introduced by model-checking do not mix well together: the mallocator will give
+ * standard memory when we are using raw memory (so these blocks are killed on restore) and the contrary (so these
* blocks will leak across restores).
*
- * In addition, model-checking is activated when the command-line arguments
- * are parsed, at the beginning of main, while most of the mallocators are
- * created during the constructor functions launched from xbt_preinit, before
- * the beginning of the main function.
+ * In addition, model-checking is activated when the command-line arguments are parsed, at the beginning of main, while
+ * most of the mallocators are created during the constructor functions launched from xbt_preinit, before the beginning
+ * of the main function.
*
- * We want the code as fast as possible when they are active while we can deal
- * with a little slow-down when they are inactive. So we start the mallocators
- * as inactive. When they are so, they check at each use whether they should
- * switch to the fast active mode or should stay in inactive mode.
- * Finally, we give external elements a way to switch them
- * all to the active mode (through xbt_mallocator_initialization_is_done).
+ * We want the code as fast as possible when they are active while we can deal with a little slow-down when they are
+ * inactive. So we start the mallocators as inactive. When they are so, they check at each use whether they should
+ * switch to the fast active mode or should stay in inactive mode. Finally, we give external elements a way to switch
+ * them all to the active mode (through xbt_mallocator_initialization_is_done).
*
- * This design avoids to store all mallocators somewhere for later conversion,
- * which would be hard to achieve provided that all our data structures use
- * some mallocators internally...
+ * This design avoids to store all mallocators somewhere for later conversion, which would be hard to achieve provided
+ * that all our data structures use some mallocators internally...
*/
/* Value != 0 when the framework configuration is done. Value > 1 if the
}
/**
- * This function must be called once the framework configuration is done. If not,
- * mallocators will never get used. Check the implementation notes in
- * src/xbt/mallocator.c for the justification of this.
+ * This function must be called once the framework configuration is done. If not, mallocators will never get used.
+ * Check the implementation notes in src/xbt/mallocator.c for the justification of this.
*
- * For example, surf_config uses this function to tell to the mallocators that
- * the simgrid
- * configuration is now finished and that it can create them if not done yet */
+ * For example, surf_config uses this function to tell to the mallocators that the simgrid configuration is now
+ * finished and that it can create them if not done yet */
void xbt_mallocator_initialization_is_done(int protect)
{
initialization_done = protect ? 2 : 1;
/**
* \brief Constructor
- * \param size size of the internal stack: number of objects the mallocator
- * will be able to store
- * \param new_f function to allocate a new object of your datatype, called
- * in \a xbt_mallocator_get() when the mallocator is empty
- * \param free_f function to free an object of your datatype, called
- * in \a xbt_mallocator_release() when the stack is full, and when
- * the mallocator is freed.
- * \param reset_f function to reinitialise an object of your datatype, called
- * when you extract an object from the mallocator (can be NULL)
+ * \param size size of the internal stack: number of objects the mallocator will be able to store
+ * \param new_f function to allocate a new object of your datatype, called in \a xbt_mallocator_get() when the
+ * mallocator is empty
+ * \param free_f function to free an object of your datatype, called in \a xbt_mallocator_release() when the stack is
+ * full, and when the mallocator is freed.
+ * \param reset_f function to reinitialise an object of your datatype, called when you extract an object from the
+ * mallocator (can be NULL)
*
* Create and initialize a new mallocator for a given datatype.
*
* \return pointer to the created mallocator
* \see xbt_mallocator_free()
*/
-xbt_mallocator_t xbt_mallocator_new(int size,
- pvoid_f_void_t new_f,
- void_f_pvoid_t free_f,
- void_f_pvoid_t reset_f)
+xbt_mallocator_t xbt_mallocator_new(int size, pvoid_f_void_t new_f, void_f_pvoid_t free_f, void_f_pvoid_t reset_f)
{
xbt_mallocator_t m;
xbt_assert(new_f != NULL && free_f != NULL, "invalid parameter");
m = xbt_new0(s_xbt_mallocator_t, 1);
- XBT_VERB("Create mallocator %p (%s)",
- m, xbt_mallocator_is_active() ? "enabled" : "disabled");
+ XBT_VERB("Create mallocator %p (%s)", m, xbt_mallocator_is_active() ? "enabled" : "disabled");
m->current_size = 0;
m->new_f = new_f;
m->free_f = free_f;
/** \brief Destructor
* \param m the mallocator you want to destroy
*
- * Destroy the mallocator and all its data. The function
- * free_f is called on each object in the mallocator.
+ * Destroy the mallocator and all its data. The function free_f is called on each object in the mallocator.
*
* \see xbt_mallocator_new()
*/
void xbt_mallocator_free(xbt_mallocator_t m)
{
-
int i;
xbt_assert(m != NULL, "Invalid parameter");
- XBT_VERB("Frees mallocator %p (size:%d/%d)", m, m->current_size,
- m->max_size);
+ XBT_VERB("Frees mallocator %p (size:%d/%d)", m, m->current_size, m->max_size);
for (i = 0; i < m->current_size; i++) {
m->free_f(m->objects[i]);
}
*
* Remove an object from the mallocator and return it.
* This function is designed to be used instead of malloc().
- * If the mallocator is not empty, an object is
- * extracted from the mallocator and no malloc is done.
+ * If the mallocator is not empty, an object is extracted from the mallocator and no malloc is done.
*
- * If the mallocator is empty, a new object is created,
- * by calling the function new_f().
+ * If the mallocator is empty, a new object is created, by calling the function new_f().
*
* In both cases, the function reset_f() (if defined) is called on the object.
*
/* No object is ready yet. Create a bunch of them to try to group the
* mallocs on the same memory pages (to help the cache lines) */
- /* XBT_DEBUG("Create a new object for mallocator %p (size:%d/%d)", */
- /* m, m->current_size, m->max_size); */
+ /* XBT_DEBUG("Create a new object for mallocator %p (size:%d/%d)", m, m->current_size, m->max_size); */
int i;
int amount = MIN(m->max_size / 2, 1000);
for (i = 0; i < amount; i++)
}
/* there is at least an available object, now */
- /* XBT_DEBUG("Reuse an old object for mallocator %p (size:%d/%d)", */
- /* m, m->current_size, m->max_size); */
+ /* XBT_DEBUG("Reuse an old object for mallocator %p (size:%d/%d)", m, m->current_size, m->max_size); */
object = m->objects[--m->current_size];
lock_release(m);
} else {
*
* Push into the mallocator an object you don't need anymore.
* This function is designed to be used instead of free().
- * If the mallocator is not full, your object if stored into
- * the mallocator and no free is done.
- * If the mallocator is full, the object is freed by calling
- * the function free_f().
+ * If the mallocator is not full, your object if stored into the mallocator and no free is done.
+ * If the mallocator is full, the object is freed by calling the function free_f().
*
* \see xbt_mallocator_get()
*/
lock_acquire(m);
if (m->current_size < m->max_size) {
/* there is enough place to push the object */
- /* XBT_DEBUG
- ("Store deleted object in mallocator %p for further use (size:%d/%d)",
+ /* XBT_DEBUG("Store deleted object in mallocator %p for further use (size:%d/%d)",
m, m->current_size, m->max_size); */
m->objects[m->current_size++] = object;
lock_release(m);
} else {
lock_release(m);
/* otherwise we don't have a choice, we must free the object */
- /* XBT_DEBUG("Free deleted object: mallocator %p is full (size:%d/%d)", m,
- m->current_size, m->max_size); */
+ /* XBT_DEBUG("Free deleted object: mallocator %p is full (size:%d/%d)", m, m->current_size, m->max_size); */
m->free_f(object);
}
} else {
#include "memory_map.hpp"
extern "C" {
-
-XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_memory_map, xbt,
- "Logging specific to algorithms for memory_map");
-
+XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_memory_map, xbt, "Logging specific to algorithms for memory_map");
}
namespace simgrid {
FILE *fp = std::fopen(path, "r");
if(fp == NULL)
std::perror("fopen failed");
- xbt_assert(fp,
- "Cannot open %s to investigate the memory map of the process.", path);
+ xbt_assert(fp, "Cannot open %s to investigate the memory map of the process.", path);
free(path);
setbuf(fp, NULL);
/* Wipeout the new line character */
line[read - 1] = '\0';
- /* Tokenize the line using spaces as delimiters and store each token */
- /* in lfields array. We expect 5 tokens/fields */
+ /* Tokenize the line using spaces as delimiters and store each token in lfields array. We expect 5 tokens/fields */
char* lfields[6];
lfields[0] = strtok(line, " ");
if (lfields[1][4] == 'p')
memreg.flags |= MAP_PRIVATE;
-
else if (lfields[1][4] == 's')
memreg.flags |= MAP_SHARED;
/* Create space for a new map region in the region's array and copy the */
/* parsed stuff from the temporal memreg variable */
- XBT_DEBUG("Found region for %s",
- !memreg.pathname.empty() ? memreg.pathname.c_str() : "(null)");
+ XBT_DEBUG("Found region for %s", !memreg.pathname.empty() ? memreg.pathname.c_str() : "(null)");
ret.push_back(std::move(memreg));
}
std::fclose(fp);
return ret;
#else
- /* On FreeBSD, kinfo_getvmmap() could be used but mmap() support is disabled
- anyway. */
+ /* On FreeBSD, kinfo_getvmmap() could be used but mmap() support is disabled anyway. */
xbt_die("Could not get memory map from process %lli", (long long int) pid);
#endif
}
* \param fun the function to call in parallel
* \param data each element of this dynar will be passed as an argument to fun
*/
-int xbt_parmap_mc_apply(xbt_parmap_t parmap, int_f_pvoid_pvoid_t fun,
- void* data, unsigned int length, void* ref_snapshot)
+int xbt_parmap_mc_apply(xbt_parmap_t parmap, int_f_pvoid_pvoid_t fun, void* data, unsigned int length,
+ void* ref_snapshot)
{
/* Assign resources to worker threads */
parmap->snapshot_compare = fun;
/**
* \brief Ends the parmap: wakes the controller thread when all workers terminate.
*
- * This function is called by all worker threads when they end (not including
- * the controller).
+ * This function is called by all worker threads when they end (not including the controller).
*
* \param parmap a parmap
*/
/**
* \brief Waits for some work to process.
*
- * This function is called by each worker thread (not including the controller)
- * when it has no more work to do.
+ * This function is called by each worker thread (not including the controller) when it has no more work to do.
*
* \param parmap a parmap
* \param round the expected round number
/**
* \brief Ends the parmap: wakes the controller thread when all workers terminate.
*
- * This function is called by all worker threads when they end (not including
- * the controller).
+ * This function is called by all worker threads when they end (not including the controller).
*
* \param parmap a parmap
*/
/**
* \brief Waits for some work to process.
*
- * This function is called by each worker thread (not including the controller)
- * when it has no more work to do.
+ * This function is called by each worker thread (not including the controller) when it has no more work to do.
*
* \param parmap a parmap
* \param round the expected round number
/**
* \brief Waits for some work to process.
*
- * This function is called by each worker thread (not including the controller)
- * when it has no more work to do.
+ * This function is called by each worker thread (not including the controller) when it has no more work to do.
*
* \param parmap a parmap
* \param round the expected round number
/**
* \param swag poor victim
*
- * kilkil a swag but not it's content. If you do not understand why
- * xbt_swag_free should not free its content, don't use swags.
+ * kilkil a swag but not it's content. If you do not understand why xbt_swag_free should not free its content,
+ * don't use swags.
*/
inline void xbt_swag_free(xbt_swag_t swag)
{
* \param obj the objet to insert in the swag
* \param swag a swag
*
- * insert (at the head... you probably had a very good reason to do
- * that, I hope you know what you're doing) \a obj in \a swag
+ * insert (at the head... you probably had a very good reason to do that, I hope you know what you're doing) \a obj in
+ * \a swag
*/
inline void xbt_swag_insert_at_head(void *obj, xbt_swag_t swag)
{
swag->head = obj;
swag->tail = obj;
swag->count++;
- }
- else if (obj != swag->head && !xbt_swag_getPrev(obj, swag->offset)) {
+ } else if (obj != swag->head && !xbt_swag_getPrev(obj, swag->offset)) {
xbt_swag_getNext(obj, swag->offset) = swag->head;
xbt_swag_getPrev(swag->head, swag->offset) = obj;
swag->head = obj;
* \param obj the objet to insert in the swag
* \param swag a swag
*
- * insert (at the tail... you probably had a very good reason to do
- * that, I hope you know what you're doing) \a obj in \a swag
+ * insert (at the tail... you probably had a very good reason to do that, I hope you know what you're doing) \a obj in
+ * \a swag
*/
inline void xbt_swag_insert_at_tail(void *obj, xbt_swag_t swag)
{
swag->head = obj;
swag->tail = obj;
swag->count++;
- }
- else if (obj != swag->tail && !xbt_swag_getNext(obj, swag->offset)) {
+ } else if (obj != swag->tail && !xbt_swag_getNext(obj, swag->offset)) {
xbt_swag_getPrev(obj, swag->offset) = swag->tail;
xbt_swag_getNext(swag->tail, swag->offset) = obj;
swag->tail = obj;
if (next) {
xbt_swag_getPrev(next, offset) = prev;
xbt_swag_getNext(obj, offset) = NULL;
- }
- else {
+ } else {
swag->tail = prev;
}
swag->count--;
- }
- else if (next) {
+ } else if (next) {
xbt_swag_getPrev(next, offset) = NULL;
xbt_swag_getNext(obj, offset) = NULL;
swag->head = next;
swag->count--;
- }
- else if (obj == swag->head) {
+ } else if (obj == swag->head) {
swag->head = swag->tail = NULL;
swag->count--;
}
return (swag->count);
}
-
#ifdef SIMGRID_TEST
XBT_TEST_SUITE("swag", "Swag data container");
obj2->name = "Obj 2";
xbt_test_add("Basic usage");
- xbt_test_log("%p %p %ld\n", obj1, &(obj1->setB),
- (long) ((char *) &(obj1->setB) - (char *) obj1));
+ xbt_test_log("%p %p %ld\n", obj1, &(obj1->setB), (long) ((char *) &(obj1->setB) - (char *) obj1));
setA = xbt_swag_new(xbt_swag_offset(*obj1, setA));
setB = xbt_swag_new(xbt_swag_offset(*obj1, setB));
xbt_free(obj1);
xbt_free(obj2);
}
-
#endif /* SIMGRID_TEST */
#define APPEND2_END_TOKEN_CLEAR "\n "
static void open_append2_file(xbt_log_append2_file_t data){
- if(data->count<0)
- {
+ if(data->count<0) {
//Roll
if(!data->file)
data->file= fopen(data->filename, "w");
fputs(APPEND2_END_TOKEN_CLEAR,data->file);
fseek(data->file,0,SEEK_SET);
}
- }
- else{
+ } else{
//printf("Splitting\n");
//Split
if(data->file)
data->count++;
data->file= fopen(newname, "w");
xbt_assert(data->file);
-
}
}
-
-
-
static void append2_file(xbt_log_appender_t this_, char *str) {
xbt_log_append2_file_t d=(xbt_log_append2_file_t) this_->data;
xbt_assert(d->file);
- if(ftell(d->file)>=d->limit)
- {
+ if(ftell(d->file)>=d->limit) {
open_append2_file(d);
}
fputs(str, d->file);
if(d->count<0){
- fputs(APPEND2_END_TOKEN,d->file);
- fseek(d->file,-((signed long)strlen(APPEND2_END_TOKEN)),SEEK_CUR);
+ fputs(APPEND2_END_TOKEN,d->file);
+ fseek(d->file,-((signed long)strlen(APPEND2_END_TOKEN)),SEEK_CUR);
}
}
res->data = data;
return res;
}
-
#define show_int(data) show_it(data, "d")
#define show_double(data) show_it(data, "f")
-static int xbt_log_layout_format_doit(xbt_log_layout_t l,
- xbt_log_event_t ev,
- const char *msg_fmt)
+static int xbt_log_layout_format_doit(xbt_log_layout_t l, xbt_log_event_t ev, const char *msg_fmt)
{
char *p = ev->buffer;
int rem_size = ev->buffer_size;
length = strtol(q, &q, 10);
goto handle_modifier;
case 'c': /* category name; LOG4J compliant
- should accept a precision postfix to show the
- hierarchy */
+ should accept a precision postfix to show the hierarchy */
show_string(ev->cat->name);
break;
case 'p': /* priority name; LOG4J compliant */
} else \
return 0
-static int xbt_log_layout_simple_doit(xbt_log_layout_t l,
- xbt_log_event_t ev,
- const char *fmt)
+static int xbt_log_layout_simple_doit(xbt_log_layout_t l, xbt_log_event_t ev, const char *fmt)
{
char *p = ev->buffer;
int rem_size = ev->buffer_size;
/* Display the proc info if available */
procname = xbt_procname();
if (procname && strcmp(procname,"maestro")) {
- len = snprintf(p, rem_size, "%s:%s:(%d) ",
- SIMIX_host_self_get_name(), procname, xbt_getpid());
+ len = snprintf(p, rem_size, "%s:%s:(%d) ", SIMIX_host_self_get_name(), procname, xbt_getpid());
check_overflow(len);
}
else if (!procname) {
- len = snprintf(p, rem_size, "%s::(%d) ",
- SIMIX_host_self_get_name(), xbt_getpid());
+ len = snprintf(p, rem_size, "%s::(%d) ", SIMIX_host_self_get_name(), xbt_getpid());
check_overflow(len);
}
/* Display the date */
- len = snprintf(p, rem_size, "%f] ",
- surf_get_clock() - simple_begin_of_time);
+ len = snprintf(p, rem_size, "%f] ", surf_get_clock() - simple_begin_of_time);
check_overflow(len);
/* Display file position if not INFO */
if (ev->priority != xbt_log_priority_info && !xbt_log_no_loc) {
- len = snprintf(p, rem_size, "%s:%d: ",
- ev->fileName, ev->lineNum);
+ len = snprintf(p, rem_size, "%s:%d: ", ev->fileName, ev->lineNum);
check_overflow(len);
}
/* Display category name */
- len = snprintf(p, rem_size, "[%s/%s] ",
- ev->cat->name, xbt_log_priority_names[ev->priority]);
+ len = snprintf(p, rem_size, "[%s/%s] ", ev->cat->name, xbt_log_priority_names[ev->priority]);
check_overflow(len);
/* Display user-provided message */
XBT_LOG_NEW_CATEGORY(smpi, "All SMPI categories"); /* lives here even if that's a bit odd to solve linking issues: this is used in xbt_log_file_appender to detect whether SMPI is used (and thus whether we should unbench the writing to disk) */
-
char *xbt_binary_name = NULL; /* Name of the system process containing us (mandatory to retrieve neat backtraces) */
xbt_dynar_t xbt_cmdline = NULL; /* all we got in argv */
#include <windows.h>
#ifndef __GNUC__
-/* Should not be necessary but for some reason,
- * DllMain is called twice at attachment and
- * at detachment.*/
+/* Should not be necessary but for some reason, DllMain is called twice at attachment and at detachment.*/
static int xbt_dll_process_is_attached = 0;
/* see also http://msdn.microsoft.com/en-us/library/ms682583%28VS.85%29.aspx */
XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_matrix, xbt, "2D data storage");
/** \brief constructor */
-xbt_matrix_t xbt_matrix_new(int lines, int rows,
- const unsigned long elmsize,
- void_f_pvoid_t const free_f)
+xbt_matrix_t xbt_matrix_new(int lines, int rows, const unsigned long elmsize, void_f_pvoid_t const free_f)
{
xbt_matrix_t res = xbt_new(s_xbt_matrix_t, 1);
res->lines = lines;
}
/** \brief Creates a matrix being a submatrix of another one */
-xbt_matrix_t xbt_matrix_new_sub(xbt_matrix_t from,
- int lsize, int rsize,
- int lpos, int rpos,
+xbt_matrix_t xbt_matrix_new_sub(xbt_matrix_t from, int lsize, int rsize, int lpos, int rpos,
pvoid_f_pvoid_t const cpy_f)
{
-
- xbt_matrix_t res = xbt_matrix_new(lsize, rsize,
- from->elmsize, from->free_f);
+ xbt_matrix_t res = xbt_matrix_new(lsize, rsize, from->elmsize, from->free_f);
xbt_matrix_copy_values(res, from, lsize, rsize, 0, 0, lpos, rpos, cpy_f);
return res;
}
xbt_matrix_free((xbt_matrix_t) * (void **) d);
}
-
/** \brief Display the content of a matrix (debugging purpose)
* \param coords: boolean indicating whether we should add the coords of each cell to the output*/
-void xbt_matrix_dump(xbt_matrix_t matrix, const char *name, int coords,
- void_f_pvoid_t display_fun)
+void xbt_matrix_dump(xbt_matrix_t matrix, const char *name, int coords, void_f_pvoid_t display_fun)
{
unsigned int i, j;
- fprintf(stderr, ">>> Matrix %s dump (%u x %u)\n", name, matrix->lines,
- matrix->rows);
+ fprintf(stderr, ">>> Matrix %s dump (%u x %u)\n", name, matrix->lines, matrix->rows);
for (i = 0; i < matrix->lines; i++) {
fprintf(stderr, " ");
for (j = 0; j < matrix->rows; j++) {
* \param lpos_src: line offset on destination matrix
* \param rpos_src: row offset on destination matrix
*/
-void xbt_matrix_copy_values(xbt_matrix_t dst, xbt_matrix_t src,
- unsigned int lsize, unsigned int rsize,
- unsigned int lpos_dst, unsigned int rpos_dst,
- unsigned int lpos_src, unsigned int rpos_src,
+void xbt_matrix_copy_values(xbt_matrix_t dst, xbt_matrix_t src, unsigned int lsize, unsigned int rsize,
+ unsigned int lpos_dst, unsigned int rpos_dst,unsigned int lpos_src, unsigned int rpos_src,
pvoid_f_pvoid_t const cpy_f)
{
unsigned int i, j;
- XBT_DEBUG
- ("Copy a %ux%u submatrix from %ux%u(of %ux%u) to %ux%u (of %ux%u)",
- lsize, rsize, lpos_src, rpos_src, src->lines, src->rows, lpos_dst,
- rpos_dst, dst->lines, dst->rows);
+ XBT_DEBUG ("Copy a %ux%u submatrix from %ux%u(of %ux%u) to %ux%u (of %ux%u)",
+ lsize, rsize, lpos_src, rpos_src, src->lines, src->rows, lpos_dst, rpos_dst, dst->lines, dst->rows);
/* everybody knows that issue is between the chair and the screen (particulary in my office) */
xbt_assert(src->elmsize == dst->elmsize);
xbt_matrix_get_as(dst, j + lpos_dst, i + rpos_dst, void *) =
cpy_f(xbt_matrix_get_ptr(src, j + rpos_src, i + lpos_src));
} else {
- memcpy(xbt_matrix_get_ptr(dst, lpos_dst, i + rpos_dst),
- xbt_matrix_get_ptr(src, lpos_src, i + rpos_src),
+ memcpy(xbt_matrix_get_ptr(dst, lpos_dst, i + rpos_dst), xbt_matrix_get_ptr(src, lpos_src, i + rpos_src),
dst->elmsize * lsize);
}
}
-
}
/** \brief Creates a new matrix of double filled with zeros */
}
/** \brief add to C the result of A*B */
-void xbt_matrix_double_addmult(xbt_matrix_t A, xbt_matrix_t B,
- /*OUT*/ xbt_matrix_t C)
+void xbt_matrix_double_addmult(xbt_matrix_t A, xbt_matrix_t B, /*OUT*/ xbt_matrix_t C)
{
unsigned int i, j, k;
- xbt_assert(A->lines == C->lines,
- "A->lines != C->lines (%u vs %u)", A->lines, C->lines);
+ xbt_assert(A->lines == C->lines, "A->lines != C->lines (%u vs %u)", A->lines, C->lines);
xbt_assert(B->rows == C->rows);
for (i = 0; i < C->lines; i++)
for (j = 0; j < C->rows; j++)
for (k = 0; k < B->lines; k++)
- xbt_matrix_get_as(C, i, j, double) +=
- xbt_matrix_get_as(A, i, k, double) * xbt_matrix_get_as(B, k, j,
- double);
+ xbt_matrix_get_as(C, i, j, double) += xbt_matrix_get_as(A, i, k, double) * xbt_matrix_get_as(B, k, j, double);
}
*
* This is a reimplementation of the GNU getline function, so that our code don't depends on the GNU libc.
*
- * xbt_getline() reads an entire line from stream, storing the address of the
- * buffer containing the text into *buf. The buffer is null-terminated and
- * includes the newline character, if one was found.
+ * xbt_getline() reads an entire line from stream, storing the address of the buffer containing the text into *buf.
+ * The buffer is null-terminated and includes the newline character, if one was found.
*
- * If *buf is NULL, then xbt_getline() will allocate a buffer for storing the
- * line, which should be freed by the user program.
+ * If *buf is NULL, then xbt_getline() will allocate a buffer for storing the line, which should be freed by the user
+ * program.
*
- * Alternatively, before calling xbt_getline(), *buf can contain a pointer to a
- * malloc()-allocated buffer *n bytes in size. If the buffer is not large
- * enough to hold the line, xbt_getline() resizes it with realloc(), updating
+ * Alternatively, before calling xbt_getline(), *buf can contain a pointer to a malloc()-allocated buffer *n bytes in
+ * size. If the buffer is not large enough to hold the line, xbt_getline() resizes it with realloc(), updating
* *buf and *n as necessary.
*
- * In either case, on a successful call, *buf and *n will be updated to reflect
- * the buffer address and allocated size respectively.
+ * In either case, on a successful call, *buf and *n will be updated to reflect the buffer address and allocated size
+ * respectively.
*/
ssize_t xbt_getline(char **buf, size_t *n, FILE *stream)
{
#include "simgrid/simix.h" /* used implementation */
#include "../simix/smx_private.h" /* FIXME */
-XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync, xbt,
- "Synchronization mechanism");
+XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync, xbt, "Synchronization mechanism");
/****** mutex related functions ******/
struct s_xbt_mutex_ {
return bar;
}
-
int xbt_barrier_wait(xbt_bar_t bar)
{
int ret=0;
xbt_cond_wait(bar->cond, bar->mutex);
xbt_mutex_release(bar->mutex);
}
-
return ret;
}
xbt_cond_destroy(bar->cond);
xbt_free(bar);
}
-
XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt, "Synchronization mechanism (OS-level)");
-
/* use named sempahore when sem_init() does not work */
#if !HAVE_SEM_INIT
static int next_sem_ID = 0;
if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
THROWF(system_error, errcode,
"Impossible to set the SimGrid identity descriptor to the main thread (pthread_setspecific failed)");
-
+
__xbt_running_ctx_fetch = _os_thread_get_running_ctx;
__xbt_ex_terminate = _os_thread_ex_terminate;
return res;
}
-
xbt_os_thread_t xbt_os_thread_create(const char *name, pvoid_f_pvoid_t start_routine, void *param, void *extra_data)
{
xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
xbt_assert(errcode==0 , "pthread_key_create failed");
}
-void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
-
+void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value)
+{
int errcode = pthread_setspecific(key, value);
xbt_assert(errcode==0, "pthread_setspecific failed");
}
-void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
+void* xbt_os_thread_get_specific(xbt_os_thread_key_t key)
+{
return pthread_getspecific(key);
}
{
#if HAVE_SEM_INIT
if (sem_destroy(sem->ps) < 0)
- THROWF(system_error, errno, "sem_destroy() failed: %s",
- strerror(errno));
+ THROWF(system_error, errno, "sem_destroy() failed: %s", strerror(errno));
#else
if (sem_close(sem->ps) < 0)
THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
xbt_free(sem->name);
-
#endif
xbt_free(sem);
}
strerror(errno));
}
-
/** @brief Returns the amount of cores on the current host */
int xbt_os_get_numcores(void) {
#ifdef WIN32
#endif
}
-/* TSC (tick-level) timers are said to be unreliable on SMP hosts and thus
- disabled in SDL source code */
-
+/* TSC (tick-level) timers are said to be unreliable on SMP hosts and thus disabled in SDL source code */
/* \defgroup XBT_sysdep All system dependency
- * \brief This section describes many macros/functions that can serve as
- * an OS abstraction.
+ * \brief This section describes many macros/functions that can serve as an OS abstraction.
*/
-
-
struct s_xbt_os_timer {
#if HAVE_POSIX_GETTIME
struct timespec start, stop, elapse;
double xbt_os_timer_elapsed(xbt_os_timer_t timer)
{
#if HAVE_POSIX_GETTIME
- return ((double) timer->stop.tv_sec) - ((double) timer->start.tv_sec) +
- ((double) timer->elapse.tv_sec ) +
- ((((double) timer->stop.tv_nsec) -
- ((double) timer->start.tv_nsec) + ((double) timer->elapse.tv_nsec )) / 1e9);
+ return ((double) timer->stop.tv_sec) - ((double) timer->start.tv_sec) + ((double) timer->elapse.tv_sec ) +
+ ((((double) timer->stop.tv_nsec) - ((double) timer->start.tv_nsec) + ((double) timer->elapse.tv_nsec )) / 1e9);
#elif HAVE_GETTIMEOFDAY || defined(_WIN32)
- return ((double) timer->stop.tv_sec) - ((double) timer->start.tv_sec)
- + ((double) timer->elapse.tv_sec ) +
- ((((double) timer->stop.tv_usec) -
- ((double) timer->start.tv_usec) + ((double) timer->elapse.tv_usec )) / 1000000.0);
+ return ((double) timer->stop.tv_sec) - ((double) timer->start.tv_sec) + ((double) timer->elapse.tv_sec ) +
+ ((((double) timer->stop.tv_usec) - ((double) timer->start.tv_usec) + ((double) timer->elapse.tv_usec )) /
+ 1000000.0);
#else
- return (double) timer->stop - (double) timer->start + (double)
- timer->elapse;
+ return (double) timer->stop - (double) timer->start + (double) timer->elapse;
#endif
}
char **evt;
while ((evt = action_get_action(argv[0]))) {
char* lowername = str_tolower (evt[1]);
- action_fun function =
- (action_fun)xbt_dict_get(xbt_action_funs, lowername);
+ action_fun function = (action_fun)xbt_dict_get(xbt_action_funs, lowername);
xbt_free(lowername);
TRY{
function((const char **)evt);
- }
- CATCH(e) {
+ } CATCH(e) {
free(evt);
xbt_die("Replay error :\n %s", e.msg);
}
const char **evt;
xbt_assert(argc >= 2,
"No '%s' agent function provided, no simulation-wide trace file provided, "
- "and no process-wide trace file provided in deployment file. Aborting.",
- argv[0]
+ "and no process-wide trace file provided in deployment file. Aborting.", argv[0]
);
xbt_replay_reader_t reader = xbt_replay_reader_new(argv[1]);
while ((evt=xbt_replay_reader_get(reader))) {
xbt_free(lowername);
TRY{
function(evt);
- }
- CATCH(e) {
+ } CATCH(e) {
free(evt);
xbt_die("Replay error on line %d of file %s :\n %s" , reader->linenum,reader->filename, e.msg);
}
return 0;
}
-
static char **action_get_action(char *name)
{
xbt_dynar_t evt = NULL;
xbt_dynar_t myqueue = xbt_dict_get_or_null(xbt_action_queues, name);
if (myqueue == NULL || xbt_dynar_is_empty(myqueue)) { // nothing stored for me. Read the file further
-
if (xbt_action_fp == NULL) { // File closed now. There's nothing more to read. I'm out of here
goto todo_done;
}
xbt_dynar_t otherqueue =
xbt_dict_get_or_null(xbt_action_queues, evtname);
if (otherqueue == NULL) { // Damn. Create the queue of that guy
- otherqueue =
- xbt_dynar_new(sizeof(xbt_dynar_t), xbt_dynar_free_voidp);
+ otherqueue = xbt_dynar_new(sizeof(xbt_dynar_t), xbt_dynar_free_voidp);
xbt_dict_set(xbt_action_queues, evtname, otherqueue, NULL);
}
xbt_dynar_push(otherqueue, &evt);
return xbt_dynar_to_array(evt);
}
-
// I did all my actions for me in the file (either I closed the file, or a colleague did)
// Let's cleanup before leaving
todo_done:
*
* @param s The string to strip. Modified in place.
* @param char_list A string which contains the characters you want to strip.
- *
*/
void xbt_str_rtrim(char *s, const char *char_list)
{
*
* @param s The string to strip. Modified in place.
* @param char_list A string which contains the characters you want to strip.
- *
*/
void xbt_str_ltrim(char *s, const char *char_list)
{
*
* @param s The string to strip.
* @param char_list A string which contains the characters you want to strip.
- *
*/
void xbt_str_trim(char *s, const char *char_list)
{
-
if (!s)
return;
*
* If the variable name contains spaces, use the brace version (ie, ${toto tutu})
*
- * You can provide a default value to use if the variable is not set in the dict by using
- * '${var:=default}' or '${var:-default}'. These two forms are equivalent, even if they
- * shouldn't to respect the shell standard (:= form should set the value in the dict,
- * but does not) (BUG).
+ * You can provide a default value to use if the variable is not set in the dict by using '${var:=default}' or
+ * '${var:-default}'. These two forms are equivalent, even if they shouldn't to respect the shell standard (:= form
+ * should set the value in the dict, but does not) (BUG).
*/
-
char *xbt_str_varsubst(const char *str, xbt_dict_t patterns)
{
xbt_strbuff_t buff = xbt_strbuff_new_from(str);
* - "\0" (ASCII 0 (0x00)) NULL.
* - "\x0B" (ASCII 11 (0x0B)) vertical tab.
*/
-
xbt_dynar_t xbt_str_split(const char *s, const char *sep)
{
xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
*
* The string passed as argument must be writable (not const)
* The elements of the dynar are just parts of the string passed as argument.
- * So if you don't store that argument elsewhere, you should free it in addition
- * to freeing the dynar. This can be done by simply freeing the first argument
- * of the dynar:
+ * So if you don't store that argument elsewhere, you should free it in addition to freeing the dynar. This can be done
+ * by simply freeing the first argument of the dynar:
* free(xbt_dynar_get_ptr(dynar,0));
*
- * Actually this function puts a bunch of \0 in the memory area you passed as
- * argument to separate the elements, and pushes the address of each chunk
- * in the resulting dynar. Yes, that's uneven. Yes, that's gory. But that's efficient.
+ * Actually this function puts a bunch of \0 in the memory area you passed as argument to separate the elements, and
+ * pushes the address of each chunk in the resulting dynar. Yes, that's uneven. Yes, that's gory. But that's efficient.
*/
xbt_dynar_t xbt_str_split_quoted_in_place(char *s) {
xbt_dynar_t res = xbt_dynar_new(sizeof(char *), NULL);
end = beg;
while (!done) {
-
-
switch (*end) {
case '\\':
ctn = 1;
THROWF(arg_error, 0, "String ends with \\");
end++; /* Pass the protected char */
break;
-
case '\'':
ctn = 1;
if (!in_double_quote) {
end++;
}
break;
-
case ' ':
case '\t':
case '\n':
case '\0':
if (*end == '\0' && (in_simple_quote || in_double_quote)) {
- THROWF(arg_error, 0,
- "End of string found while searching for %c in %s",
- (in_simple_quote ? '\'' : '"'), s);
+ THROWF(arg_error, 0, "End of string found while searching for %c in %s", (in_simple_quote ? '\'' : '"'), s);
}
if (in_simple_quote || in_double_quote) {
end++;
end = beg;
}
break;
-
default:
ctn = 1;
end++;
/** @brief Splits a string into a dynar of strings, taking quotes into account
*
- * It basically does the same argument separation than the shell, where white
- * spaces can be escaped and where arguments are never split within a
- * quote group.
+ * It basically does the same argument separation than the shell, where white spaces can be escaped and where arguments
+ * are never split within a quote group.
* Several subsequent spaces are ignored (unless within quotes, of course).
* You may want to trim the input string, if you want to avoid empty entries
- *
*/
-
xbt_dynar_t xbt_str_split_quoted(const char *s)
{
xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
}
return res;
}
+
/** @brief Join a set of strings as a single string
*
* The parameter must be a NULL-terminated array of chars,
return res;
}
-/** @brief creates a new string containing what can be read on a fd
- *
- */
+/** @brief creates a new string containing what can be read on a fd */
char *xbt_str_from_file(FILE * file)
{
xbt_strbuff_t buff = xbt_strbuff_new();
return res;
}
+
/** @brief Parse a double out of a string, or raise an error
*
* The #str is passed as argument to your #error_msg, as follows:
mytest("Empty", "", "");
mytest("Basic test", "toto tutu", "totoXXXtutu");
- mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u",
- "totoXXXtutu");
+ mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u", "totoXXXtutu");
mytest("Protected space", "toto\\ tutu", "toto tutu");
mytest("Several spaces", "toto tutu", "totoXXXtutu");
mytest("LTriming", " toto tatu", "totoXXXtatu");
mytest("Single quotes", "'toto tutu' tata", "toto tutuXXXtata");
mytest("Double quotes", "\"toto tutu\" tata", "toto tutuXXXtata");
mytest("Mixed quotes", "\"toto' 'tutu\" tata", "toto' 'tutuXXXtata");
- mytest("Backslashed quotes", "\\'toto tutu\\' tata",
- "'totoXXXtutu'XXXtata");
- mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata",
- "toto 'tutuXXXtata");
-
+ mytest("Backslashed quotes", "\\'toto tutu\\' tata", "'totoXXXtutu'XXXtata");
+ mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata", "toto 'tutuXXXtata");
}
#define mytest_str(name, input, separator, expected) \
test_parse_error(xbt_str_parse_double, "Parse '' as a double", rdouble, "");
test_parse_error(xbt_str_parse_double, "Parse cruft as a double", rdouble, "cruft");
}
-
#endif /* SIMGRID_TEST */
XBT_LOG_NEW_DEFAULT_SUBCATEGORY(strbuff, xbt, "String buffers");
-/**
-** Buffer code
-**/
-
inline void xbt_strbuff_empty(xbt_strbuff_t b)
{
b->used = 0;
*
* If the variable name contains spaces, use the brace version (ie, ${toto tutu})
*
- * You can provide a default value to use if the variable is not set in the dict by using
- * '${var:=default}' or '${var:-default}'. These two forms are equivalent, even if they
- * shouldn't to respect the shell standard (:= form should set the value in the dict,
- * but does not) (BUG).
+ * You can provide a default value to use if the variable is not set in the dict by using '${var:=default}' or
+ * '${var:-default}'. These two forms are equivalent, even if they shouldn't to respect the shell standard (:= form
+ * should set the value in the dict, but does not) (BUG).
*/
void xbt_strbuff_varsubst(xbt_strbuff_t b, xbt_dict_t patterns)
{
-
char *end; /* pointers around the parsed chunk */
int in_simple_quote = 0, in_double_quote = 0;
int done = 0;
end++;
xbt_assert(*end != '\0', "String ends with \\");
break;
-
case '\'':
if (!in_double_quote) {
/* simple quote not protected by double ones, note it */
in_double_quote = !in_double_quote;
}
break;
-
case '$':
if (!in_simple_quote) {
/* Go for the substitution. First search the variable name */
int val_len;
beg_subst = end;
-
if (*(++end) == '{') {
/* the variable name is enclosed in braces. */
beg_var = end + 1;
default_value[p - end_var - 2] = '\0';
end_subst = p + 1; /* eat '}' */
-
break;
}
end_var++;
end_subst = end_var + 1; /* also kill the } in the name */
xbt_assert(end_var != beg_var, "Variable name empty (${} is not valid)");
-
-
} else {
/* name given directly */
beg_var = end;
end_var = beg_var;
- while (*end_var != '\0' && *end_var != ' ' && *end_var != '\t'
- && *end_var != '\n')
+ while (*end_var != '\0' && *end_var != ' ' && *end_var != '\t' && *end_var != '\n')
end_var++;
end_subst = end_var;
xbt_assert (end_var != beg_var, "Variable name empty ($ is not valid)");
if (val_len <= end_subst - beg_subst) {
/* enough room to do the substitute in place */
memmove(beg_subst, value, val_len); /* substitute */
- memmove(beg_subst + val_len, end_subst, b->used - (end_subst - b->data) + 1); /* move the end of the string closer */
+ /* move the end of the string closer */
+ memmove(beg_subst + val_len, end_subst, b->used - (end_subst - b->data) + 1);
// XBT_DEBUG("String is now: '%s'",b->data);
end = beg_subst + val_len; /* update the currently explored char in the overall loop */
// XBT_DEBUG("end of substituted section is now '%s'",end);
int tooshort = val_len - (end_subst - beg_subst) + 1 /* don't forget \0 */ ;
int newused = b->used + tooshort;
end += tooshort; /* update the pointer of the overall loop */
-// XBT_DEBUG("Too short (by %d chars; %d chars left in area)",val_len- (end_subst-beg_subst), b->size - b->used);
+// XBT_DEBUG("Too short (by %d chars; %d chars left in area)",val_len-(end_subst-beg_subst),b->size - b->used);
if (newused > b->size) {
- /* We have to realloc the data area before (because b->size is too small). We have to update our pointers, too */
+ /* We have to realloc the data area before (because b->size is too small).
+ * We have to update our pointers, too */
char *newdata = xbt_realloc(b->data, b->used + MAX(minimal_increment, tooshort));
int offset = newdata - b->data;
b->data = newdata;
beg_subst += offset;
end_subst += offset;
}
- memmove(beg_subst + val_len, end_subst, b->used - (end_subst - b->data) + 1); /* move the end of the string a bit further */
+ /* move the end of the string a bit further */
+ memmove(beg_subst + val_len, end_subst, b->used - (end_subst - b->data) + 1);
memmove(beg_subst, value, val_len); /* substitute */
b->used = newused;
// XBT_DEBUG("String is now: %s",b->data);
}
free(value);
-
free(default_value);
-
end--; /* compensate the next end++ */
}
break;
-
case '\0':
done = 1;
break;
#ifdef SIMGRID_TEST
#include "xbt/strbuff.h"
-/* buffstr have 512 chars by default. Adding 1000 chars like this will force a resize, allowing us to test that b->used and b->size are consistent */
+/* buffstr have 512 chars by default. Adding 1000 chars like this will force a resize, allowing us to test that
+ * b->used and b->size are consistent */
#define force_resize \
"1.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
"2.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
"9.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
"0.........1.........2.........3.........4.........5.........6.........7.........8.........9........."
-static void mytest(const char *input, const char *patterns,
- const char *expected)
+static void mytest(const char *input, const char *patterns, const char *expected)
{
xbt_dynar_t dyn_patterns; /* splited string */
xbt_dict_t p; /* patterns */
xbt_strbuff_append(sb, input);
xbt_strbuff_varsubst(sb, p);
xbt_dict_free(&p);
- xbt_test_assert(!strcmp(sb->data, expected),
- "Input (%s) with patterns (%s) leads to (%s) instead of (%s)",
+ xbt_test_assert(!strcmp(sb->data, expected), "Input (%s) with patterns (%s) leads to (%s) instead of (%s)",
input, patterns, sb->data, expected);
xbt_strbuff_free(sb);
}
xbt_test_add("Value much longer, no braces, data before and after");
mytest("toto $t tata", "t=" force_resize, "toto " force_resize " tata");
xbt_test_add("Value much longer, braces, data before and after");
- mytest("toto ${t} tata", "t=" force_resize,
- "toto " force_resize " tata");
+ mytest("toto ${t} tata", "t=" force_resize, "toto " force_resize " tata");
xbt_test_add("Escaped $");
mytest("\\$tutu", "tutu=t", "\\$tutu");
mytest("${t:-toto}", "", "toto");
xbt_test_add("Useless default value (variable already defined)");
mytest("${t:-toto}", "t=TRUC", "TRUC");
-
}
-
#endif /* SIMGRID_TEST */
extern int smx_cleaned;
extern int xbt_initialized;
-
SG_END_DECL()
-
#endif /* XBT_MODINTER_H */