jitcraft/StringPool.h
author David Anderson <dvander@alliedmods.net>
Sun Jul 01 18:21:15 2012 -0700 (2012-07-01)
changeset 23 8a31742781c1
parent 0 c455ebb9a5dc
child 54 8e22792a3921
permissions -rw-r--r--
Implement ++ and -- operators.
     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 <vector>
    22 #include <string.h>
    23 #include "PoolAllocator.h"
    24 
    25 namespace jc {
    26 
    27 typedef const char Name;
    28 
    29 // Guarantee that strings with the same contents will map to one pointer. The
    30 // strings are pool allocated, and search is linear for simplicity.
    31 class StringPool
    32 {
    33     PoolAllocator &pool_;
    34     std::vector<Name *> strings_;
    35 
    36   public:
    37     StringPool(PoolAllocator &pool)
    38       : pool_(pool)
    39     {
    40     }
    41 
    42     Name *add(const char *string) {
    43         for (size_t i = 0; i < strings_.size(); i++) {
    44             if (strcmp(strings_[i], string) == 0)
    45                 return strings_[i];
    46         }
    47         char *name = (char *)pool_.allocate(strlen(string) + 1);
    48         strcpy(name, string);
    49         strings_.push_back(name);
    50         return name;
    51     }
    52 };
    53 
    54 }
    55 
    56 #endif // _include_jitcraft_string_pool_h_