Statistics
| Branch: | Revision:

root / include / cflyweightstringpool.h @ 7f251033

History | View | Annotate | Download (2.47 KB)

1
//==========================================================================
2
//  CSTRINGPOOL.H - part of
3
//                     OMNeT++/OMNEST
4
//            Discrete System Simulation in C++
5
//
6
//==========================================================================
7

    
8
/*--------------------------------------------------------------*
9
  Copyright (C) 1992-2008 Andras Varga
10
  Copyright (C) 2006-2008 OpenSim Ltd.
11

12
  This file is distributed WITHOUT ANY WARRANTY. See the file
13
  `license' for details on this and other legal matters.
14
*--------------------------------------------------------------*/
15

    
16
#ifndef __CFLYWEIGHTSTRINGPOOL_H
17
#define __CFLYWEIGHTSTRINGPOOL_H
18

    
19
#include <string>
20
#include <map>
21
#include "simkerneldefs.h"
22
#include "simutil.h"
23
#include "cstringpool.h"
24

    
25
NAMESPACE_BEGIN
26

    
27
/**
28
 * For saving memory on the storage of (largely) constant strings that occur in
29
 * many instances during runtime: module names, gate names, property names,
30
 * keys and values, etc. These strings can be stored in a cStringPool as one
31
 * shared instance. Strings in the cStringPool are refcounted.
32
 * (See Flyweight GoF pattern.)
33
 *
34
 * @ingroup internals
35
 */
36
class cFlyweightStringPool : cStringPool
37
{
38
  protected:
39
    struct strless {
40
        bool operator()(const char *s1, const char *s2) const {
41
            int d0 = *s1 - *s2;
42
            if (d0<0) return true; else if (d0>0) return false;
43
            return strcmp(s1,s2) < 0;  // note: (s1+1,s2+1) not good because either strings may be empty
44
        }
45
    };
46
    std::string name;
47
    typedef std::map<char *,int,strless> StringIntMap;
48
    StringIntMap pool; // map<string,refcount>
49
    bool alive; // useful when stringpool is a global variable
50

    
51
  public:
52
    cFlyweightStringPool(const char *poolName=NULL);
53
    ~cFlyweightStringPool();
54

    
55
    /**
56
     * Returns pointer to the pooled copy of the given string, and increments
57
     * its reference count. get() and release() must occur in pairs.
58
     * Passing NULL is OK.
59
     */
60
    const char *get(const char *s);
61

    
62
    /**
63
     * Returns pointer to the pooled copy of the given string, or NULL.
64
     * Reference count is not incremented. Passing NULL is OK.
65
     */
66
    const char *peek(const char *s) const;
67

    
68
    /**
69
     * The parameter must a pointer returned by get(). It decrements the
70
     * reference count and frees the pooled string if it reaches zero.
71
     * Passing NULL is OK.
72
     */
73
    void release(const char *s);
74

    
75
    /**
76
     * For debug purposes.
77
     */
78
    void dump() const;
79
};
80

    
81
NAMESPACE_END
82

    
83

    
84
#endif
85

    
86