CommandUtils.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "server/commands/CommandUtils.h"
  2. static bool splitStringIntern(const std::string& rawCommand, std::string& command, std::vector<std::string>& args)
  3. {
  4. size_t old = 0;
  5. size_t index = 0;
  6. // parse first argument
  7. while(index < rawCommand.size())
  8. {
  9. if(rawCommand[index] == ' ')
  10. {
  11. command = rawCommand.substr(old, index - old);
  12. old = index + 1;
  13. index++;
  14. break;
  15. }
  16. index++;
  17. }
  18. // if the command name is the whole raw command
  19. if(index == rawCommand.size())
  20. {
  21. command = rawCommand.substr(old, index - old);
  22. return false;
  23. }
  24. // parse remainding arguments
  25. while(index < rawCommand.size())
  26. {
  27. if(rawCommand[index] == '"')
  28. {
  29. // no space before the quotation mark
  30. if(index != old)
  31. {
  32. return true;
  33. }
  34. old = index + 1;
  35. while(true)
  36. {
  37. index++;
  38. // quotation mark not closed
  39. if(index >= rawCommand.size())
  40. {
  41. return true;
  42. }
  43. else if(rawCommand[index] == '"')
  44. {
  45. break;
  46. }
  47. }
  48. // no space after quotation mark
  49. if(index + 1 < rawCommand.size() && rawCommand[index + 1] != ' ')
  50. {
  51. return true;
  52. }
  53. args.push_back(rawCommand.substr(old, index - old));
  54. old = index + 2;
  55. }
  56. else if(rawCommand[index] == ' ')
  57. {
  58. if(index > old && index - old > 0)
  59. {
  60. args.push_back(rawCommand.substr(old, index - old));
  61. }
  62. old = index + 1;
  63. }
  64. index++;
  65. }
  66. if(index > old && index - old > 0)
  67. {
  68. args.push_back(rawCommand.substr(old, index - old));
  69. }
  70. return false;
  71. }
  72. bool CommandUtils::splitString(const std::string& rawCommand, std::string& command, std::vector<std::string>& args)
  73. {
  74. bool b = splitStringIntern(rawCommand, command, args);
  75. if(b)
  76. {
  77. args.clear();
  78. command = "";
  79. }
  80. return b;
  81. }