jitcraft/StringPool.h
author David Anderson <dvander@alliedmods.net>
Sun Jul 01 14:52:57 2012 -0700 (2012-07-01)
changeset 21 af5d8e985502
parent 0 c455ebb9a5dc
child 54 8e22792a3921
permissions -rw-r--r--
Added initial String: support.
dvander@0
     1
/*
dvander@0
     2
 * Copyright (C) 2012 David Anderson
dvander@0
     3
 *
dvander@0
     4
 * This file is part of JITCraft.
dvander@0
     5
 *
dvander@0
     6
 * JITCraft is free software: you can redistribute it and/or modify it under
dvander@0
     7
 * the terms of the GNU General Public License as published by the Free
dvander@0
     8
 * Software Foundation, either version 3 of the License, or (at your option)
dvander@0
     9
 * any later version.
dvander@0
    10
 * 
dvander@0
    11
 * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY
dvander@0
    12
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
dvander@0
    13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
dvander@0
    14
 *
dvander@0
    15
 * You should have received a copy of the GNU General Public License along with
dvander@0
    16
 * JITCraft. If not, see http://www.gnu.org/licenses/.
dvander@0
    17
 */
dvander@0
    18
#ifndef _include_jitcraft_string_pool_h_
dvander@0
    19
#define _include_jitcraft_string_pool_h_
dvander@0
    20
dvander@0
    21
#include <vector>
dvander@0
    22
#include <string.h>
dvander@0
    23
#include "PoolAllocator.h"
dvander@0
    24
dvander@0
    25
namespace jc {
dvander@0
    26
dvander@0
    27
typedef const char Name;
dvander@0
    28
dvander@0
    29
// Guarantee that strings with the same contents will map to one pointer. The
dvander@0
    30
// strings are pool allocated, and search is linear for simplicity.
dvander@0
    31
class StringPool
dvander@0
    32
{
dvander@0
    33
    PoolAllocator &pool_;
dvander@0
    34
    std::vector<Name *> strings_;
dvander@0
    35
dvander@0
    36
  public:
dvander@0
    37
    StringPool(PoolAllocator &pool)
dvander@0
    38
      : pool_(pool)
dvander@0
    39
    {
dvander@0
    40
    }
dvander@0
    41
dvander@0
    42
    Name *add(const char *string) {
dvander@0
    43
        for (size_t i = 0; i < strings_.size(); i++) {
dvander@0
    44
            if (strcmp(strings_[i], string) == 0)
dvander@0
    45
                return strings_[i];
dvander@0
    46
        }
dvander@0
    47
        char *name = (char *)pool_.allocate(strlen(string) + 1);
dvander@0
    48
        strcpy(name, string);
dvander@0
    49
        strings_.push_back(name);
dvander@0
    50
        return name;
dvander@0
    51
    }
dvander@0
    52
};
dvander@0
    53
dvander@0
    54
}
dvander@0
    55
dvander@0
    56
#endif // _include_jitcraft_string_pool_h_