monotone

monotone Mtn Source Tree

Root/interner.hh

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

Archive Download this file

Branches

Tags

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