monotone

monotone Mtn Source Tree

Root/interner.hh

1#ifndef __INTERNER_HH__
2#define __INTERNER_HH__
3
4// copyright (C) 2002, 2003 graydon hoare <graydon@pobox.com>
5// all rights reserved.
6// licensed to the public under the terms of the GNU GPL (>= 2)
7// see the file COPYING for details
8
9#include <string>
10#include <ext/hash_map>
11
12#include "sanity.hh"
13
14struct string_hash
15{
16 size_t operator()(std::string const & s) const
17 {
18 return __gnu_cxx::__stl_hash_string(s.c_str());
19 }
20};
21
22struct string_eq
23{
24 bool operator()(std::string const & a,
25 std::string const & b) const
26 {
27 return a == b;
28 }
29};
30
31template <typename T>
32struct
33interner
34{
35 typedef typename __gnu_cxx::hash_map<std::string, T,
36 string_hash,
37 string_eq> hmap;
38
39 hmap fwd;
40 std::vector<std::string> rev;
41 interner() {}
42 std::string lookup (T in) const
43 {
44 std::vector<std::string>::size_type k = static_cast<std::vector<std::string>::size_type>(in);
45 I(k < rev.size());
46 return rev[k];
47 }
48 T intern(std::string const & s)
49 {
50 bool is_new;
51 return intern(s, is_new);
52 }
53 T intern(std::string const & s, bool & is_new)
54 {
55 is_new = false;
56 typename hmap::const_iterator i = fwd.find(s);
57 if (i == fwd.end())
58 {
59 is_new = true;
60 T t = rev.size();
61fwd.insert(make_pair(s, t));
62 rev.push_back(s);
63return t;
64 }
65 else
66 return i->second;
67 }
68};
69
70#endif // __INTERNER_HH__

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status