gutils.c 22.9 KB
Newer Older
1
/* vim: set sw=8: -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 3 4
/*
 * utils.c:  Various utility routines that do not depend on the GUI of Gnumeric
 *
Chyla Zbigniew's avatar
Chyla Zbigniew committed
5
 * Authors:
6
 *    Miguel de Icaza (miguel@gnu.org)
7
 *    Jukka-Pekka Iivonen (iivonen@iki.fi)
Chyla Zbigniew's avatar
Chyla Zbigniew committed
8
 *    Zbigniew Chyla (cyba@gnome.pl)
9
 */
10
#include <gnumeric-config.h>
11
#include <glib/gi18n.h>
12
#include "gnumeric.h"
13
#include "gutils.h"
14

15 16
#include "sheet.h"
#include "ranges.h"
17
#include "mathfunc.h"
Jody Goldberg's avatar
Jody Goldberg committed
18
#include "libgnumeric.h"
19

20
#include <stdlib.h>
21
#include <math.h>
22
#include <stdio.h>
23
#include <string.h>
Chyla Zbigniew's avatar
Chyla Zbigniew committed
24 25
#include <sys/types.h>
#include <sys/stat.h>
26
#include <unistd.h>
Chyla Zbigniew's avatar
Chyla Zbigniew committed
27
#include <fcntl.h>
28
#include <errno.h>
Jody Goldberg's avatar
Jody Goldberg committed
29
#include <gsf/gsf-impl-utils.h>
Morten Welinder's avatar
Morten Welinder committed
30 31 32
#ifdef HAVE_FLOATINGPOINT_H
#include <floatingpoint.h>
#endif
33

34 35
static void
cb_hash_collect_keys (gpointer key, gpointer value, GSList **accum)
36
{
37
	*accum = g_slist_prepend (*accum, key);
38 39
}

40 41 42 43 44 45 46 47 48 49 50
/**
 * gnm_hash_keys :
 * @hash : #GHashTable
 *
 * Collects an unordered list of the keys in @hash.
 *
 * Returns a list which the caller needs to free.
 * 	The content has not additional references added
 **/
GSList *
gnm_hash_keys (GHashTable *hash)
51
{
52 53 54 55 56
	GSList *accum = NULL;
	g_hash_table_foreach (hash,
		(GHFunc )cb_hash_collect_keys, &accum);
	return accum;
}
57

58 59 60 61 62
static void
cb_hash_collect_values (gpointer key, gpointer value, GSList **accum)
{
	*accum = g_slist_prepend (*accum, value);
}
63

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
/**
 * gnm_hash_values :
 * @hash : #GHashTable
 *
 * Collects an unordered list of the values in @hash.
 *
 * Returns a list which the caller needs to free.
 * 	The content has not additional references added
 **/
GSList *
gnm_hash_values (GHashTable *hash)
{
	GSList *accum = NULL;
	g_hash_table_foreach (hash,
		(GHFunc )cb_hash_collect_values, &accum);
	return accum;
80 81
}

82
/***************************************************************************/
83
void
84
gnm_ptr_array_insert (GPtrArray *array, gpointer value, int index)
85
{
86
	if (index < (int)array->len) {
87 88 89 90 91 92
		int i = array->len - 1;
		gpointer last = g_ptr_array_index (array, i);
		g_ptr_array_add (array, last);

		while (i-- > index) {
			gpointer tmp = g_ptr_array_index (array, i);
93
			g_ptr_array_index (array, i + 1) = tmp;
94 95 96 97 98 99
		}
		g_ptr_array_index (array, index) = value;
	} else
		g_ptr_array_add (array, value);
}

Chyla Zbigniew's avatar
Chyla Zbigniew committed
100
/**
101
 * gnm_slist_create:
102 103 104 105 106
 * @item1: First item.
 *
 * Creates a GList from NULL-terminated list of arguments.
 *
 * Return value: created list.
107
 **/
108
GSList *
109
gnm_slist_create (gpointer item1, ...)
110 111 112 113 114 115 116 117 118 119 120 121 122 123
{
	va_list args;
	GSList *list = NULL;
	gpointer item;

	va_start (args, item1);
	for (item = item1; item != NULL; item = va_arg (args, gpointer)) {
		list = g_slist_prepend (list, item);
	}
	va_end (args);

	return g_slist_reverse (list);
}

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
/**
 * gnm_slist_map:
 * @list        : list of some items
 * @map_func    : mapping function
 *
 **/
GSList *
gnm_slist_map (GSList const *list, GnmMapFunc map_func)
{
	GSList *list_copy = NULL;

	GNM_SLIST_FOREACH (list, void, value,
		GNM_SLIST_PREPEND (list_copy, map_func (value))
	);

	return g_slist_reverse (list_copy);
}

