Vaucanson  1.4.1
escaper.hxx
Go to the documentation of this file.
1 // escaper.hxx: this file is part of the Vaucanson project.
2 //
3 // Vaucanson, a generic library for finite state machines.
4 //
5 // Copyright (C) 2004, 2005, 2006 The Vaucanson Group.
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License
9 // as published by the Free Software Foundation; either version 2
10 // of the License, or (at your option) any later version.
11 //
12 // The complete GNU General Public Licence Notice can be found as the
13 // `COPYING' file in the root directory.
14 //
15 // The Vaucanson Group consists of people listed in the `AUTHORS' file.
16 //
17 #ifndef VCSN_MISC_ESCAPER_HXX
18 # define VCSN_MISC_ESCAPER_HXX
19 
28 # include <string>
29 # include <sstream>
30 
31 # include <vaucanson/misc/escaper.hh>
33 
34 namespace vcsn
35 {
36  namespace misc
37  {
38 
40  inline
41  int
43  {
44  static const int idx = std::ios::xalloc ();
45  return idx;
46  }
47 
48  /*--------.
49  | escaper |
50  `--------*/
51 
52  template <class T>
53  escaper<T>::escaper (const T& w) : w_ (w)
54  {
55  }
56 
57  template <class T>
58  std::ostream&
59  escaper<T>::operator() (std::ostream& ostr) const
60  {
61  std::ostringstream o;
62  o << w_;
63  std::string w = o.str ();
64  const std::set<char>& e = getesc (ostr);
65  for (std::string::const_iterator i = w.begin (); i != w.end (); ++i)
66  if (e.find (*i) != e.end ())
67  ostr << "\\" << *i;
68  else
69  ostr << *i;
70  return ostr;
71  }
72 
73  /*-------------.
74  | make_escaper |
75  `-------------*/
76 
77  template <class T>
78  escaper<T>
79  make_escaper (const T& w)
80  {
81  return escaper<T> (w);
82  }
83 
84  /*-------.
85  | setesc |
86  `-------*/
87 
88  inline
89  setesc::setesc (const std::set<char>& s) : s_ (s)
90  {
91  }
92 
93  inline
94  std::ostream&
95  setesc::operator() (std::ostream& ostr) const
96  {
97  typedef std::set<char> esc_set;
98  const int idx = escaped ();
99 
100  if (not ostr.pword (idx))
101  ostr.register_callback (pword_delete<esc_set>, idx);
102  else
103  delete static_cast<esc_set*> (ostr.pword (idx));
104  ostr.pword (idx) = new esc_set (s_);
105  return ostr;
106  }
107 
108  /*-------.
109  | getesc |
110  `-------*/
111 
112  inline
113  std::set<char>& getesc (std::ostream& ostr)
114  {
115  const int idx = escaped ();
116 
117  if (not ostr.pword (idx))
119  return *static_cast<std::set<char>*> (ostr.pword (idx));
120  }
121 
122  } // End of namespace misc.
123 } // End of namespace vcsn.
124 
125 #endif // ! VCSN_MISC_ESCAPER_HXX