/* vim: set ts=4 sw=4 tw=99 et:
 *
 * Copyright (C) 2012 David Anderson
 *
 * This file is part of SourcePawn.
 *
 * SourcePawn is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 * 
 * SourcePawn is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * SourcePawn. If not, see http://www.gnu.org/licenses/.
 */
#ifndef _include_jitcraft_string_pool_h_
#define _include_jitcraft_string_pool_h_

#include <string.h>
#include "AllocatorPolicies.h"
#include "HashTable.h"
#include "Strings.h"

namespace ke {

class Zone;
class String;

// Guarantee that strings with the same contents will map to one pointer. 
class StringPool
{
    struct Policy
    {
        typedef String * Payload;

        static uint32 hash(const CharsAndLength &key) {
            return HashCharSequence(key.str(), key.length());
        }
        
        static bool matches(const CharsAndLength &key, String *string) {
            if (string->length() != key.length())
                return false;
            return memcmp(string->chars(), key.str(), key.length() * sizeof(char)) == 0;
        }
    };

    typedef HashTable<Policy, ZoneAllocatorPolicy> StringSet;

  public:
    StringPool(Zone *zone);
    ~StringPool();
    bool initialize();

  public:
    String *add(const char *str, size_t len);
    void sweep();

  private:
    Zone *zone_;
    StringSet set_;
};

}

#endif // _include_jitcraft_string_pool_h_