/**
 * gnm_slist_free_custom:
 * @list: list of some items
 * @free_func: function freeing list item
 *
 * Clears a list, calling @free_func for each list item.
 **/
void
gnm_slist_free_custom (GSList *list, GFreeFunc free_func)
{
	GSList *l;

	for (l = list; l != NULL; l = l->next) {
		free_func (l->data);
	}
	g_slist_free (list);
}

160
gint
161
gnm_list_index_custom (GList *list, gpointer data, GCompareFunc cmp_func)
162 163 164 165 166 167 168 169 170 171 172 173 174
{
	GList *l;
	gint i;

	for (l = list, i = 0; l != NULL; l = l->next, i++) {
		if (cmp_func (l->data, data) == 0) {
			return i;
		}
	}

	return -1;
}

175
/**
176
 * gnm_list_free_custom:
177 178 179
 * @list: list of some items
 * @free_func: function freeing list item
 *
180
 * Clears a list, calling @free_func for each list item.
181 182 183
 *
 */
void
184
gnm_list_free_custom (GList *list, GFreeFunc free_func)
185 186 187 188 189 190 191 192 193
{
	GList *l;

	for (l = list; l != NULL; l = l->next) {
		free_func (l->data);
	}
	g_list_free (list);
}

194
/**
195
 * gnm_strsplit_to_slist:
196 197 198 199 200
 * @string: String to split
 * @delimiter: Token delimiter
 *
 * Splits up string into tokens at delim and returns a string list.
 *
201
 * Returns: string list which you should free after use using function
202
 * e_free_string_list().
203
 **/
204
GSList *
205
gnm_strsplit_to_slist (gchar const *string, gchar const *delimiter)
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
{
	gchar **token_v;
	GSList *string_list = NULL;
	gint i;

	token_v = g_strsplit (string, delimiter, 0);
	if (token_v != NULL) {
		for (i = 0; token_v[i] != NULL; i++) {
			string_list = g_slist_prepend (string_list, token_v[i]);
		}
		string_list = g_slist_reverse (string_list);
		g_free (token_v);
	}

	return string_list;
}
Chyla Zbigniew's avatar
Chyla Zbigniew committed
222

223
gint
224
gnm_utf8_collate_casefold (const char *a, const char *b)
225 226 227 228 229 230 231 232 233
{
	char *a2 = g_utf8_casefold (a, -1);
	char *b2 = g_utf8_casefold (b, -1);
	int res = g_utf8_collate (a2, b2);
	g_free (a2);
	g_free (b2);
	return res;
}

234
gint
235
gnm_ascii_strcase_equal (gconstpointer v1, gconstpointer v2)
236 237 238 239
{
	return g_ascii_strcasecmp ((char const *) v1, (char const *)v2) == 0;
}

240 241
/* a char* hash function from ASU */
guint
242
gnm_ascii_strcase_hash (gconstpointer v)
243
{
Jody Goldberg's avatar
Jody Goldberg committed
244 245
	unsigned const char *s = (unsigned const char *)v;
	unsigned const char *p;
246
	guint h = 0, g;
Morten Welinder's avatar
Morten Welinder committed
247

248
	for(p = s; *p != '\0'; p += 1) {
Morten Welinder's avatar
Morten Welinder committed
249
		h = ( h << 4 ) + g_ascii_tolower (*p);
250 251 252 253 254
		if ( ( g = h & 0xf0000000 ) ) {
			h = h ^ (g >> 24);
			h = h ^ g;
		}
	}
Morten Welinder's avatar
Morten Welinder committed
255

256 257 258
	return h /* % M */;
}

259
char *
260
gnm_sys_data_dir (char const *subdir)
261
{
Jody Goldberg's avatar
new.  
Jody Goldberg committed
262 263
	if (subdir == NULL)
		return (char *)gnumeric_data_dir;
264
	return g_build_filename (gnumeric_data_dir, subdir, NULL);
265 266 267
}

char *
268
gnm_sys_lib_dir (char const *subdir)
269
{
270
	return g_build_filename (gnumeric_lib_dir, subdir, NULL);
271 272 273
}

#define GLADE_SUFFIX	"glade"
Jody Goldberg's avatar
Jody Goldberg committed
274
#define PLUGIN_SUFFIX	"plugins"
275

Miguel de Icaza's avatar
Miguel de Icaza committed
276
char *
277
gnm_sys_glade_dir (void)
Miguel de Icaza's avatar
Miguel de Icaza committed
278
{
279
	return gnm_sys_data_dir (GLADE_SUFFIX);
Miguel de Icaza's avatar
Miguel de Icaza committed
280 281 282
}

char *
283
gnm_sys_plugin_dir (void)
Miguel de Icaza's avatar
Miguel de Icaza committed
284
{
285
	return gnm_sys_lib_dir (PLUGIN_SUFFIX);
Miguel de Icaza's avatar
Miguel de Icaza committed
286
}
287 288

