stringdict.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #ifndef __STRINGDICT_H
  2. #define __STRINGDICT_H
  3. #include <bfc/string/StringW.h>
  4. #include <bfc/ptrlist.h>
  5. // a convenient class to statically declare strings and their IDs with binary search lookups
  6. //
  7. // example of use :
  8. //
  9. // BEGIN_STRINGDICTIONARY(_identifier)
  10. // SDI("somestring", 0);
  11. // SDI("someotherstring", 1);
  12. // SDI("andyetanotherstring", 2);
  13. // END_STRINGDICTIONARY(_identifier, identifier)
  14. // foo (const char *str) {
  15. // int a = identifier.getId(str);
  16. // if (a < 0) {
  17. // // not found!
  18. // }
  19. // return a;
  20. // }
  21. class StringDictionaryItem
  22. {
  23. public:
  24. StringDictionaryItem(const wchar_t *string, int stringid) : str(string), id(stringid) {}
  25. virtual ~StringDictionaryItem() {}
  26. const wchar_t *getString()
  27. {
  28. return str;
  29. }
  30. int getId()
  31. {
  32. return id;
  33. }
  34. private:
  35. StringW str;
  36. int id;
  37. };
  38. class StringDictionaryItemCompare
  39. {
  40. public:
  41. static int compareItem(void *p1, void *p2)
  42. {
  43. return WCSICMP(((StringDictionaryItem *)p1)->getString(), ((StringDictionaryItem *)p2)->getString());
  44. }
  45. static int compareAttrib(const wchar_t *attrib, void *item)
  46. {
  47. return WCSICMP(attrib, ((StringDictionaryItem *)item)->getString());
  48. }
  49. };
  50. class StringDictionary
  51. {
  52. public:
  53. StringDictionary() {}
  54. virtual ~StringDictionary()
  55. {
  56. items.deleteAll();
  57. }
  58. virtual void addItem(const wchar_t *str, int id)
  59. {
  60. ASSERT(id != -1);
  61. items.addItem(new StringDictionaryItem(str, id));
  62. }
  63. virtual int getId(const wchar_t *str)
  64. {
  65. StringDictionaryItem *i = items.findItem(str);
  66. if (i == NULL)
  67. return -1;
  68. return i->getId();
  69. }
  70. private:
  71. PtrListQuickSorted<StringDictionaryItem, StringDictionaryItemCompare> items;
  72. };
  73. #define BEGIN_STRINGDICTIONARY(class_ident) \
  74. class class_ident : public StringDictionary { \
  75. public: \
  76. class_ident() {
  77. #define SDI(str, id) \
  78. addItem(str, id);
  79. #define END_STRINGDICTIONARY(class_ident, instance_ident) \
  80. }; \
  81. virtual ~class_ident() { } \
  82. }; \
  83. \
  84. class_ident instance_ident;
  85. #endif