CommandUtils.cpp 2.2 KB

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