char *
289
gnm_usr_dir (char const *subdir)
290
{
Jody Goldberg's avatar
Jody Goldberg committed
291
	char const *home_dir = g_get_home_dir ();
Miguel de Icaza's avatar
Miguel de Icaza committed
292

293 294 295 296 297 298
	if (!home_dir)
		return NULL;

	return g_build_filename (home_dir, ".gnumeric",
				 GNUMERIC_VERSION, subdir,
				 NULL);
299 300
}

Miguel de Icaza's avatar
Miguel de Icaza committed
301
char *
302
gnm_usr_plugin_dir (void)
Miguel de Icaza's avatar
Miguel de Icaza committed
303
{
304
	return gnm_usr_dir (PLUGIN_SUFFIX);
Miguel de Icaza's avatar
Miguel de Icaza committed
305
}
306 307

/* ------------------------------------------------------------------------- */
308 309 310 311 312 313 314

/*
 * Escapes all backslashes and quotes in a string. It is based on glib's
 * g_strescape.
 *
 * Also adds quotes around the result.
 */
315 316
void
gnm_strescape (GString *target, char const *string)
317
{
318 319 320 321 322 323 324 325 326 327
	g_string_append_c (target, '"');
	/* This loop should be UTF-8 safe.  */
	for (; *string; string++) {
		switch (*string) {
		case '"':
		case '\\':
			g_string_append_c (target, '\\');
		default:
			g_string_append_c (target, *string);
		}
328
	}
329
	g_string_append_c (target, '"');
330 331
}

Morten Welinder's avatar
Morten Welinder committed
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
/*
 * The reverse operation of gnm_strescape.  Returns a pointer to the
 * first char after the string on success or NULL on failure.
 *
 * First character of the string should be an ASCII character used
 * for quoting.
 */
const char *
gnm_strunescape (GString *target, const char *string)
{
	char quote = *string++;
	size_t oldlen = target->len;

	/* This should be UTF-8 safe as long as quote is ASCII.  */
	while (*string != quote) {
		if (*string == 0)
			goto error;
		else if (*string == '\\') {
			string++;
			if (*string == 0)
				goto error;
		}

		g_string_append_c (target, *string);
		string++;
	}

	return ++string;

 error:
	g_string_truncate (target, oldlen);
	return NULL;
}

Morten Welinder's avatar
Morten Welinder committed
366 367 368 369 370 371
void
gnm_string_append_gstring (GString *target, const GString *source)
{
	g_string_append_len (target, source->str, source->len);
}

372
/* ------------------------------------------------------------------------- */
Morten Welinder's avatar
Morten Welinder committed
373

Morten Welinder's avatar
Morten Welinder committed
374
#ifdef NEED_FAKE_MODFGNUM
Jody Goldberg's avatar
Jody Goldberg committed
375 376
gnm_float
modfgnum (gnm_float x, gnm_float *iptr)
Morten Welinder's avatar
Morten Welinder committed
377
{
Morten Welinder's avatar
Morten Welinder committed
378 379 380 381 382 383 384 385 386 387
	if (isnangnum (x))
		return *iptr = x;
	else if (finitegnum (x)) {
		if (x >= 0)
			return x - (*iptr = floorgnum (x));
		else
			return x - (*iptr = -floorgnum (-x));			
	} else {
		*iptr = x;
		return 0;
Morten Welinder's avatar
Morten Welinder committed
388 389 390 391 392 393 394
	}
}
#endif

/* ------------------------------------------------------------------------- */

#ifdef NEED_FAKE_STRTOGNUM
Jody Goldberg's avatar
Jody Goldberg committed
395
gnm_float
Jody Goldberg's avatar
Jody Goldberg committed
396
strtognum (char const *str, char **end)
Morten Welinder's avatar
Morten Welinder committed
397 398
{
#if defined(HAVE_STRING_TO_DECIMAL) && defined(HAVE_DECIMAL_TO_QUADRUPLE)
Jody Goldberg's avatar
Jody Goldberg committed
399
	gnm_float res;
Morten Welinder's avatar
Morten Welinder committed
400 401 402 403 404 405
	decimal_record dr;
	enum decimal_string_form form;
	decimal_mode dm;
	fp_exception_field_type excp;
	char *echar;

Morten Welinder's avatar
Morten Welinder committed
406 407
	string_to_decimal ((char **)&str, INT_MAX, 0,
			   &dr, &form, &echar);
Morten Welinder's avatar
Morten Welinder committed
408 409 410 411 412 413 414 415 416
	if (end) *end = (char *)str;

	if (form == invalid_form) {
		errno = EINVAL;
		return 0.0;
	}

	dm.rd = fp_nearest;
	decimal_to_quadruple (&res, &dm, &dr, &excp);
Morten Welinder's avatar
Morten Welinder committed
417 418 419
        if (excp & ((1 << fp_overflow) | (1 << fp_underflow)))
                errno = ERANGE;
	return res;
Morten Welinder's avatar
Morten Welinder committed
420
#else
Morten Welinder's avatar
Morten Welinder committed
421
	char *myend;
Jody Goldberg's avatar
Jody Goldberg committed
422
	gnm_float res;
Morten Welinder's avatar
Morten Welinder committed
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
	int count;

	if (end == 0) end = &myend;
	(void) strtod (str, end);
	if (str == *end)
		return 0;

	errno = 0;
	count = sscanf (str, "%Lf", &res);
	if (count == 1)
		return res;

	/* Now what?  */
	*end = (char *)str;
	errno = ERANGE;
	return 0.0;
Morten Welinder's avatar
Morten Welinder committed
439 440 441 442 443
#endif
}
#endif

