tokenset.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #include "tokenset.h"
  2. /**
  3. * This file is part of uhferret.
  4. *
  5. * Author:: Peter Lane
  6. * Copyright:: Copyright 2011, Peter Lane.
  7. * License:: GPLv3
  8. *
  9. * uhferret is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation, either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * uhferret is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with uhferret. If not, see <http://www.gnu.org/licenses/>.
  21. */
  22. Token::Token ()
  23. : _capacity (2), _top (0)
  24. {
  25. _token = new char [_capacity];
  26. }
  27. Token::~Token ()
  28. {
  29. delete[] _token;
  30. }
  31. void Token::Erase ()
  32. {
  33. _top = 0;
  34. }
  35. void Token::AddChar (char c)
  36. {
  37. if (_top == _capacity)
  38. Grow ();
  39. _token [_top] = c;
  40. ++_top;
  41. }
  42. std::string Token::GetString () const
  43. {
  44. return std::string (_token, _top);
  45. }
  46. int Token::GetLength () const
  47. {
  48. return _top;
  49. }
  50. void Token::Grow ()
  51. {
  52. char * newtoken = new char [2 * _capacity];
  53. for (int i = 0; i < _capacity; ++i)
  54. newtoken[i] = _token[i];
  55. _capacity = 2 * _capacity;
  56. delete _token;
  57. _token = newtoken;
  58. }
  59. // *** TokenSet
  60. TokenSet::TokenSet ()
  61. : _nextindex (0)
  62. {}
  63. std::size_t TokenSet::GetIndexFor (std::string token)
  64. {
  65. _tokens_it = _tokens.find (token);
  66. if (_tokens_it != _tokens.end()) // found it
  67. return _tokens_it->second;
  68. else // otherwise, make a new index
  69. {
  70. _tokens[token] = _nextindex;
  71. _strings[_nextindex] = token;
  72. _nextindex++;
  73. return _nextindex-1;
  74. }
  75. }
  76. std::string TokenSet::GetStringFor (std::size_t token)
  77. {
  78. _strings_it = _strings.find (token);
  79. assert (_strings_it != _strings.end ()); // it's an error if token not in token set
  80. return std::string (_strings_it->second.c_str ());
  81. }
  82. void TokenSet::Clear ()
  83. {
  84. _tokens.clear ();
  85. _strings.clear ();
  86. _nextindex = 0;
  87. }
  88. void TokenSet::SetNextIndex (int index)
  89. {
  90. _nextindex = index;
  91. }
  92. void TokenSet::SetIndexString (std::string token, int index)
  93. {
  94. _strings[index] = token;
  95. _tokens[token] = index;
  96. }