/* Copyright (C) 2012 Olaf Till This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see . */ #ifndef __PTRMAP__ #define __PTRMAP__ #include #include class ptrmap_class { // This mimics, to a certain degree, Octaves scheme for unique // objects in src/oct-stream., described here for preserving // my personal understanding: only one static data member 'instance' // which is a pointer with type of the containing class. There, the // unique object is allocated by a member function which is not the // constructor. This avoids the problem that static members must be // globally initialized but possibly can't be, since their initial // value is got from a function call (as, e.g., 'lookup_cache' // here). Having the allocation in a different member function than // the constructor leaves the possibility to allocate the unique // object without defining the parent object, by calling the // allocator over the classname. This again avoids having the data // members defined in the parent object also; so we can use the same // class for unique object and its parent, which seems quite // elegant. public: static void init (void) { if (! instance) instance = new ptrmap_class; } static void deinit (void) { if (instance) delete instance; } static int insert (void *); static void *lookup (int key, int& err); static int remove (int); // zero on success, -1 on failure private: ptrmap_class (void) : lookup_cache (active_map.end ()) {} ~ptrmap_class (void) {} int do_insert (void *); void *do_lookup (int key, int& err); int do_remove (int); // This has to be initialized as NULL. static ptrmap_class *instance; typedef std::map ptrmap_t; typedef std::set ptrset_t; ptrmap_t::const_iterator lookup_cache; // Keys are external identifiers of pointers, e.g. corresponding to // opened and not closed objects. Keys are non-negative. ptrmap_t active_map; // Keeps track of unused keys smaller than greatest used key. ptrset_t holes_set; }; #endif // __PTRMAP__