pcsc-lite  1.8.22
simclist.c
1 /*
2  * Copyright (c) 2007,2008,2009,2010,2011 Mij <mij@bitchx.it>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 
17 
18 /*
19  * SimCList library. See http://mij.oltrelinux.com/devel/simclist
20  */
21 
22 /* SimCList implementation, version 1.6 */
23 
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h> /* for setting errno */
27 #include <sys/types.h>
28 #ifndef _WIN32
29  /* not in Windows! */
30 # include <unistd.h>
31 # include <stdint.h>
32 #endif
33 #ifndef SIMCLIST_NO_DUMPRESTORE
34  /* includes for dump/restore */
35 # include <time.h>
36 # include <sys/uio.h> /* for READ_ERRCHECK() and write() */
37 # include <fcntl.h> /* for open() etc */
38 # ifndef _WIN32
39 # include <arpa/inet.h> /* for htons() on UNIX */
40 # else
41 # include <winsock2.h> /* for htons() on Windows */
42 # endif
43 #endif
44 
45 /* disable asserts */
46 #ifndef SIMCLIST_DEBUG
47 #define NDEBUG
48 #endif
49 
50 #include <assert.h>
51 
52 
53 #include <sys/stat.h> /* for open()'s access modes S_IRUSR etc */
54 #include <limits.h>
55 
56 #if defined(_MSC_VER) || defined(__MINGW32__)
57 /* provide gettimeofday() missing in Windows */
58 int gettimeofday(struct timeval *tp, void *tzp) {
59  DWORD t;
60 
61  /* XSI says: "If tzp is not a null pointer, the behavior is unspecified" */
62  assert(tzp == NULL);
63 
64  t = timeGetTime();
65  tp->tv_sec = t / 1000;
66  tp->tv_usec = t % 1000;
67  return 0;
68 }
69 #endif
70 
71 
72 /* work around lack of inttypes.h support in broken Microsoft Visual Studio compilers */
73 #if !defined(_WIN32) || !defined(_MSC_VER)
74 # include <inttypes.h> /* (u)int*_t */
75 #else
76 # include <basetsd.h>
77 typedef UINT8 uint8_t;
78 typedef UINT16 uint16_t;
79 typedef ULONG32 uint32_t;
80 typedef UINT64 uint64_t;
81 typedef INT8 int8_t;
82 typedef INT16 int16_t;
83 typedef LONG32 int32_t;
84 typedef INT64 int64_t;
85 #endif
86 
87 
88 /* define some commodity macros for Dump/Restore functionality */
89 #ifndef SIMCLIST_NO_DUMPRESTORE
90 /* write() decorated with error checking logic */
91 #define WRITE_ERRCHECK(fd, msgbuf, msglen) do { \
92  if (write(fd, msgbuf, msglen) < 0) return -1; \
93  } while (0);
94 /* READ_ERRCHECK() decorated with error checking logic */
95 #define READ_ERRCHECK(fd, msgbuf, msglen) do { \
96  if (read(fd, msgbuf, msglen) != msglen) { \
97  /*errno = EPROTO;*/ \
98  return -1; \
99  } \
100  } while (0);
101 
102 /* convert 64bit integers from host to network format */
103 #define hton64(x) (\
104  htons(1) == 1 ? \
105  (uint64_t)x /* big endian */ \
106  : /* little endian */ \
107  ((uint64_t)((((uint64_t)(x) & 0xff00000000000000ULL) >> 56) | \
108  (((uint64_t)(x) & 0x00ff000000000000ULL) >> 40) | \
109  (((uint64_t)(x) & 0x0000ff0000000000ULL) >> 24) | \
110  (((uint64_t)(x) & 0x000000ff00000000ULL) >> 8) | \
111  (((uint64_t)(x) & 0x00000000ff000000ULL) << 8) | \
112  (((uint64_t)(x) & 0x0000000000ff0000ULL) << 24) | \
113  (((uint64_t)(x) & 0x000000000000ff00ULL) << 40) | \
114  (((uint64_t)(x) & 0x00000000000000ffULL) << 56))) \
115  )
116 
117 /* convert 64bit integers from network to host format */
118 #define ntoh64(x) (hton64(x))
119 #endif
120 
121 /* some OSes don't have EPROTO (eg OpenBSD) */
122 #ifndef EPROTO
123 #define EPROTO EIO
124 #endif
125 
126 #ifdef SIMCLIST_WITH_THREADS
127 /* limit (approx) to the number of threads running
128  * for threaded operations. Only meant when
129  * SIMCLIST_WITH_THREADS is defined */
130 #define SIMCLIST_MAXTHREADS 2
131 #endif
132 
133 /*
134  * how many elems to keep as spare. During a deletion, an element
135  * can be saved in a "free-list", not free()d immediately. When
136  * latter insertions are performed, spare elems can be used instead
137  * of malloc()ing new elems.
138  *
139  * about this param, some values for appending
140  * 10 million elems into an empty list:
141  * (#, time[sec], gain[%], gain/no[%])
142  * 0 2,164 0,00 0,00 <-- feature disabled
143  * 1 1,815 34,9 34,9
144  * 2 1,446 71,8 35,9 <-- MAX gain/no
145  * 3 1,347 81,7 27,23
146  * 5 1,213 95,1 19,02
147  * 8 1,064 110,0 13,75
148  * 10 1,015 114,9 11,49 <-- MAX gain w/ likely sol
149  * 15 1,019 114,5 7,63
150  * 25 0,985 117,9 4,72
151  * 50 1,088 107,6 2,15
152  * 75 1,016 114,8 1,53
153  * 100 0,988 117,6 1,18
154  * 150 1,022 114,2 0,76
155  * 200 0,939 122,5 0,61 <-- MIN time
156  */
157 #ifndef SIMCLIST_MAX_SPARE_ELEMS
158 #define SIMCLIST_MAX_SPARE_ELEMS 5
159 #endif
160 
161 
162 #ifdef SIMCLIST_WITH_THREADS
163 #include <pthread.h>
164 #endif
165 
166 #include "simclist.h"
167 
168 
169 /* minumum number of elements for sorting with quicksort instead of insertion */
170 #define SIMCLIST_MINQUICKSORTELS 24
171 
172 
173 /* list dump declarations */
174 #define SIMCLIST_DUMPFORMAT_VERSION 1 /* (short integer) version of fileformat managed by _dump* and _restore* functions */
175 
176 #define SIMCLIST_DUMPFORMAT_HEADERLEN 30 /* length of the header */
177 
178 /* header for a list dump */
180  uint16_t ver; /* version */
181  int32_t timestamp_sec; /* dump timestamp, seconds since UNIX Epoch */
182  int32_t timestamp_usec; /* dump timestamp, microseconds since timestamp_sec */
183  int32_t rndterm; /* random value terminator -- terminates the data sequence */
184 
185  uint32_t totlistlen; /* sum of every element' size, bytes */
186  uint32_t numels; /* number of elements */
187  uint32_t elemlen; /* bytes length of an element, for constant-size lists, <= 0 otherwise */
188  int32_t listhash; /* hash of the list at the time of dumping, or 0 if to be ignored */
189 };
190 
191 
192 
193 /* deletes tmp from list, with care wrt its position (head, tail, middle) */
194 static int list_drop_elem(list_t *restrict l, struct list_entry_s *tmp, unsigned int pos);
195 
196 /* set default values for initialized lists */
197 static int list_attributes_setdefaults(list_t *restrict l);
198 
199 #ifndef NDEBUG
200 /* check whether the list internal REPresentation is valid -- Costs O(n) */
201 static int list_repOk(const list_t *restrict l);
202 
203 /* check whether the list attribute set is valid -- Costs O(1) */
204 static int list_attrOk(const list_t *restrict l);
205 #endif
206 
207 /* do not inline, this is recursive */
208 static void list_sort_quicksort(list_t *restrict l, int versus,
209  unsigned int first, struct list_entry_s *fel,
210  unsigned int last, struct list_entry_s *lel);
211 
212 static inline void list_sort_selectionsort(list_t *restrict l, int versus,
213  unsigned int first, struct list_entry_s *fel,
214  unsigned int last, struct list_entry_s *lel);
215 
216 static void *list_get_minmax(const list_t *restrict l, int versus);
217 
218 static inline struct list_entry_s *list_findpos(const list_t *restrict l, int posstart);
219 
220 /*
221  * Random Number Generator
222  *
223  * The user is expected to seed the RNG (ie call srand()) if
224  * SIMCLIST_SYSTEM_RNG is defined.
225  *
226  * Otherwise, a self-contained RNG based on LCG is used; see
227  * http://en.wikipedia.org/wiki/Linear_congruential_generator .
228  *
229  * Facts pro local RNG:
230  * 1. no need for the user to call srand() on his own
231  * 2. very fast, possibly faster than OS
232  * 3. avoid interference with user's RNG
233  *
234  * Facts pro system RNG:
235  * 1. may be more accurate (irrelevant for SimCList randno purposes)
236  * 2. why reinvent the wheel
237  *
238  * Default to local RNG for user's ease of use.
239  */
240 
241 #ifdef SIMCLIST_SYSTEM_RNG
242 /* keep track whether we initialized already (non-0) or not (0) */
243 static unsigned random_seed = 0;
244 
245 /* use local RNG */
246 static inline void seed_random(void) {
247  if (random_seed == 0)
248  random_seed = (unsigned)getpid() ^ (unsigned)time(NULL);
249 }
250 
251 static inline long get_random(void) {
252  random_seed = (1664525 * random_seed + 1013904223);
253  return random_seed;
254 }
255 
256 #else
257 /* use OS's random generator */
258 # define seed_random()
259 # define get_random() (rand())
260 #endif
261 
262 
263 /* list initialization */
264 int list_init(list_t *restrict l) {
265  if (l == NULL) return -1;
266 
267  memset(l, 0, sizeof *l);
268 
269  seed_random();
270 
271  l->numels = 0;
272 
273  /* head/tail sentinels and mid pointer */
274  l->head_sentinel = (struct list_entry_s *)malloc(sizeof(struct list_entry_s));
275  l->tail_sentinel = (struct list_entry_s *)malloc(sizeof(struct list_entry_s));
276  if (NULL == l->tail_sentinel || NULL == l->head_sentinel)
277  return -1;
278 
279  l->head_sentinel->next = l->tail_sentinel;
280  l->tail_sentinel->prev = l->head_sentinel;
281  l->head_sentinel->prev = l->tail_sentinel->next = l->mid = NULL;
282  l->head_sentinel->data = l->tail_sentinel->data = NULL;
283 
284  /* iteration attributes */
285  l->iter_active = 0;
286  l->iter_pos = 0;
287  l->iter_curentry = NULL;
288 
289  /* free-list attributes */
290  l->spareels = (struct list_entry_s **)malloc(SIMCLIST_MAX_SPARE_ELEMS * sizeof(struct list_entry_s *));
291  l->spareelsnum = 0;
292  if (NULL == l->spareels)
293  return -1;
294 
295 #ifdef SIMCLIST_WITH_THREADS
296  l->threadcount = 0;
297 #endif
298 
299  if (list_attributes_setdefaults(l))
300  return -1;
301 
302  assert(list_repOk(l));
303  assert(list_attrOk(l));
304 
305  return 0;
306 }
307 
308 void list_destroy(list_t *restrict l) {
309  unsigned int i;
310 
311  list_clear(l);
312  for (i = 0; i < l->spareelsnum; i++) {
313  free(l->spareels[i]);
314  }
315  free(l->spareels);
316  free(l->head_sentinel);
317  free(l->tail_sentinel);
318 }
319 
320 int list_attributes_setdefaults(list_t *restrict l) {
321  l->attrs.comparator = NULL;
322  l->attrs.seeker = NULL;
323 
324  /* also free() element data when removing and element from the list */
325  l->attrs.meter = NULL;
326  l->attrs.copy_data = 0;
327 
328  l->attrs.hasher = NULL;
329 
330  /* serializer/unserializer */
331  l->attrs.serializer = NULL;
332  l->attrs.unserializer = NULL;
333 
334  assert(list_attrOk(l));
335 
336  return 0;
337 }
338 
339 /* setting list properties */
340 int list_attributes_comparator(list_t *restrict l, element_comparator comparator_fun) {
341  if (l == NULL) return -1;
342 
343  l->attrs.comparator = comparator_fun;
344 
345  assert(list_attrOk(l));
346 
347  return 0;
348 }
349 
350 int list_attributes_seeker(list_t *restrict l, element_seeker seeker_fun) {
351  if (l == NULL) return -1;
352 
353  l->attrs.seeker = seeker_fun;
354  assert(list_attrOk(l));
355 
356  return 0;
357 }
358 
359 int list_attributes_copy(list_t *restrict l, element_meter metric_fun, int copy_data) {
360  if (l == NULL || (metric_fun == NULL && copy_data != 0)) return -1;
361 
362  l->attrs.meter = metric_fun;
363  l->attrs.copy_data = copy_data;
364 
365  assert(list_attrOk(l));
366 
367  return 0;
368 }
369 
370 int list_attributes_hash_computer(list_t *restrict l, element_hash_computer hash_computer_fun) {
371  if (l == NULL) return -1;
372 
373  l->attrs.hasher = hash_computer_fun;
374  assert(list_attrOk(l));
375  return 0;
376 }
377 
378 int list_attributes_serializer(list_t *restrict l, element_serializer serializer_fun) {
379  if (l == NULL) return -1;
380 
381  l->attrs.serializer = serializer_fun;
382  assert(list_attrOk(l));
383  return 0;
384 }
385 
386 int list_attributes_unserializer(list_t *restrict l, element_unserializer unserializer_fun) {
387  if (l == NULL) return -1;
388 
389  l->attrs.unserializer = unserializer_fun;
390  assert(list_attrOk(l));
391  return 0;
392 }
393 
394 int list_append(list_t *restrict l, const void *data) {
395  return list_insert_at(l, data, l->numels);
396 }
397 
398 int list_prepend(list_t *restrict l, const void *data) {
399  return list_insert_at(l, data, 0);
400 }
401 
402 void *list_fetch(list_t *restrict l) {
403  return list_extract_at(l, 0);
404 }
405 
406 void *list_get_at(const list_t *restrict l, unsigned int pos) {
407  struct list_entry_s *tmp;
408 
409  tmp = list_findpos(l, pos);
410 
411  return (tmp != NULL ? tmp->data : NULL);
412 }
413 
414 void *list_get_max(const list_t *restrict l) {
415  return list_get_minmax(l, +1);
416 }
417 
418 void *list_get_min(const list_t *restrict l) {
419  return list_get_minmax(l, -1);
420 }
421 
422 /* REQUIRES {list->numels >= 1}
423  * return the min (versus < 0) or max value (v > 0) in l */
424 static void *list_get_minmax(const list_t *restrict l, int versus) {
425  void *curminmax;
426  struct list_entry_s *s;
427 
428  if (l->attrs.comparator == NULL || l->numels == 0)
429  return NULL;
430 
431  curminmax = l->head_sentinel->next->data;
432  for (s = l->head_sentinel->next->next; s != l->tail_sentinel; s = s->next) {
433  if (l->attrs.comparator(curminmax, s->data) * versus > 0)
434  curminmax = s->data;
435  }
436 
437  return curminmax;
438 }
439 
440 /* set tmp to point to element at index posstart in l */
441 static inline struct list_entry_s *list_findpos(const list_t *restrict l, int posstart) {
442  struct list_entry_s *ptr;
443  float x;
444  int i;
445 
446  if (NULL == l->head_sentinel || NULL == l->tail_sentinel)
447  return NULL;
448 
449  /* accept 1 slot overflow for fetching head and tail sentinels */
450  if (posstart < -1 || posstart > (int)l->numels) return NULL;
451 
452  x = (float)(posstart+1) / l->numels;
453  if (x <= 0.25) {
454  /* first quarter: get to posstart from head */
455  for (i = -1, ptr = l->head_sentinel; i < posstart; ptr = ptr->next, i++);
456  } else if (x < 0.5) {
457  /* second quarter: get to posstart from mid */
458  for (i = (l->numels-1)/2, ptr = l->mid; i > posstart; ptr = ptr->prev, i--);
459  } else if (x <= 0.75) {
460  /* third quarter: get to posstart from mid */
461  for (i = (l->numels-1)/2, ptr = l->mid; i < posstart; ptr = ptr->next, i++);
462  } else {
463  /* fourth quarter: get to posstart from tail */
464  for (i = l->numels, ptr = l->tail_sentinel; i > posstart; ptr = ptr->prev, i--);
465  }
466 
467  return ptr;
468 }
469 
470 void *list_extract_at(list_t *restrict l, unsigned int pos) {
471  struct list_entry_s *tmp;
472  void *data;
473 
474  if (l->iter_active || pos >= l->numels) return NULL;
475 
476  tmp = list_findpos(l, pos);
477  if (NULL == tmp)
478  return NULL;
479 
480  data = tmp->data;
481 
482  tmp->data = NULL; /* save data from list_drop_elem() free() */
483  list_drop_elem(l, tmp, pos);
484  l->numels--;
485 
486  assert(list_repOk(l));
487 
488  return data;
489 }
490 
491 int list_insert_at(list_t *restrict l, const void *data, unsigned int pos) {
492  struct list_entry_s *lent, *succ, *prec;
493 
494  if (l->iter_active || pos > l->numels) return -1;
495 
496  /* this code optimizes malloc() with a free-list */
497  if (l->spareelsnum > 0) {
498  lent = l->spareels[l->spareelsnum-1];
499  l->spareelsnum--;
500  } else {
501  lent = (struct list_entry_s *)malloc(sizeof(struct list_entry_s));
502  if (lent == NULL)
503  return -1;
504  }
505 
506  if (l->attrs.copy_data) {
507  /* make room for user' data (has to be copied) */
508  size_t datalen = l->attrs.meter(data);
509  lent->data = (struct list_entry_s *)malloc(datalen);
510  if (NULL == lent->data)
511  return -1;
512  memcpy(lent->data, data, datalen);
513  } else {
514  lent->data = (void*)data;
515  }
516 
517  /* actually append element */
518  prec = list_findpos(l, pos-1);
519  if (NULL == prec)
520  return -1;
521  succ = prec->next;
522 
523  prec->next = lent;
524  lent->prev = prec;
525  lent->next = succ;
526  succ->prev = lent;
527 
528  l->numels++;
529 
530  /* fix mid pointer */
531  if (l->numels == 1) { /* first element, set pointer */
532  l->mid = lent;
533  } else if (l->numels % 2) { /* now odd */
534  if (pos >= (l->numels-1)/2) l->mid = l->mid->next;
535  } else { /* now even */
536  if (pos <= (l->numels-1)/2) l->mid = l->mid->prev;
537  }
538 
539  assert(list_repOk(l));
540 
541  return 1;
542 }
543 
544 int list_delete(list_t *restrict l, const void *data) {
545  int pos, r;
546 
547  pos = list_locate(l, data);
548  if (pos < 0)
549  return -1;
550 
551  r = list_delete_at(l, pos);
552  if (r < 0)
553  return -1;
554 
555  assert(list_repOk(l));
556 
557  return 0;
558 }
559 
560 int list_delete_at(list_t *restrict l, unsigned int pos) {
561  struct list_entry_s *delendo;
562 
563 
564  if (l->iter_active || pos >= l->numels) return -1;
565 
566  delendo = list_findpos(l, pos);
567 
568  list_drop_elem(l, delendo, pos);
569 
570  l->numels--;
571 
572 
573  assert(list_repOk(l));
574 
575  return 0;
576 }
577 
578 int list_delete_range(list_t *restrict l, unsigned int posstart, unsigned int posend) {
579  struct list_entry_s *lastvalid, *tmp, *tmp2;
580  unsigned int numdel, midposafter, i;
581  int movedx;
582 
583  if (l->iter_active || posend < posstart || posend >= l->numels) return -1;
584 
585  numdel = posend - posstart + 1;
586  if (numdel == l->numels) return list_clear(l);
587 
588  tmp = list_findpos(l, posstart); /* first el to be deleted */
589  lastvalid = tmp->prev; /* last valid element */
590 
591  midposafter = (l->numels-1-numdel)/2;
592 
593  midposafter = midposafter < posstart ? midposafter : midposafter+numdel;
594  movedx = midposafter - (l->numels-1)/2;
595 
596  if (movedx > 0) { /* move right */
597  for (i = 0; i < (unsigned int)movedx; l->mid = l->mid->next, i++);
598  } else { /* move left */
599  movedx = -movedx;
600  for (i = 0; i < (unsigned int)movedx; l->mid = l->mid->prev, i++);
601  }
602 
603  assert(posstart == 0 || lastvalid != l->head_sentinel);
604  i = posstart;
605  if (l->attrs.copy_data) {
606  /* also free element data */
607  for (; i <= posend; i++) {
608  tmp2 = tmp;
609  tmp = tmp->next;
610  if (tmp2->data != NULL) free(tmp2->data);
611  if (l->spareelsnum < SIMCLIST_MAX_SPARE_ELEMS) {
612  l->spareels[l->spareelsnum++] = tmp2;
613  } else {
614  free(tmp2);
615  }
616  }
617  } else {
618  /* only free containers */
619  for (; i <= posend; i++) {
620  tmp2 = tmp;
621  tmp = tmp->next;
622  if (l->spareelsnum < SIMCLIST_MAX_SPARE_ELEMS) {
623  l->spareels[l->spareelsnum++] = tmp2;
624  } else {
625  free(tmp2);
626  }
627  }
628  }
629  assert(i == posend+1 && (posend != l->numels || tmp == l->tail_sentinel));
630 
631  lastvalid->next = tmp;
632  tmp->prev = lastvalid;
633 
634  l->numels -= posend - posstart + 1;
635 
636  assert(list_repOk(l));
637 
638  return numdel;
639 }
640 
641 int list_clear(list_t *restrict l) {
642  struct list_entry_s *s;
643  unsigned int numels;
644 
645  /* will be returned */
646  numels = l->numels;
647 
648  if (l->iter_active) return -1;
649 
650  if (l->head_sentinel && l->tail_sentinel) {
651  if (l->attrs.copy_data) { /* also free user data */
652  /* spare a loop conditional with two loops: spareing elems and freeing elems */
653  for (s = l->head_sentinel->next; l->spareelsnum < SIMCLIST_MAX_SPARE_ELEMS && s != l->tail_sentinel; s = s->next) {
654  /* move elements as spares as long as there is room */
655  if (s->data != NULL) free(s->data);
656  l->spareels[l->spareelsnum++] = s;
657  }
658  while (s != l->tail_sentinel) {
659  /* free the remaining elems */
660  if (s->data != NULL) free(s->data);
661  s = s->next;
662  free(s->prev);
663  }
664  l->head_sentinel->next = l->tail_sentinel;
665  l->tail_sentinel->prev = l->head_sentinel;
666  } else { /* only free element containers */
667  /* spare a loop conditional with two loops: spareing elems and freeing elems */
668  for (s = l->head_sentinel->next; l->spareelsnum < SIMCLIST_MAX_SPARE_ELEMS && s != l->tail_sentinel; s = s->next) {
669  /* move elements as spares as long as there is room */
670  l->spareels[l->spareelsnum++] = s;
671  }
672  while (s != l->tail_sentinel) {
673  /* free the remaining elems */
674  s = s->next;
675  free(s->prev);
676  }
677  l->head_sentinel->next = l->tail_sentinel;
678  l->tail_sentinel->prev = l->head_sentinel;
679  }
680  }
681  l->numels = 0;
682  l->mid = NULL;
683 
684  assert(list_repOk(l));
685 
686  return numels;
687 }
688 
689 unsigned int list_size(const list_t *restrict l) {
690  return l->numels;
691 }
692 
693 int list_empty(const list_t *restrict l) {
694  return (l->numels == 0);
695 }
696 
697 int list_locate(const list_t *restrict l, const void *data) {
698  struct list_entry_s *el;
699  int pos = 0;
700 
701  if (NULL == l->head_sentinel || NULL == l->tail_sentinel)
702  return -1;
703 
704  if (l->attrs.comparator != NULL) {
705  /* use comparator */
706  for (el = l->head_sentinel->next; el != l->tail_sentinel; el = el->next, pos++) {
707  if (l->attrs.comparator(data, el->data) == 0) break;
708  }
709  } else {
710  /* compare references */
711  for (el = l->head_sentinel->next; el != l->tail_sentinel; el = el->next, pos++) {
712  if (el->data == data) break;
713  }
714  }
715  if (el == l->tail_sentinel) return -1;
716 
717  return pos;
718 }
719 
720 void *list_seek(list_t *restrict l, const void *indicator) {
721  const struct list_entry_s *iter;
722 
723  if (l->attrs.seeker == NULL) return NULL;
724 
725  if (NULL == l->head_sentinel || NULL == l->tail_sentinel)
726  return NULL;
727 
728  for (iter = l->head_sentinel->next; iter != l->tail_sentinel; iter = iter->next) {
729  if (l->attrs.seeker(iter->data, indicator) != 0) return iter->data;
730  }
731 
732  return NULL;
733 }
734 
735 int list_contains(const list_t *restrict l, const void *data) {
736  return (list_locate(l, data) >= 0);
737 }
738 
739 int list_concat(const list_t *l1, const list_t *l2, list_t *restrict dest) {
740  struct list_entry_s *el, *srcel;
741  unsigned int cnt;
742  int err;
743 
744 
745  if (l1 == NULL || l2 == NULL || dest == NULL || l1 == dest || l2 == dest)
746  return -1;
747 
748  if (NULL == l1->head_sentinel || NULL == l1->tail_sentinel
749  || NULL == l2->head_sentinel || NULL == l2->tail_sentinel)
750  return -1;
751 
752  if (list_init(dest))
753  return -1;
754 
755  dest->numels = l1->numels + l2->numels;
756  if (dest->numels == 0)
757  return 0;
758 
759  /* copy list1 */
760  srcel = l1->head_sentinel->next;
761  el = dest->head_sentinel;
762  while (srcel != l1->tail_sentinel) {
763  el->next = (struct list_entry_s *)malloc(sizeof(struct list_entry_s));
764  if (NULL == el->next)
765  return -1;
766  el->next->prev = el;
767  el = el->next;
768  el->data = srcel->data;
769  srcel = srcel->next;
770  }
771  dest->mid = el; /* approximate position (adjust later) */
772  /* copy list 2 */
773  srcel = l2->head_sentinel->next;
774  while (srcel != l2->tail_sentinel) {
775  el->next = (struct list_entry_s *)malloc(sizeof(struct list_entry_s));
776  if (NULL == el->next)
777  return -1;
778  el->next->prev = el;
779  el = el->next;
780  el->data = srcel->data;
781  srcel = srcel->next;
782  }
783  el->next = dest->tail_sentinel;
784  dest->tail_sentinel->prev = el;
785 
786  /* fix mid pointer */
787  err = l2->numels - l1->numels;
788  if ((err+1)/2 > 0) { /* correct pos RIGHT (err-1)/2 moves */
789  err = (err+1)/2;
790  for (cnt = 0; cnt < (unsigned int)err; cnt++) dest->mid = dest->mid->next;
791  } else if (err/2 < 0) { /* correct pos LEFT (err/2)-1 moves */
792  err = -err/2;
793  for (cnt = 0; cnt < (unsigned int)err; cnt++) dest->mid = dest->mid->prev;
794  }
795 
796  assert(!(list_repOk(l1) && list_repOk(l2)) || list_repOk(dest));
797 
798  return 0;
799 }
800 
801 int list_sort(list_t *restrict l, int versus) {
802  if (l->iter_active || l->attrs.comparator == NULL) /* cannot modify list in the middle of an iteration */
803  return -1;
804 
805  if (l->numels <= 1)
806  return 0;
807 
808  if (NULL == l->head_sentinel || NULL == l->tail_sentinel)
809  return -1;
810 
811  list_sort_quicksort(l, versus, 0, l->head_sentinel->next, l->numels-1, l->tail_sentinel->prev);
812  assert(list_repOk(l));
813  return 0;
814 }
815 
816 #ifdef SIMCLIST_WITH_THREADS
817 struct list_sort_wrappedparams {
818  list_t *restrict l;
819  int versus;
820  unsigned int first, last;
821  struct list_entry_s *fel, *lel;
822 };
823 
824 static void *list_sort_quicksort_threadwrapper(void *wrapped_params) {
825  struct list_sort_wrappedparams *wp = (struct list_sort_wrappedparams *)wrapped_params;
826  list_sort_quicksort(wp->l, wp->versus, wp->first, wp->fel, wp->last, wp->lel);
827  free(wp);
828  pthread_exit(NULL);
829  return NULL;
830 }
831 #endif
832 
833 static inline void list_sort_selectionsort(list_t *restrict l, int versus,
834  unsigned int first, struct list_entry_s *fel,
835  unsigned int last, struct list_entry_s *lel) {
836  struct list_entry_s *cursor, *toswap, *firstunsorted;
837  void *tmpdata;
838 
839  if (last <= first) /* <= 1-element lists are always sorted */
840  return;
841 
842  for (firstunsorted = fel; firstunsorted != lel; firstunsorted = firstunsorted->next) {
843  /* find min or max in the remainder of the list */
844  for (toswap = firstunsorted, cursor = firstunsorted->next; cursor != lel->next; cursor = cursor->next)
845  if (l->attrs.comparator(toswap->data, cursor->data) * -versus > 0) toswap = cursor;
846  if (toswap != firstunsorted) { /* swap firstunsorted with toswap */
847  tmpdata = firstunsorted->data;
848  firstunsorted->data = toswap->data;
849  toswap->data = tmpdata;
850  }
851  }
852 }
853 
854 static void list_sort_quicksort(list_t *restrict l, int versus,
855  unsigned int first, struct list_entry_s *fel,
856  unsigned int last, struct list_entry_s *lel) {
857  unsigned int pivotid;
858  unsigned int i;
859  register struct list_entry_s *pivot;
860  struct list_entry_s *left, *right;
861  void *tmpdata;
862 #ifdef SIMCLIST_WITH_THREADS
863  pthread_t tid;
864  int traised;
865 #endif
866 
867 
868  if (last <= first) /* <= 1-element lists are always sorted */
869  return;
870 
871  if (last - first+1 <= SIMCLIST_MINQUICKSORTELS) {
872  list_sort_selectionsort(l, versus, first, fel, last, lel);
873  return;
874  }
875 
876  /* base of iteration: one element list */
877  if (! (last > first)) return;
878 
879  pivotid = (get_random() % (last - first + 1));
880  /* pivotid = (last - first + 1) / 2; */
881 
882  /* find pivot */
883  if (pivotid < (last - first + 1)/2) {
884  for (i = 0, pivot = fel; i < pivotid; pivot = pivot->next, i++);
885  } else {
886  for (i = last - first, pivot = lel; i > pivotid; pivot = pivot->prev, i--);
887  }
888 
889  /* smaller PIVOT bigger */
890  left = fel;
891  right = lel;
892  /* iterate --- left ---> PIV <--- right --- */
893  while (left != pivot && right != pivot) {
894  for (; left != pivot && (l->attrs.comparator(left->data, pivot->data) * -versus <= 0); left = left->next);
895  /* left points to a smaller element, or to pivot */
896  for (; right != pivot && (l->attrs.comparator(right->data, pivot->data) * -versus >= 0); right = right->prev);
897  /* right points to a bigger element, or to pivot */
898  if (left != pivot && right != pivot) {
899  /* swap, then move iterators */
900  tmpdata = left->data;
901  left->data = right->data;
902  right->data = tmpdata;
903 
904  left = left->next;
905  right = right->prev;
906  }
907  }
908 
909  /* now either left points to pivot (end run), or right */
910  if (right == pivot) { /* left part longer */
911  while (left != pivot) {
912  if (l->attrs.comparator(left->data, pivot->data) * -versus > 0) {
913  tmpdata = left->data;
914  left->data = pivot->prev->data;
915  pivot->prev->data = pivot->data;
916  pivot->data = tmpdata;
917  pivot = pivot->prev;
918  pivotid--;
919  if (pivot == left) break;
920  } else {
921  left = left->next;
922  }
923  }
924  } else { /* right part longer */
925  while (right != pivot) {
926  if (l->attrs.comparator(right->data, pivot->data) * -versus < 0) {
927  /* move current right before pivot */
928  tmpdata = right->data;
929  right->data = pivot->next->data;
930  pivot->next->data = pivot->data;
931  pivot->data = tmpdata;
932  pivot = pivot->next;
933  pivotid++;
934  if (pivot == right) break;
935  } else {
936  right = right->prev;
937  }
938  }
939  }
940 
941  /* sort sublists A and B : |---A---| pivot |---B---| */
942 
943 #ifdef SIMCLIST_WITH_THREADS
944  traised = 0;
945  if (pivotid > 0) {
946  /* prepare wrapped args, then start thread */
947  if (l->threadcount < SIMCLIST_MAXTHREADS-1) {
948  struct list_sort_wrappedparams *wp = (struct list_sort_wrappedparams *)malloc(sizeof(struct list_sort_wrappedparams));
949  if (NULL == wp)
950  return -1;
951  l->threadcount++;
952  traised = 1;
953  wp->l = l;
954  wp->versus = versus;
955  wp->first = first;
956  wp->fel = fel;
957  wp->last = first+pivotid-1;
958  wp->lel = pivot->prev;
959  if (pthread_create(&tid, NULL, list_sort_quicksort_threadwrapper, wp) != 0) {
960  free(wp);
961  traised = 0;
962  list_sort_quicksort(l, versus, first, fel, first+pivotid-1, pivot->prev);
963  }
964  } else {
965  list_sort_quicksort(l, versus, first, fel, first+pivotid-1, pivot->prev);
966  }
967  }
968  if (first + pivotid < last) list_sort_quicksort(l, versus, first+pivotid+1, pivot->next, last, lel);
969  if (traised) {
970  pthread_join(tid, (void **)NULL);
971  l->threadcount--;
972  }
973 #else
974  if (pivotid > 0) list_sort_quicksort(l, versus, first, fel, first+pivotid-1, pivot->prev);
975  if (first + pivotid < last) list_sort_quicksort(l, versus, first+pivotid+1, pivot->next, last, lel);
976 #endif
977 }
978 
979 int list_iterator_start(list_t *restrict l) {
980  if (l->iter_active) return 0;
981  if (NULL == l->head_sentinel)
982  return -1;
983  l->iter_pos = 0;
984  l->iter_active = 1;
985  l->iter_curentry = l->head_sentinel->next;
986  return 1;
987 }
988 
989 void *list_iterator_next(list_t *restrict l) {
990  void *toret;
991 
992  if (! l->iter_active) return NULL;
993 
994  toret = l->iter_curentry->data;
995  l->iter_curentry = l->iter_curentry->next;
996  l->iter_pos++;
997 
998  return toret;
999 }
1000 
1001 int list_iterator_hasnext(const list_t *restrict l) {
1002  if (! l->iter_active) return 0;
1003  return (l->iter_pos < l->numels);
1004 }
1005 
1006 int list_iterator_stop(list_t *restrict l) {
1007  if (! l->iter_active) return 0;
1008  l->iter_pos = 0;
1009  l->iter_active = 0;
1010  return 1;
1011 }
1012 
1013 int list_hash(const list_t *restrict l, list_hash_t *restrict hash) {
1014  struct list_entry_s *x;
1015  list_hash_t tmphash;
1016 
1017  assert(hash != NULL);
1018 
1019  tmphash = l->numels * 2 + 100;
1020  if (l->attrs.hasher == NULL) {
1021 #ifdef SIMCLIST_ALLOW_LOCATIONBASED_HASHES
1022  /* ENABLE WITH CARE !! */
1023 #warning "Memlocation-based hash is consistent only for testing modification in the same program run."
1024  int i;
1025 
1026  /* only use element references */
1027  for (x = l->head_sentinel->next; x != l->tail_sentinel; x = x->next) {
1028  for (i = 0; i < sizeof(x->data); i++) {
1029  tmphash += (tmphash ^ (uintptr_t)x->data);
1030  }
1031  tmphash += tmphash % l->numels;
1032  }
1033 #else
1034  return -1;
1035 #endif
1036  } else {
1037  /* hash each element with the user-given function */
1038  for (x = l->head_sentinel->next; x != l->tail_sentinel; x = x->next) {
1039  tmphash += tmphash ^ l->attrs.hasher(x->data);
1040  tmphash += tmphash % l->numels;
1041  }
1042  }
1043 
1044  *hash = tmphash;
1045 
1046  return 0;
1047 }
1048 
1049 #ifndef SIMCLIST_NO_DUMPRESTORE
1050 int list_dump_getinfo_filedescriptor(int fd, list_dump_info_t *restrict info) {
1051  int32_t terminator_head, terminator_tail;
1052  uint32_t elemlen;
1053  off_t hop;
1054 
1055 
1056  /* version */
1057  READ_ERRCHECK(fd, & info->version, sizeof(info->version));
1058  info->version = ntohs(info->version);
1059  if (info->version > SIMCLIST_DUMPFORMAT_VERSION) {
1060  errno = EILSEQ;
1061  return -1;
1062  }
1063 
1064  /* timestamp.tv_sec and timestamp.tv_usec */
1065  READ_ERRCHECK(fd, & info->timestamp.tv_sec, sizeof(info->timestamp.tv_sec));
1066  info->timestamp.tv_sec = ntohl(info->timestamp.tv_sec);
1067  READ_ERRCHECK(fd, & info->timestamp.tv_usec, sizeof(info->timestamp.tv_usec));
1068  info->timestamp.tv_usec = ntohl(info->timestamp.tv_usec);
1069 
1070  /* list terminator (to check thereafter) */
1071  READ_ERRCHECK(fd, & terminator_head, sizeof(terminator_head));
1072  terminator_head = ntohl(terminator_head);
1073 
1074  /* list size */
1075  READ_ERRCHECK(fd, & info->list_size, sizeof(info->list_size));
1076  info->list_size = ntohl(info->list_size);
1077 
1078  /* number of elements */
1079  READ_ERRCHECK(fd, & info->list_numels, sizeof(info->list_numels));
1080  info->list_numels = ntohl(info->list_numels);
1081 
1082  /* length of each element (for checking for consistency) */
1083  READ_ERRCHECK(fd, & elemlen, sizeof(elemlen));
1084  elemlen = ntohl(elemlen);
1085 
1086  /* list hash */
1087  READ_ERRCHECK(fd, & info->list_hash, sizeof(info->list_hash));
1088  info->list_hash = ntohl(info->list_hash);
1089 
1090  /* check consistency */
1091  if (elemlen > 0) {
1092  /* constant length, hop by size only */
1093  hop = info->list_size;
1094  } else {
1095  /* non-constant length, hop by size + all element length blocks */
1096  hop = info->list_size + elemlen*info->list_numels;
1097  }
1098  if (lseek(fd, hop, SEEK_CUR) == -1) {
1099  return -1;
1100  }
1101 
1102  /* read the trailing value and compare with terminator_head */
1103  READ_ERRCHECK(fd, & terminator_tail, sizeof(terminator_tail));
1104  terminator_tail = ntohl(terminator_tail);
1105 
1106  if (terminator_head == terminator_tail)
1107  info->consistent = 1;
1108  else
1109  info->consistent = 0;
1110 
1111  return 0;
1112 }
1113 
1114 int list_dump_getinfo_file(const char *restrict filename, list_dump_info_t *restrict info) {
1115  int fd, ret;
1116 
1117  fd = open(filename, O_RDONLY, 0);
1118  if (fd < 0) return -1;
1119 
1120  ret = list_dump_getinfo_filedescriptor(fd, info);
1121  close(fd);
1122 
1123  return ret;
1124 }
1125 
1126 int list_dump_filedescriptor(const list_t *restrict l, int fd, size_t *restrict len) {
1127  struct list_entry_s *x;
1128  void *ser_buf;
1129  uint32_t bufsize;
1130  struct timeval timeofday;
1131  struct list_dump_header_s header;
1132 
1133  if (l->attrs.meter == NULL && l->attrs.serializer == NULL) {
1134  errno = ENOTTY;
1135  return -1;
1136  }
1137 
1138  /**** DUMP FORMAT ****
1139 
1140  [ ver timestamp | totlen numels elemlen hash | DATA ]
1141 
1142  where DATA can be:
1143  @ for constant-size list (element size is constant; elemlen > 0)
1144  [ elem elem ... elem ]
1145  @ for other lists (element size dictated by element_meter each time; elemlen <= 0)
1146  [ size elem size elem ... size elem ]
1147 
1148  all integers are encoded in NETWORK BYTE FORMAT
1149  *****/
1150 
1151 
1152  /* prepare HEADER */
1153  /* version */
1154  header.ver = htons( SIMCLIST_DUMPFORMAT_VERSION );
1155 
1156  /* timestamp */
1157  gettimeofday(&timeofday, NULL);
1158  header.timestamp_sec = htonl(timeofday.tv_sec);
1159  header.timestamp_usec = htonl(timeofday.tv_usec);
1160 
1161  header.rndterm = htonl((int32_t)get_random());
1162 
1163  /* total list size is postprocessed afterwards */
1164 
1165  /* number of elements */
1166  header.numels = htonl(l->numels);
1167 
1168  /* include an hash, if possible */
1169  if (l->attrs.hasher != NULL) {
1170  if (htonl(list_hash(l, & header.listhash)) != 0) {
1171  /* could not compute list hash! */
1172  return -1;
1173  }
1174  } else {
1175  header.listhash = htonl(0);
1176  }
1177 
1178  header.totlistlen = header.elemlen = 0;
1179 
1180  /* leave room for the header at the beginning of the file */
1181  if (lseek(fd, SIMCLIST_DUMPFORMAT_HEADERLEN, SEEK_SET) < 0) {
1182  /* errno set by lseek() */
1183  return -1;
1184  }
1185 
1186  /* write CONTENT */
1187  if (l->numels > 0) {
1188  /* SPECULATE that the list has constant element size */
1189 
1190  if (l->attrs.serializer != NULL) { /* user user-specified serializer */
1191  /* get preliminary length of serialized element in header.elemlen */
1192  ser_buf = l->attrs.serializer(l->head_sentinel->next->data, & header.elemlen);
1193  free(ser_buf);
1194  /* request custom serialization of each element */
1195  for (x = l->head_sentinel->next; x != l->tail_sentinel; x = x->next) {
1196  ser_buf = l->attrs.serializer(x->data, &bufsize);
1197  header.totlistlen += bufsize;
1198  if (header.elemlen != 0) { /* continue on speculation */
1199  if (header.elemlen != bufsize) {
1200  free(ser_buf);
1201  /* constant element length speculation broken! */
1202  header.elemlen = 0;
1203  header.totlistlen = 0;
1204  x = l->head_sentinel;
1205  if (lseek(fd, SIMCLIST_DUMPFORMAT_HEADERLEN, SEEK_SET) < 0) {
1206  /* errno set by lseek() */
1207  return -1;
1208  }
1209  /* restart from the beginning */
1210  continue;
1211  }
1212  /* speculation confirmed */
1213  WRITE_ERRCHECK(fd, ser_buf, bufsize);
1214  } else { /* speculation found broken */
1215  WRITE_ERRCHECK(fd, & bufsize, sizeof(size_t));
1216  WRITE_ERRCHECK(fd, ser_buf, bufsize);
1217  }
1218  free(ser_buf);
1219  }
1220  } else if (l->attrs.meter != NULL) {
1221  header.elemlen = (uint32_t)l->attrs.meter(l->head_sentinel->next->data);
1222 
1223  /* serialize the element straight from its data */
1224  for (x = l->head_sentinel->next; x != l->tail_sentinel; x = x->next) {
1225  bufsize = l->attrs.meter(x->data);
1226  header.totlistlen += bufsize;
1227  if (header.elemlen != 0) {
1228  if (header.elemlen != bufsize) {
1229  /* constant element length speculation broken! */
1230  header.elemlen = 0;
1231  header.totlistlen = 0;
1232  x = l->head_sentinel;
1233  /* restart from the beginning */
1234  continue;
1235  }
1236  WRITE_ERRCHECK(fd, x->data, bufsize);
1237  } else {
1238  WRITE_ERRCHECK(fd, &bufsize, sizeof(size_t));
1239  WRITE_ERRCHECK(fd, x->data, bufsize);
1240  }
1241  }
1242  }
1243  /* adjust endianness */
1244  header.elemlen = htonl(header.elemlen);
1245  header.totlistlen = htonl(header.totlistlen);
1246  }
1247 
1248  /* write random terminator */
1249  WRITE_ERRCHECK(fd, & header.rndterm, sizeof(header.rndterm)); /* list terminator */
1250 
1251 
1252  /* write header */
1253  lseek(fd, 0, SEEK_SET);
1254 
1255  WRITE_ERRCHECK(fd, & header.ver, sizeof(header.ver)); /* version */
1256  WRITE_ERRCHECK(fd, & header.timestamp_sec, sizeof(header.timestamp_sec)); /* timestamp seconds */
1257  WRITE_ERRCHECK(fd, & header.timestamp_usec, sizeof(header.timestamp_usec)); /* timestamp microseconds */
1258  WRITE_ERRCHECK(fd, & header.rndterm, sizeof(header.rndterm)); /* random terminator */
1259 
1260  WRITE_ERRCHECK(fd, & header.totlistlen, sizeof(header.totlistlen)); /* total length of elements */
1261  WRITE_ERRCHECK(fd, & header.numels, sizeof(header.numels)); /* number of elements */
1262  WRITE_ERRCHECK(fd, & header.elemlen, sizeof(header.elemlen)); /* size of each element, or 0 for independent */
1263  WRITE_ERRCHECK(fd, & header.listhash, sizeof(header.listhash)); /* list hash, or 0 for "ignore" */
1264 
1265 
1266  /* possibly store total written length in "len" */
1267  if (len != NULL) {
1268  *len = sizeof(header) + ntohl(header.totlistlen);
1269  }
1270 
1271  return 0;
1272 }
1273 
1274 int list_restore_filedescriptor(list_t *restrict l, int fd, size_t *restrict len) {
1275  struct list_dump_header_s header;
1276  unsigned long cnt;
1277  void *buf;
1278  uint32_t elsize, totreadlen, totmemorylen;
1279 
1280  memset(& header, 0, sizeof(header));
1281 
1282  /* read header */
1283 
1284  /* version */
1285  READ_ERRCHECK(fd, &header.ver, sizeof(header.ver));
1286  header.ver = ntohs(header.ver);
1287  if (header.ver != SIMCLIST_DUMPFORMAT_VERSION) {
1288  errno = EILSEQ;
1289  return -1;
1290  }
1291 
1292  /* timestamp */
1293  READ_ERRCHECK(fd, & header.timestamp_sec, sizeof(header.timestamp_sec));
1294  header.timestamp_sec = ntohl(header.timestamp_sec);
1295  READ_ERRCHECK(fd, & header.timestamp_usec, sizeof(header.timestamp_usec));
1296  header.timestamp_usec = ntohl(header.timestamp_usec);
1297 
1298  /* list terminator */
1299  READ_ERRCHECK(fd, & header.rndterm, sizeof(header.rndterm));
1300 
1301  header.rndterm = ntohl(header.rndterm);
1302 
1303  /* total list size */
1304  READ_ERRCHECK(fd, & header.totlistlen, sizeof(header.totlistlen));
1305  header.totlistlen = ntohl(header.totlistlen);
1306 
1307  /* number of elements */
1308  READ_ERRCHECK(fd, & header.numels, sizeof(header.numels));
1309  header.numels = ntohl(header.numels);
1310 
1311  /* length of every element, or '0' = variable */
1312  READ_ERRCHECK(fd, & header.elemlen, sizeof(header.elemlen));
1313  header.elemlen = ntohl(header.elemlen);
1314 
1315  /* list hash, or 0 = 'ignore' */
1316  READ_ERRCHECK(fd, & header.listhash, sizeof(header.listhash));
1317  header.listhash = ntohl(header.listhash);
1318 
1319 
1320  /* read content */
1321  totreadlen = totmemorylen = 0;
1322  if (header.elemlen > 0) {
1323  /* elements have constant size = header.elemlen */
1324  if (l->attrs.unserializer != NULL) {
1325  /* use unserializer */
1326  buf = malloc(header.elemlen);
1327  if (NULL == buf)
1328  return -1;
1329  for (cnt = 0; cnt < header.numels; cnt++) {
1330  READ_ERRCHECK(fd, buf, header.elemlen);
1331  list_append(l, l->attrs.unserializer(buf, & elsize));
1332  totmemorylen += elsize;
1333  }
1334  } else {
1335  /* copy verbatim into memory */
1336  for (cnt = 0; cnt < header.numels; cnt++) {
1337  buf = malloc(header.elemlen);
1338  if (NULL == buf)
1339  return -1;
1340  READ_ERRCHECK(fd, buf, header.elemlen);
1341  list_append(l, buf);
1342  }
1343  totmemorylen = header.numels * header.elemlen;
1344  }
1345  totreadlen = header.numels * header.elemlen;
1346  } else {
1347  /* elements have variable size. Each element is preceded by its size */
1348  if (l->attrs.unserializer != NULL) {
1349  /* use unserializer */
1350  for (cnt = 0; cnt < header.numels; cnt++) {
1351  READ_ERRCHECK(fd, & elsize, sizeof(elsize));
1352  buf = malloc((size_t)elsize);
1353  if (NULL == buf)
1354  return -1;
1355  READ_ERRCHECK(fd, buf, elsize);
1356  totreadlen += elsize;
1357  list_append(l, l->attrs.unserializer(buf, & elsize));
1358  totmemorylen += elsize;
1359  }
1360  } else {
1361  /* copy verbatim into memory */
1362  for (cnt = 0; cnt < header.numels; cnt++) {
1363  READ_ERRCHECK(fd, & elsize, sizeof(elsize));
1364  buf = malloc(elsize);
1365  if (NULL == buf)
1366  return -1;
1367  READ_ERRCHECK(fd, buf, elsize);
1368  totreadlen += elsize;
1369  list_append(l, buf);
1370  }
1371  totmemorylen = totreadlen;
1372  }
1373  }
1374 
1375  READ_ERRCHECK(fd, &elsize, sizeof(elsize)); /* read list terminator */
1376  elsize = ntohl(elsize);
1377 
1378  /* possibly verify the list consistency */
1379  /* wrt hash */
1380  /* don't do that
1381  if (header.listhash != 0 && header.listhash != list_hash(l)) {
1382  errno = ECANCELED;
1383  return -1;
1384  }
1385  */
1386 
1387  /* wrt header */
1388  if (totreadlen != header.totlistlen && (int32_t)elsize == header.rndterm) {
1389  errno = EPROTO;
1390  return -1;
1391  }
1392 
1393  /* wrt file */
1394  if (lseek(fd, 0, SEEK_CUR) != lseek(fd, 0, SEEK_END)) {
1395  errno = EPROTO;
1396  return -1;
1397  }
1398 
1399  if (len != NULL) {
1400  *len = totmemorylen;
1401  }
1402 
1403  return 0;
1404 }
1405 
1406 int list_dump_file(const list_t *restrict l, const char *restrict filename, size_t *restrict len) {
1407  int fd, oflag, mode;
1408 
1409 #ifndef _WIN32
1410  oflag = O_RDWR | O_CREAT | O_TRUNC;
1411  mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
1412 #else
1413  oflag = _O_RDWR | _O_CREAT | _O_TRUNC;
1414  mode = _S_IRUSR | _S_IWUSR | _S_IRGRP | _S_IROTH;
1415 #endif
1416  fd = open(filename, oflag, mode);
1417  if (fd < 0) return -1;
1418 
1419  list_dump_filedescriptor(l, fd, len);
1420  close(fd);
1421 
1422  return 0;
1423 }
1424 
1425 int list_restore_file(list_t *restrict l, const char *restrict filename, size_t *restrict len) {
1426  int fd;
1427 
1428  fd = open(filename, O_RDONLY, 0);
1429  if (fd < 0) return -1;
1430 
1431  list_restore_filedescriptor(l, fd, len);
1432  close(fd);
1433 
1434  return 0;
1435 }
1436 #endif /* ifndef SIMCLIST_NO_DUMPRESTORE */
1437 
1438 
1439 static int list_drop_elem(list_t *restrict l, struct list_entry_s *tmp, unsigned int pos) {
1440  if (tmp == NULL) return -1;
1441 
1442  /* fix mid pointer. This is wrt the PRE situation */
1443  if (l->numels % 2) { /* now odd */
1444  /* sort out the base case by hand */
1445  if (l->numels == 1) l->mid = NULL;
1446  else if (pos >= l->numels/2) l->mid = l->mid->prev;
1447  } else { /* now even */
1448  if (pos < l->numels/2) l->mid = l->mid->next;
1449  }
1450 
1451  tmp->prev->next = tmp->next;
1452  tmp->next->prev = tmp->prev;
1453 
1454  /* free what's to be freed */
1455  if (l->attrs.copy_data && tmp->data != NULL)
1456  free(tmp->data);
1457 
1458  if (l->spareels != NULL && l->spareelsnum < SIMCLIST_MAX_SPARE_ELEMS) {
1459  l->spareels[l->spareelsnum++] = tmp;
1460  } else {
1461  free(tmp);
1462  }
1463 
1464  return 0;
1465 }
1466 
1467 /* ready-made comparators and meters */
1468 #define SIMCLIST_NUMBER_COMPARATOR(type) int list_comparator_##type(const void *a, const void *b) { return( *(type *)a < *(type *)b) - (*(type *)a > *(type *)b); }
1469 
1470 SIMCLIST_NUMBER_COMPARATOR(int8_t)
1471 SIMCLIST_NUMBER_COMPARATOR(int16_t)
1472 SIMCLIST_NUMBER_COMPARATOR(int32_t)
1473 SIMCLIST_NUMBER_COMPARATOR(int64_t)
1474 
1475 SIMCLIST_NUMBER_COMPARATOR(uint8_t)
1476 SIMCLIST_NUMBER_COMPARATOR(uint16_t)
1477 SIMCLIST_NUMBER_COMPARATOR(uint32_t)
1478 SIMCLIST_NUMBER_COMPARATOR(uint64_t)
1479 
1480 SIMCLIST_NUMBER_COMPARATOR(float)
1481 SIMCLIST_NUMBER_COMPARATOR(double)
1482 
1483 int list_comparator_string(const void *a, const void *b) { return strcmp((const char *)b, (const char *)a); }
1484 
1485 /* ready-made metric functions */
1486 #define SIMCLIST_METER(type) size_t list_meter_##type(const void *el) { if (el) { /* kill compiler whinge */ } return sizeof(type); }
1487 
1488 SIMCLIST_METER(int8_t)
1489 SIMCLIST_METER(int16_t)
1490 SIMCLIST_METER(int32_t)
1491 SIMCLIST_METER(int64_t)
1492 
1493 SIMCLIST_METER(uint8_t)
1494 SIMCLIST_METER(uint16_t)
1495 SIMCLIST_METER(uint32_t)
1496 SIMCLIST_METER(uint64_t)
1497 
1498 SIMCLIST_METER(float)
1499 SIMCLIST_METER(double)
1500 
1501 size_t list_meter_string(const void *el) { return strlen((const char *)el) + 1; }
1502 
1503 /* ready-made hashing functions */
1504 #define SIMCLIST_HASHCOMPUTER(type) list_hash_t list_hashcomputer_##type(const void *el) { return (list_hash_t)(*(type *)el); }
1505 
1506 SIMCLIST_HASHCOMPUTER(int8_t)
1507 SIMCLIST_HASHCOMPUTER(int16_t)
1508 SIMCLIST_HASHCOMPUTER(int32_t)
1509 SIMCLIST_HASHCOMPUTER(int64_t)
1510 
1511 SIMCLIST_HASHCOMPUTER(uint8_t)
1512 SIMCLIST_HASHCOMPUTER(uint16_t)
1513 SIMCLIST_HASHCOMPUTER(uint32_t)
1514 SIMCLIST_HASHCOMPUTER(uint64_t)
1515 
1516 SIMCLIST_HASHCOMPUTER(float)
1517 SIMCLIST_HASHCOMPUTER(double)
1518 
1519 list_hash_t list_hashcomputer_string(const void *el) {
1520  size_t l;
1521  list_hash_t hash = 123;
1522  const char *str = (const char *)el;
1523  char plus;
1524 
1525  for (l = 0; str[l] != '\0'; l++) {
1526  if (l) plus = hash ^ str[l];
1527  else plus = hash ^ (str[l] - str[0]);
1528  hash += (plus << (CHAR_BIT * (l % sizeof(list_hash_t))));
1529  }
1530 
1531  return hash;
1532 }
1533 
1534 
1535 #ifndef NDEBUG
1536 static int list_repOk(const list_t *restrict l) {
1537  int ok, i;
1538  struct list_entry_s *s;
1539 
1540  ok = (l != NULL) && (
1541  /* head/tail checks */
1542  (l->head_sentinel != NULL && l->tail_sentinel != NULL) &&
1543  (l->head_sentinel != l->tail_sentinel) && (l->head_sentinel->prev == NULL && l->tail_sentinel->next == NULL) &&
1544  /* empty list */
1545  (l->numels > 0 || (l->mid == NULL && l->head_sentinel->next == l->tail_sentinel && l->tail_sentinel->prev == l->head_sentinel)) &&
1546  /* spare elements checks */
1547  l->spareelsnum <= SIMCLIST_MAX_SPARE_ELEMS
1548  );
1549 
1550  if (!ok) return 0;
1551 
1552  if (l->numels >= 1) {
1553  /* correct referencing */
1554  for (i = -1, s = l->head_sentinel; i < (int)(l->numels-1)/2 && s->next != NULL; i++, s = s->next) {
1555  if (s->next->prev != s) break;
1556  }
1557  ok = (i == (int)(l->numels-1)/2 && l->mid == s);
1558  if (!ok) return 0;
1559  for (; s->next != NULL; i++, s = s->next) {
1560  if (s->next->prev != s) break;
1561  }
1562  ok = (i == (int)l->numels && s == l->tail_sentinel);
1563  }
1564 
1565  return ok;
1566 }
1567 
1568 static int list_attrOk(const list_t *restrict l) {
1569  int ok;
1570 
1571  ok = (l->attrs.copy_data == 0 || l->attrs.meter != NULL);
1572  return ok;
1573 }
1574 
1575 #endif
1576 
list object
Definition: simclist.h:181
Definition: simclist.h:155