monotone

monotone Mtn Source Tree

Root/src/interner.hh

1// Copyright (C) 2002 Graydon Hoare <graydon@pobox.com>
2//
3// This program is made available under the GNU GPL version 2.0 or
4// greater. See the accompanying file COPYING for details.
5//
6// This program is distributed WITHOUT ANY WARRANTY; without even the
7// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
8// PURPOSE.
9
10#ifndef __INTERNER_HH__
11#define __INTERNER_HH__
12
13#include "vector.hh"
14#include "hash_map.hh"
15#include "sanity.hh"
16
17template <typename T>
18struct
19interner
20{
21 typedef typename hashmap::hash_map<std::string, T> hmap;
22
23 hmap fwd;
24 std::vector<std::string> rev;
25 interner() {}
26 interner(std::string const & init_str, T init_value)
27 {
28 I(intern(init_str) == init_value);
29 }
30 std::string lookup (T in) const
31 {
32 std::vector<std::string>::size_type k = static_cast<std::vector<std::string>::size_type>(in);
33 I(k < rev.size());
34 return rev[k];
35 }
36 T intern(std::string const & s)
37 {
38 bool is_new;
39 return intern(s, is_new);
40 }
41 T intern(std::string const & s, bool & is_new)
42 {
43 T t = rev.size();
44 // if fwd already contains an entry with key s, this just finds
45 // that and returns it
46 std::pair<typename hmap::iterator, bool> res(fwd.insert(make_pair(s, t)));
47 is_new = res.second;
48 if (is_new)
49 rev.push_back(s);
50 return res.first->second;
51 }
52};
53
54#endif // __INTERNER_HH__
55
56// Local Variables:
57// mode: C++
58// fill-column: 76
59// c-file-style: "gnu"
60// indent-tabs-mode: nil
61// End:
62// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s:

Archive Download this file

Branches

Tags

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