/* ------------------------------------------------------------------------- */
444 445

#ifdef NEED_FAKE_LDEXPGNUM
Jody Goldberg's avatar
Jody Goldberg committed
446 447
gnm_float
ldexpgnum (gnm_float x, int exp)
448
{
449
	if (!finitegnum (x) || x == 0)
450 451
		return x;
	else {
Jody Goldberg's avatar
Jody Goldberg committed
452
		gnm_float res = x * gpow2 (exp);
453
		if (finitegnum (res))
454 455 456
			return res;
		else {
			errno = ERANGE;
457
			return (x > 0) ? gnm_pinf : gnm_ninf;
458 459
		}
	}
460 461 462 463 464 465
}
#endif

/* ------------------------------------------------------------------------- */

#ifdef NEED_FAKE_FREXPGNUM
Jody Goldberg's avatar
Jody Goldberg committed
466 467
gnm_float
frexpgnum (gnm_float x, int *exp)
468
{
Morten Welinder's avatar
Morten Welinder committed
469
	gnm_float l2x;
470

Morten Welinder's avatar
Morten Welinder committed
471 472
	if (!finitegnum (x))
		return x;
473

Morten Welinder's avatar
Morten Welinder committed
474 475 476 477 478
	if (x == 0)
		return *exp = 0;

	l2x = loggnum (gnumabs (x)) / loggnum (2);
	*exp = (int)floorgnum (l2x);
479 480 481

	/*
	 * Now correct the result and adjust things that might have gotten
Morten Welinder's avatar
Morten Welinder committed
482
	 * off-by-one due to rounding.
483 484 485 486 487 488 489 490 491 492 493 494
	 */
	res = x / gpow2 (*exp);
	if (gnumabs (res) >= 1.0)
		res /= 2, (*exp)++;
	else if (gnumabs (res) < 0.5)
		res *= 2, (*exp)--;

	return res;
}
#endif

/* ------------------------------------------------------------------------- */
Morten Welinder's avatar
Morten Welinder committed
495 496

#ifdef NEED_FAKE_ERFGNUM
Jody Goldberg's avatar
Jody Goldberg committed
497 498
gnm_float
erfgnum (gnm_float x)
Morten Welinder's avatar
Morten Welinder committed
499
{
500 501 502 503 504 505 506 507 508 509 510 511 512 513
	if (gnumabs (x) < 0.1) {
		/* For small x the pnorm formula loses precision.  */
		gnm_float sum = 0;
		gnm_float term = x * 2 / sqrtgnum (M_PIgnum);
		gnm_float n;
		gnm_float x2 = x * x;

		for (n = 0; gnumabs (term) >= gnumabs (sum) * GNUM_EPSILON ; n++) {
			sum += term / (2 * n + 1);
			term *= -x2 / (n + 1);
		}

		return sum;
	}
Morten Welinder's avatar
Morten Welinder committed
514 515 516 517 518 519 520
	return pnorm (x * M_SQRT2gnum, 0, 1, TRUE, FALSE) * 2 - 1;
}
#endif

/* ------------------------------------------------------------------------- */

#ifdef NEED_FAKE_ERFCGNUM
Jody Goldberg's avatar
Jody Goldberg committed
521 522
gnm_float
erfcgnum (gnm_float x)
Morten Welinder's avatar
Morten Welinder committed
523 524 525 526 527 528 529 530
{
	return 2 * pnorm (x * M_SQRT2gnum, 0, 1, FALSE, FALSE);
}
#endif

/* ------------------------------------------------------------------------- */

