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
11#include "hash_map.hh"
12#include "sanity.hh"
13
14struct string_eq
15{
16 bool operator()(std::string const & a,
17 std::string const & b) const
18 {
19 return a == b;
20 }
21};
22
23template <typename T>
24struct
25interner
26{
27 typedef typename hashmap::hash_map<std::string, T,
28 hashmap::string_hash,
29 string_eq> hmap;
30
31 hmap fwd;
32 std::vector<std::string> rev;
33 interner() {}
34 interner(std::string const & init_str, T init_value)
35 {
36 I(intern(init_str) == init_value);
37 }
38 std::string lookup (T in) const
39 {
40 std::vector<std::string>::size_type k = static_cast<std::vector<std::string>::size_type>(in);
41 I(k < rev.size());
42 return rev[k];
43 }
44 T intern(std::string const & s)
45 {
46 bool is_new;
47 return intern(s, is_new);
48 }
49 T intern(std::string const & s, bool & is_new)
50 {
51 std::pair<typename hmap::iterator, bool> res;
52 T t = rev.size();
53 // if fwd already contains an entry with key s, this just finds
54 // that and returns it
55 res = fwd.insert(make_pair(s, t));
56 is_new = res.second;
57 if (is_new)
58 rev.push_back(s);
59 return res.first->second;
60 }
61};
62
63#endif // __INTERNER_HH__

Archive Download this file

Branches

Tags

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