src/StringPool.h
author David Anderson <danderson@mozilla.com>
Wed Jul 25 01:32:49 2012 -0700 (2012-07-25)
changeset 93 23189d937087
parent 91 5f4402180204
child 195 c1ba166f3fc4
permissions -rw-r--r--
Fix opt clang build.
     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 <string.h>
    22 #include "AllocatorPolicies.h"
    23 #include "HashTable.h"
    24 #include "Strings.h"
    25 
    26 namespace ke {
    27 
    28 class Zone;
    29 class String;
    30 
    31 // Guarantee that strings with the same contents will map to one pointer. 
    32 class StringPool
    33 {
    34     class CharsAndLength {
    35         const char *str_;
    36         size_t length_;
    37 
    38       public:
    39         CharsAndLength(const char *str, size_t length)
    40           : str_(str),
    41             length_(length)
    42         {
    43         }
    44 
    45         const char *str() const {
    46             return str_;
    47         }
    48         size_t length() const {
    49             return length_;
    50         }
    51     };
    52 
    53     struct Policy
    54     {
    55         typedef String * Payload;
    56 
    57         static uint32 hash(const CharsAndLength &key) {
    58             return HashCharSequence(key.str(), key.length());
    59         }
    60         
    61         static bool matches(const CharsAndLength &key, String *string) {
    62             if (string->length() != key.length())
    63                 return false;
    64             return memcmp(string->chars(), key.str(), key.length() * sizeof(char)) == 0;
    65         }
    66     };
    67 
    68     typedef HashTable<Policy, ZoneAllocatorPolicy> StringSet;
    69 
    70   public:
    71     StringPool(Zone *zone);
    72     ~StringPool();
    73     bool initialize();
    74 
    75   public:
    76     String *add(const char *str, size_t len);
    77     void sweep();
    78 
    79   private:
    80     Zone *zone_;
    81     StringSet set_;
    82 };
    83 
    84 }
    85 
    86 #endif // _include_jitcraft_string_pool_h_