#ifdef NEED_FAKE_YNGNUM
Jody Goldberg's avatar
Jody Goldberg committed
531 532
gnm_float
yngnum (int n, gnm_float x)
Morten Welinder's avatar
Morten Welinder committed
533 534 535 536 537 538 539
{
	static gboolean warned = FALSE;
	if (!warned) {
		warned = TRUE;
		g_warning (_("This version of Gnumeric has been compiled with inadequate precision in yngnum."));
	}

Jody Goldberg's avatar
Jody Goldberg committed
540
	return (gnm_float)yn (n, (double)x);
Morten Welinder's avatar
Morten Welinder committed
541 542 543
}
#endif

544
/* ------------------------------------------------------------------------- */
Morten Welinder's avatar
Morten Welinder committed
545 546 547 548 549 550

#ifdef NEED_FAKE_LGAMMA_R
gnm_float
lgamma_rgnum (gnm_float x, int *signp)
{
#ifdef HAVE_LGAMMA
551
	gnm_float res = lgammagnum (x);
Morten Welinder's avatar
Morten Welinder committed
552 553 554 555 556 557 558 559
	*signp = (x >= 0 || fmodgnum (floorgnum (-x), 2.0) != 0.0) ? +1 : -1;
	return res;
#else
#error "I need to have lgamma for this to work."
#endif
}
#endif

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
/* ------------------------------------------------------------------------- */
/* Partially lifted from R, but they got the guts from me -- MW.  */

#ifdef NEED_FAKE_EXPM1
gnm_float
expm1gnum (gnm_float x)
{
#ifdef HAVE_LOG1P
	gnm_float y, a = gnumabs (x);

	if (a > 1e-8) {
		y = expgnum (x) - 1;
		if (a > 0.697)
			return y;  /* negligible cancellation */
	} else {
		if (a < GNUM_EPSILON)
			return x;
		/* Taylor expansion, more accurate in this range */
		y = (x / 2 + 1) * x;
	}

	/* Newton step for solving   log(1 + y) = x   for y : */
	y -= (1 + y) * (log1pgnum (y) - x);
	return y;
#else
#error "I need to have log1pgnum for this to work."
#endif
}
#endif

Morten Welinder's avatar
Morten Welinder committed
590 591
/* ------------------------------------------------------------------------- */

592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
#ifdef NEED_FAKE_ASINH
gnm_float
asinhgnum (gnm_float x)
{
  gnm_float y = gnumabs (x);
  gnm_float r = log1pgnum (y * y / (hypotgnum (y, 1.0) + 1.0) + y);
  return (x >= 0) ? r : -r;
}
#endif

/* ------------------------------------------------------------------------- */

#ifdef NEED_FAKE_ACOSH
gnm_float
acoshgnum (gnm_float x)
{
  gnm_float xm1 = x - 1;
  return log1pgnum (xm1 + sqrtgnum (xm1) * sqrtgnum (x + 1.0));
}
#endif

/* ------------------------------------------------------------------------- */

#ifdef NEED_FAKE_ATANH
gnm_float
atanhgnum (gnm_float x)
{
  gnm_float y = gnumabs (x);
  gnm_float r = -0.5 * log1pgnum (-(y + y) / (1.0 + y));
  return (x >= 0) ? r : -r;
}
#endif

/* ------------------------------------------------------------------------- */

627
/**
628
 * gnm_utf8_strcapital:
Morten Welinder's avatar
Morten Welinder committed
629
 * @p: pointer to UTF-8 string
630 631 632 633 634 635
 * @len: length in bytes, or -1.
 *
 * Similar to g_utf8_strup and g_utf8_strup, except that this function
 * creates a string "Very Much Like: This, One".
 *
 * Return value: newly allocated string.
636
 **/
637
char *
638
gnm_utf8_strcapital (const char *p, ssize_t len)
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
{
	const char *pend = (len < 0 ? NULL : p + len);
	GString *res = g_string_sized_new (len < 0 ? 1 : len + 1);
	gboolean up = TRUE;

	/*
	 * This does a simple character-by-character mapping and probably
	 * is not linguistically correct.
	 */

	for (; (len < 0 || p < pend) && *p; p = g_utf8_next_char (p)) {
		gunichar c = g_utf8_get_char (p);

		if (g_unichar_isalpha (c)) {
			if (up ? g_unichar_isupper (c) : g_unichar_islower (c))
				/* Correct case -- keep the char.  */
				g_string_append_unichar (res, c);
			else {
				char *tmp = up
					? g_utf8_strup (p, 1)
					: g_utf8_strdown (p, 1);
				g_string_append (res, tmp);
				g_free (tmp);
			}
			up = FALSE;
		} else {
			g_string_append_unichar (res, c);
			up = TRUE;
		}
	}

670
	return g_string_free (res, FALSE);
671 672
}

Morten Welinder's avatar
Morten Welinder committed
673
/* ------------------------------------------------------------------------- */
Morten Welinder's avatar
Morten Welinder committed
674

675
#undef DEBUG_CHUNK_ALLOCATOR
676

