Mirror of :pserver:cvs@cvs.fefe.de:/cvs libowfat https://www.fefe.de/libowfat/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.1 KiB

13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
  1. #include "likely.h"
  2. #include <stdlib.h>
  3. #include <fcntl.h>
  4. #include <sys/mman.h>
  5. #include <unistd.h>
  6. #include "iarray.h"
  7. #ifdef __dietlibc__
  8. #include <sys/atomic.h>
  9. #else
  10. #define __CAS(ptr,oldval,newval) __sync_val_compare_and_swap(ptr,oldval,newval)
  11. #endif
  12. static iarray_page* new_page(size_t pagesize) {
  13. void* x=mmap(0,pagesize,PROT_READ|PROT_WRITE,MAP_ANONYMOUS|MAP_PRIVATE,-1,0);
  14. if (x==MAP_FAILED) return 0;
  15. return (iarray_page*)x;
  16. }
  17. void* iarray_allocate(iarray* ia,size_t pos) {
  18. size_t index,prevlen=ia->len;
  19. iarray_page** p=&ia->pages[pos%(sizeof(ia->pages)/sizeof(ia->pages[0]))];
  20. iarray_page* newpage=0;
  21. for (index=0; pos<index+ia->elemperpage; index+=ia->elemperpage) {
  22. if (!*p) {
  23. if (!newpage)
  24. if (!(newpage=new_page(ia->bytesperpage))) return 0;
  25. if (__CAS(p,0,newpage)==0)
  26. newpage=0;
  27. }
  28. if (index+ia->elemperpage>pos) {
  29. size_t l;
  30. if (newpage) munmap(newpage,ia->bytesperpage);
  31. do {
  32. l=__CAS(&ia->len,prevlen,pos);
  33. } while (l<pos);
  34. return &(*p)->data[(pos-index)*ia->elemsize];
  35. }
  36. p=&(*p)->next;
  37. }
  38. return 0; // can't happen
  39. }