nclistmgr.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*********************************************************************
  2. Copyright 2010, UCAR/Unidata See netcdf/COPYRIGHT file for
  3. copying and redistribution conditions.
  4. *********************************************************************/
  5. #include <config.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <assert.h>
  9. #include "nc.h"
  10. #define ID_SHIFT (16)
  11. #define NCFILELISTLENGTH 0x10000
  12. /* Version one just allocates the max space (sizeof(NC*)*2^16)*/
  13. static NC** nc_filelist = NULL;
  14. static int numfiles = 0;
  15. /* Common */
  16. int
  17. count_NCList(void)
  18. {
  19. return numfiles;
  20. }
  21. void
  22. free_NCList(void)
  23. {
  24. if(numfiles > 0) return; /* not empty */
  25. if(nc_filelist != NULL) free(nc_filelist);
  26. nc_filelist = NULL;
  27. }
  28. int
  29. add_to_NCList(NC* ncp)
  30. {
  31. int i;
  32. int new_id;
  33. if(nc_filelist == NULL) {
  34. if (!(nc_filelist = calloc(1, sizeof(NC*)*NCFILELISTLENGTH)))
  35. return NC_ENOMEM;
  36. numfiles = 0;
  37. }
  38. new_id = 0; /* id's begin at 1 */
  39. for(i=1;i<0x10000;i++) {
  40. if(nc_filelist[i] == NULL) {new_id = i; break;}
  41. }
  42. if(new_id == 0) return NC_ENOMEM; /* no more slots */
  43. nc_filelist[new_id] = ncp;
  44. numfiles++;
  45. new_id = (new_id << ID_SHIFT);
  46. ncp->ext_ncid = new_id;
  47. return NC_NOERR;
  48. }
  49. void
  50. del_from_NCList(NC* ncp)
  51. {
  52. unsigned int ncid = ((unsigned int)ncp->ext_ncid) >> ID_SHIFT;
  53. if(numfiles == 0 || ncid == 0 || nc_filelist == NULL) return;
  54. if(nc_filelist[ncid] != ncp) return;
  55. nc_filelist[ncid] = NULL;
  56. numfiles--;
  57. /* If all files have been closed, release the filelist memory. */
  58. if (numfiles == 0)
  59. free_NCList();
  60. }
  61. NC *
  62. find_in_NCList(int ext_ncid)
  63. {
  64. NC* f = NULL;
  65. unsigned int ncid = ((unsigned int)ext_ncid) >> ID_SHIFT;
  66. if(numfiles > 0 && nc_filelist != NULL && ncid < NCFILELISTLENGTH)
  67. f = nc_filelist[ncid];
  68. return f;
  69. }