677 678 679 680 681 682 683 684 685 686
typedef struct _gnm_mem_chunk_freeblock gnm_mem_chunk_freeblock;
typedef struct _gnm_mem_chunk_block gnm_mem_chunk_block;

struct _gnm_mem_chunk_freeblock {
	gnm_mem_chunk_freeblock *next;
};

struct _gnm_mem_chunk_block {
	gpointer data;
	int freecount, nonalloccount;
687 688 689 690
	gnm_mem_chunk_freeblock *freelist;
#ifdef DEBUG_CHUNK_ALLOCATOR
	int id;
#endif
691 692
};

Jody Goldberg's avatar
Jody Goldberg committed
693
struct _GnmMemChunk {
694
	char *name;
695
	size_t atom_size, user_atom_size, chunk_size, alignment;
696 697
	int atoms_per_block;

698 699 700 701 702 703 704 705 706 707
	/* List of all blocks.  */
	GSList *blocklist;

	/* List of blocks that are not full.  */
	GList *freeblocks;

#ifdef DEBUG_CHUNK_ALLOCATOR
	int blockid;
#endif
};
708 709


Jody Goldberg's avatar
Jody Goldberg committed
710
GnmMemChunk *
Jody Goldberg's avatar
Jody Goldberg committed
711
gnm_mem_chunk_new (char const *name, size_t user_atom_size, size_t chunk_size)
712 713
{
	int atoms_per_block;
Jody Goldberg's avatar
Jody Goldberg committed
714
	GnmMemChunk *res;
715
	size_t user_alignment, alignment, atom_size;
716 717 718
	size_t maxalign = 1 + ((sizeof (void *) - 1) |
			       (sizeof (long) - 1) |
			       (sizeof (double) - 1) |
Jody Goldberg's avatar
Jody Goldberg committed
719
			       (sizeof (gnm_float) - 1));
720

721 722 723 724 725
	/*
	 * The alignment that the caller can expect is 2^(lowest_bit_in_size).
	 * The fancy bit math computes this.  Think it over.
	 *
	 * We don't go lower than pointer-size, so this always comes out as
Jody Goldberg's avatar
Jody Goldberg committed
726
	 * 4 or 8.  (Or 16, if gnm_float is long double.)  Sometimes, when
727 728 729 730 731 732
	 * user_atom_size is a multiple of 8, this alignment is bigger than
	 * really needed, but we don't know if the structure has elements
	 * with 8-byte alignment.  In those cases we waste memory.
	 */
	user_alignment = ((user_atom_size ^ (user_atom_size - 1)) + 1) / 2;
	alignment = MIN (MAX (user_alignment, sizeof (gnm_mem_chunk_block *)), maxalign);
733 734 735 736
	atom_size = alignment + MAX (user_atom_size, sizeof (gnm_mem_chunk_freeblock));
	atoms_per_block = MAX (1, chunk_size / atom_size);
	chunk_size = atoms_per_block * atom_size;

737
#ifdef DEBUG_CHUNK_ALLOCATOR
738 739 740 741 742
	g_print ("Created %s with alignment=%d, atom_size=%d (%d), chunk_size=%d.\n",
		 name, alignment, atom_size, user_atom_size,
		 chunk_size);
#endif

Jody Goldberg's avatar
Jody Goldberg committed
743
	res = g_new (GnmMemChunk, 1);
744
	res->alignment = alignment;
745
	res->name = g_strdup (name);
746 747 748 749 750
	res->user_atom_size = user_atom_size;
	res->atom_size = atom_size;
	res->chunk_size = chunk_size;
	res->atoms_per_block = atoms_per_block;
	res->blocklist = NULL;
751 752 753 754
	res->freeblocks = NULL;
#ifdef DEBUG_CHUNK_ALLOCATOR
	res->blockid = 0;
#endif
755 756 757 758 759

	return res;
}

void
Jody Goldberg's avatar
Jody Goldberg committed
760
gnm_mem_chunk_destroy (GnmMemChunk *chunk, gboolean expect_leaks)
761
{
762 763 764 765 766 767 768
	GSList *l;

	g_return_if_fail (chunk != NULL);

#ifdef DEBUG_CHUNK_ALLOCATOR
	g_print ("Destroying %s.\n", chunk->name);
#endif
769 770 771 772 773 774
	/*
	 * Since this routine frees all memory allocated for the pool,
	 * it is sometimes convenient not to free at all.  For such
	 * cases, don't report leaks.
	 */
	if (!expect_leaks) {
775 776
		GSList *l;
		int leaked = 0;
777

778 779 780 781 782 783 784
		for (l = chunk->blocklist; l; l = l->next) {
			gnm_mem_chunk_block *block = l->data;
			leaked += chunk->atoms_per_block - (block->freecount + block->nonalloccount);
		}
		if (leaked) {
			g_warning ("Leaked %d nodes from %s.",
				   leaked, chunk->name);
785 786 787
		}
	}

788 789
	for (l = chunk->blocklist; l; l = l->next) {
		gnm_mem_chunk_block *block = l->data;
790 791 792
		g_free (block->data);
		g_free (block);
	}
793 794
	g_slist_free (chunk->blocklist);
	g_list_free (chunk->freeblocks);
795
	g_free (chunk->name);
796 797 798 799
	g_free (chunk);
}

