neverFreeMemory.h
00001 // Filename: neverFreeMemory.h
00002 // Created by:  drose (14Jun07)
00003 //
00004 ////////////////////////////////////////////////////////////////////
00005 //
00006 // PANDA 3D SOFTWARE
00007 // Copyright (c) Carnegie Mellon University.  All rights reserved.
00008 //
00009 // All use of this software is subject to the terms of the revised BSD
00010 // license.  You should have received a copy of this license along
00011 // with this source code in a file named "LICENSE."
00012 //
00013 ////////////////////////////////////////////////////////////////////
00014 
00015 #ifndef NEVERFREEMEMORY_H
00016 #define NEVERFREEMEMORY_H
00017 
00018 #include "dtoolbase.h"
00019 
00020 #include "mutexImpl.h"
00021 #include <set>
00022 
00023 ////////////////////////////////////////////////////////////////////
00024 //       Class : NeverFreeMemory
00025 // Description : This class is used to allocate bytes of memory from a
00026 //               pool that is never intended to be freed.  It is
00027 //               particularly useful to support DeletedChain, which
00028 //               allocates memory in just such a fashion.
00029 //
00030 //               When it is known that memory will not be freed, it is
00031 //               preferable to use this instead of the standard
00032 //               malloc() (or global_operator_new()) call, since this
00033 //               will help reduce fragmentation problems in the
00034 //               dynamic heap.  Also, memory allocated from here will
00035 //               exhibit less wasted space.
00036 ////////////////////////////////////////////////////////////////////
00037 class EXPCL_DTOOL NeverFreeMemory {
00038 private:
00039   NeverFreeMemory();
00040 
00041 public:
00042   INLINE static void *alloc(size_t size);
00043 
00044 PUBLISHED:
00045   INLINE static size_t get_total_alloc();
00046   INLINE static size_t get_total_used();
00047   INLINE static size_t get_total_unused();
00048 
00049 private:
00050   void *ns_alloc(size_t size);
00051   INLINE static NeverFreeMemory *get_global_ptr();
00052   static void make_global_ptr();
00053 
00054 private:
00055   class Page {
00056   public:
00057     INLINE Page(void *start, size_t size);
00058     INLINE bool operator < (const Page &other) const;
00059     INLINE void *alloc(size_t size);
00060 
00061     unsigned char *_next;
00062     size_t _remaining;
00063   };
00064 
00065   typedef set<Page> Pages;
00066   Pages _pages;
00067 
00068   size_t _total_alloc;
00069   size_t _total_used;
00070   MutexImpl _lock;
00071   static NeverFreeMemory * TVOLATILE _global_ptr;
00072 };
00073 
00074 #include "neverFreeMemory.I"
00075 
00076 #endif