cmd.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. * Copyright 2010-2015 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include <ctype.h> // isspace
  6. #include <stdint.h>
  7. #include <stdlib.h> // size_t
  8. #include <string.h> // strlen
  9. #include <bx/hash.h>
  10. #include <bx/tokenizecmd.h>
  11. #include "../common.h"
  12. #include "dbg.h"
  13. #include "cmd.h"
  14. #include <tinystl/allocator.h>
  15. #include <tinystl/string.h>
  16. #include <tinystl/unordered_map.h>
  17. namespace stl = tinystl;
  18. struct CmdContext
  19. {
  20. CmdContext()
  21. {
  22. }
  23. ~CmdContext()
  24. {
  25. }
  26. void add(const char* _name, ConsoleFn _fn, void* _userData)
  27. {
  28. uint32_t cmd = bx::hashMurmur2A(_name, (uint32_t)strlen(_name) );
  29. BX_CHECK(m_lookup.end() == m_lookup.find(cmd), "Command \"%s\" already exist.", _name);
  30. Func fn = { _fn, _userData };
  31. m_lookup.insert(stl::make_pair(cmd, fn) );
  32. }
  33. void exec(const char* _cmd)
  34. {
  35. for (const char* next = _cmd; '\0' != *next; _cmd = next)
  36. {
  37. char commandLine[1024];
  38. uint32_t size = sizeof(commandLine);
  39. int argc;
  40. char* argv[64];
  41. next = bx::tokenizeCommandLine(_cmd, commandLine, size, argc, argv, BX_COUNTOF(argv), '\n');
  42. if (argc > 0)
  43. {
  44. int err = -1;
  45. uint32_t cmd = bx::hashMurmur2A(argv[0], (uint32_t)strlen(argv[0]) );
  46. CmdLookup::iterator it = m_lookup.find(cmd);
  47. if (it != m_lookup.end() )
  48. {
  49. Func& fn = it->second;
  50. err = fn.m_fn(this, fn.m_userData, argc, argv);
  51. }
  52. switch (err)
  53. {
  54. case 0:
  55. break;
  56. case -1:
  57. {
  58. stl::string tmp(_cmd, next-_cmd - (*next == '\0' ? 0 : 1) );
  59. DBG("Command '%s' doesn't exist.", tmp.c_str() );
  60. }
  61. break;
  62. default:
  63. {
  64. stl::string tmp(_cmd, next-_cmd - (*next == '\0' ? 0 : 1) );
  65. DBG("Failed '%s' err: %d.", tmp.c_str(), err);
  66. }
  67. break;
  68. }
  69. }
  70. }
  71. }
  72. struct Func
  73. {
  74. ConsoleFn m_fn;
  75. void* m_userData;
  76. };
  77. typedef stl::unordered_map<uint32_t, Func> CmdLookup;
  78. CmdLookup m_lookup;
  79. };
  80. static CmdContext s_cmdContext;
  81. void cmdAdd(const char* _name, ConsoleFn _fn, void* _userData)
  82. {
  83. s_cmdContext.add(_name, _fn, _userData);
  84. }
  85. void cmdExec(const char* _cmd)
  86. {
  87. s_cmdContext.exec(_cmd);
  88. }