gpointer
Jody Goldberg's avatar
Jody Goldberg committed
800
gnm_mem_chunk_alloc (GnmMemChunk *chunk)
801 802 803 804 805
{
	gnm_mem_chunk_block *block;
	char *res;

	/* First try the freelist.  */
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
	if (chunk->freeblocks) {
		gnm_mem_chunk_freeblock *res;

		block = chunk->freeblocks->data;
		res = block->freelist;
		if (res) {
			block->freelist = res->next;

			block->freecount--;
			if (block->freecount == 0 && block->nonalloccount == 0) {
				/* Block turned full -- remove it from freeblocks.  */
				chunk->freeblocks = g_list_delete_link (chunk->freeblocks,
									chunk->freeblocks);
			}
			return res;
		}
		/*
		 * If we get here, the block has free space that was never
		 * allocated.
		 */
	} else {
827
		block = g_new (gnm_mem_chunk_block, 1);
828 829 830 831
#ifdef DEBUG_CHUNK_ALLOCATOR
		block->id = chunk->blockid++;
		g_print ("Allocating new chunk %d for %s.\n", block->id, chunk->name);
#endif
832 833 834
		block->nonalloccount = chunk->atoms_per_block;
		block->freecount = 0;
		block->data = g_malloc (chunk->chunk_size);
835 836 837 838
		block->freelist = NULL;

		chunk->blocklist = g_slist_prepend (chunk->blocklist, block);
		chunk->freeblocks = g_list_prepend (chunk->freeblocks, block);
839 840 841 842 843
	}

	res = (char *)block->data +
		(chunk->atoms_per_block - block->nonalloccount--) * chunk->atom_size;
	*((gnm_mem_chunk_block **)res) = block;
844 845 846 847 848 849

	if (block->nonalloccount == 0 && block->freecount == 0) {
		/* Block turned full -- remove it from freeblocks.  */
		chunk->freeblocks = g_list_delete_link (chunk->freeblocks, chunk->freeblocks);
	}

850 851 852 853
	return res + chunk->alignment;
}

gpointer
Jody Goldberg's avatar
Jody Goldberg committed
854
gnm_mem_chunk_alloc0 (GnmMemChunk *chunk)
855 856 857 858 859 860 861
{
	gpointer res = gnm_mem_chunk_alloc (chunk);
	memset (res, 0, chunk->user_atom_size);
	return res;
}

void
Jody Goldberg's avatar
Jody Goldberg committed
862
gnm_mem_chunk_free (GnmMemChunk *chunk, gpointer mem)
863 864 865 866 867
{
	gnm_mem_chunk_freeblock *fb = mem;
	gnm_mem_chunk_block *block =
		*((gnm_mem_chunk_block **)((char *)mem - chunk->alignment));

Morten Welinder's avatar
Morten Welinder committed
868 869 870 871 872 873 874 875
#if 0
	/*
	 * This is useful when the exact location of a leak needs to be
	 * pin-pointed.
	 */
	memset (mem, 0, chunk->user_atom_size);
#endif

876 877 878
	fb->next = block->freelist;
	block->freelist = fb;
	block->freecount++;
879

880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
	if (block->freecount == 1 && block->nonalloccount == 0) {
		/* Block turned non-full.  */
		chunk->freeblocks = g_list_prepend (chunk->freeblocks, block);
	} else if (block->freecount == chunk->atoms_per_block) {
		/* Block turned all-free.  */

#ifdef DEBUG_CHUNK_ALLOCATOR
		g_print ("Releasing chunk %d for %s.\n", block->id, chunk->name);
#endif
		/*
		 * FIXME -- this could be faster if we rolled our own lists.
		 * Hopefully, however, (a) the number of blocks is small,
		 * and (b) the freed block might be near the beginning ("top")
		 * of the stacks.
		 */
		chunk->blocklist = g_slist_remove (chunk->blocklist, block);
		chunk->freeblocks = g_list_remove (chunk->freeblocks, block);
Morten Welinder's avatar
Morten Welinder committed
897 898 899

		g_free (block->data);
		g_free (block);
900 901
	}
}
Morten Welinder's avatar
Morten Welinder committed
902

Morten Welinder's avatar
Morten Welinder committed
903 904 905 906
/*
 * Loop over all non-freed memory in the chunk.  It's safe to allocate or free
 * from the chunk in the callback.
 */
