src/StringPool.h
author David Anderson <dvander@alliedmods.net>
Wed Jul 25 00:16:52 2012 -0700 (2012-07-25)
changeset 90 3da12b433b00
parent 86 32ad0523b309
child 91 5f4402180204
permissions -rw-r--r--
Added a product.version file.
     1 /*
     2  * Copyright (C) 2012 David Anderson
     3  *
     4  * This file is part of JITCraft.
     5  *
     6  * JITCraft is free software: you can redistribute it and/or modify it under
     7  * the terms of the GNU General Public License as published by the Free
     8  * Software Foundation, either version 3 of the License, or (at your option)
     9  * any later version.
    10  * 
    11  * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY
    12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    13  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
    14  *
    15  * You should have received a copy of the GNU General Public License along with
    16  * JITCraft. If not, see http://www.gnu.org/licenses/.
    17  */
    18 #ifndef _include_jitcraft_string_pool_h_
    19 #define _include_jitcraft_string_pool_h_
    20 
    21 #include "AllocatorPolicies.h"
    22 #include "HashTable.h"
    23 #include "Strings.h"
    24 
    25 namespace ke {
    26 
    27 class Zone;
    28 class String;
    29 
    30 // Guarantee that strings with the same contents will map to one pointer. 
    31 class StringPool
    32 {
    33     class CharsAndLength {
    34         const char *str_;
    35         size_t length_;
    36 
    37       public:
    38         CharsAndLength(const char *str, size_t length)
    39           : str_(str),
    40             length_(length)
    41         {
    42         }
    43 
    44         const char *str() const {
    45             return str_;
    46         }
    47         size_t length() const {
    48             return length_;
    49         }
    50     };
    51 
    52     struct Policy
    53     {
    54         typedef String * Payload;
    55 
    56         static uint32 hash(const CharsAndLength &key) {
    57             return HashCharSequence(key.str(), key.length());
    58         }
    59         
    60         static bool matches(const CharsAndLength &key, String *string) {
    61             if (string->length() != key.length())
    62                 return false;
    63             return memcmp(string->chars(), key.str(), key.length() * sizeof(char)) == 0;
    64         }
    65     };
    66 
    67     typedef HashTable<Policy, ZoneAllocatorPolicy> StringSet;
    68 
    69   public:
    70     StringPool(Zone *zone);
    71     ~StringPool();
    72     bool initialize();
    73 
    74   public:
    75     String *add(const char *str, size_t len);
    76     void sweep();
    77 
    78   private:
    79     Zone *zone_;
    80     StringSet set_;
    81 };
    82 
    83 }
    84 
    85 #endif // _include_jitcraft_string_pool_h_