Morten Welinder's avatar
Morten Welinder committed
907
void
Jody Goldberg's avatar
Jody Goldberg committed
908
gnm_mem_chunk_foreach_leak (GnmMemChunk *chunk, GFunc cb, gpointer user)
Morten Welinder's avatar
Morten Welinder committed
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
{
	GSList *l, *leaks = NULL;

	for (l = chunk->blocklist; l; l = l->next) {
		gnm_mem_chunk_block *block = l->data;
		if (chunk->atoms_per_block - (block->freecount + block->nonalloccount) > 0) {
			char *freed = g_new0 (char, chunk->atoms_per_block);
			gnm_mem_chunk_freeblock *fb = block->freelist;
			int i;

			while (fb) {
				char *atom = (char *)fb - chunk->alignment;
				int no = (atom - (char *)block->data) / chunk->atom_size;
				freed[no] = 1;
				fb = fb->next;
			}

			for (i = chunk->atoms_per_block - block->nonalloccount - 1; i >= 0; i--) {
				if (!freed[i]) {
					char *atom = (char *)block->data + i * chunk->atom_size;
					leaks = g_slist_prepend (leaks, atom + chunk->alignment);
				}
			}
			g_free (freed);
		}
	}

	g_slist_foreach (leaks, cb, user);
	g_slist_free (leaks);
}
Jody Goldberg's avatar
Jody Goldberg committed
939 940

int
941
gnm_str_compare (void const *x, void const *y)
Jody Goldberg's avatar
Jody Goldberg committed
942 943 944 945 946 947
{
	if (x == NULL || y == NULL) {
		if (x == y)
			return 0;
		else
			return x ? -1 : 1;
Morten Welinder's avatar
Morten Welinder committed
948
	}
Morten Welinder's avatar
Morten Welinder committed
949

Jody Goldberg's avatar
Jody Goldberg committed
950 951
	return strcmp (x, y);
}
Morten Welinder's avatar
Morten Welinder committed
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991


const char *
gnm_guess_encoding (const char *raw, size_t len, const char *user_guess,
		    char **utf8_str)
{
	int try;

	g_return_val_if_fail (raw != NULL, NULL);

	for (try = 1; 1; try++) {
		const char *guess;
		GError *error = NULL;
		char *utf8_data;

		switch (try) {
		case 1: guess = user_guess; break;
		case 2: g_get_charset (&guess); break;
		case 3: guess = "ASCII"; break;
		case 4: guess = "ISO-8859-1"; break;
		case 5: guess = "UTF-8"; break;
		default: return NULL;
		}

		if (!guess)
			continue;

		utf8_data = g_convert (raw, len, "UTF-8", guess,
				       NULL, NULL, &error);
		if (!error) {
			if (utf8_str)
				*utf8_str = utf8_data;
			else
				g_free (utf8_data);
			return guess;
		}

		g_error_free (error);
	}
}
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
992

993 994
/**
 * gnm_get_real_name :
995
 *
996 997 998 999
 * Return a utf8 encoded string with the current user name.
 * Caller should _NOT_ free the result.
 **/
char const *
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
1000 1001
gnm_get_real_name (void)
{
Morten Welinder's avatar
Morten Welinder committed
1002
	/* We will leak this.  */
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
1003 1004
	static char *gnm_real_name = NULL;

1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
	if (gnm_real_name == NULL) {
		char const *name = getenv ("NAME");
		if (name == NULL)
			name = g_get_real_name ();
		if (name == NULL)
			name = g_get_user_name ();
		if (name != NULL)
			(void) gnm_guess_encoding (name, strlen (name),
				NULL, &gnm_real_name);
		else
			gnm_real_name = (char *)"unknown";
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
1016 1017 1018
	}
	return gnm_real_name;
}
Morten Welinder's avatar
Morten Welinder committed
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032

/**
 * gnm_destroy_password :
 *
 * Overwrite a string holding a password.  This is a separate routine to
 * ensure that the compiler does not try to outsmart us.
 *
 * Note: this does not free the memory.
 **/
void
gnm_destroy_password (char *passwd)
{
	memset (passwd, 0, strlen (passwd));
}
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062

/* ------------------------------------------------------------------------- */

static GList *timers_stack = NULL;

void
gnm_time_counter_push (void)
{
	GTimer *timer;

	timer = g_timer_new ();
	timers_stack = g_list_prepend (timers_stack, timer);
}

gdouble
gnm_time_counter_pop (void)
{
	GTimer *timer;
	gdouble ret_val;

	g_assert (timers_stack != NULL);

	timer = (GTimer *) timers_stack->data;
	timers_stack = g_list_remove (timers_stack, timers_stack->data);
	ret_val = g_timer_elapsed (timer, NULL);
	g_timer_destroy (timer);

	return ret_val;
}