CCDictionary.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /****************************************************************************
  2. Copyright (c) 2012 cocos2d-x.org
  3. Copyright (c) 2013-2016 Chukong Technologies Inc.
  4. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. #ifndef __CCDICTIONARY_H__
  23. #define __CCDICTIONARY_H__
  24. /// @cond DO_NOT_SHOW
  25. #include "base/uthash.h"
  26. #include "base/CCRef.h"
  27. #include "deprecated/CCArray.h"
  28. #include "deprecated/CCString.h"
  29. NS_CC_BEGIN
  30. class __Dictionary;
  31. /**
  32. * @addtogroup data_structures
  33. * @{
  34. */
  35. /**
  36. * DictElement is used for traversing Dictionary.
  37. *
  38. * A DictElement is one element of Dictionary, it contains two properties, key and object.
  39. * Its key has two different type (integer and string).
  40. *
  41. * @note The key type is unique, all the elements in Dictionary has the same key type(integer or string).
  42. * @code
  43. * DictElement* pElement;
  44. * CCDICT_FOREACH(dict, pElement)
  45. * {
  46. * const char*key = pElement->getStrKey();
  47. * // You certainly know the type of value, so we assume that it's a Sprite.
  48. * Sprite* pSprite = static_cast<Sprite*>(pElement->getObject());
  49. * // ......
  50. * }
  51. * @endcode
  52. *
  53. */
  54. class CC_DLL DictElement
  55. {
  56. private:
  57. /**
  58. * Constructor of DictElement. It's only for internal usage. Dictionary is its friend class.
  59. *
  60. * @param pszKey The string key of this element.
  61. * @param pObject The object of this element.
  62. */
  63. DictElement(const char* pszKey, Ref* pObject);
  64. /**
  65. * Constructor of DictElement. It's only for internal usage. Dictionary is its friend class.
  66. *
  67. * @param iKey The integer key of this element.
  68. * @param pObject The object of this element.
  69. */
  70. DictElement(intptr_t iKey, Ref* pObject);
  71. public:
  72. /**
  73. * The destructor of DictElement.
  74. * @js NA
  75. * @lua NA
  76. */
  77. ~DictElement();
  78. // Inline functions need to be implemented in header file on Android.
  79. /**
  80. * Get the string key of this element.
  81. * @note This method assumes you know the key type in the element.
  82. * If the element's key type is integer, invoking this method will cause an assert.
  83. *
  84. * @return The string key of this element.
  85. */
  86. const char* getStrKey() const
  87. {
  88. CCASSERT(_strKey[0] != '\0', "Should not call this function for integer dictionary");
  89. return _strKey;
  90. }
  91. /**
  92. * Get the integer key of this element.
  93. * @note This method assumes you know the key type in the element.
  94. * If the element's key type is string, invoking this method will cause an assert.
  95. *
  96. * @return The integer key of this element.
  97. */
  98. intptr_t getIntKey() const
  99. {
  100. CCASSERT(_strKey[0] == '\0', "Should not call this function for string dictionary");
  101. return _intKey;
  102. }
  103. /**
  104. * Get the object of this element.
  105. *
  106. * @return The object of this element.
  107. */
  108. Ref* getObject() const { return _object; }
  109. private:
  110. // The max length of string key.
  111. #define MAX_KEY_LEN 256
  112. // char array is needed for HASH_ADD_STR in UT_HASH.
  113. // So it's a pain that all elements will allocate 256 bytes for this array.
  114. char _strKey[MAX_KEY_LEN]; // hash key of string type
  115. intptr_t _intKey; // hash key of integer type
  116. Ref* _object; // hash value
  117. public:
  118. UT_hash_handle hh; // makes this class hashable
  119. friend class __Dictionary; // declare Dictionary as friend class
  120. };
  121. /** The macro for traversing dictionary
  122. *
  123. * @note It's faster than getting all keys and traversing keys to get objects by objectForKey.
  124. * It's also safe to remove elements while traversing.
  125. */
  126. #define CCDICT_FOREACH(__dict__, __el__) \
  127. DictElement* pTmp##__dict__##__el__ = nullptr; \
  128. if (__dict__) \
  129. HASH_ITER(hh, (__dict__)->_elements, __el__, pTmp##__dict__##__el__)
  130. /**
  131. * Dictionary is a class like NSDictionary in Obj-C .
  132. *
  133. * @note Only the pointer of Object or its subclass can be inserted to Dictionary.
  134. * @code
  135. * // Create a dictionary, return an autorelease object.
  136. * Dictionary* pDict = Dictionary::create();
  137. *
  138. * // Insert objects to dictionary
  139. * String* pValue1 = String::create("100");
  140. * String* pValue2 = String::create("120");
  141. * Integer* pValue3 = Integer::create(200);
  142. * pDict->setObject(pValue1, "key1");
  143. * pDict->setObject(pValue2, "key2");
  144. * pDict->setObject(pValue3, "key3");
  145. *
  146. * // Get the object for key
  147. * String* pStr1 = static_cast<String*>(pDict->objectForKey("key1"));
  148. * log("{ key1: %s }", pStr1->getCString());
  149. * Integer* pInteger = static_cast<Integer*>(pDict->objectForKey("key3"));
  150. * log("{ key3: %d }", pInteger->getValue());
  151. * @endcode
  152. *
  153. */
  154. class CC_DLL __Dictionary : public Ref, public Clonable
  155. {
  156. public:
  157. /**
  158. * The constructor of Dictionary.
  159. * @js NA
  160. * @lua NA
  161. */
  162. __Dictionary();
  163. /**
  164. * The destructor of Dictionary
  165. * @js NA
  166. * @lua NA
  167. */
  168. ~__Dictionary();
  169. /** Initializes the dictionary. It returns true if the initializations was successful.
  170. * @js NA
  171. * @lua NA
  172. */
  173. bool init();
  174. /**
  175. * Get the count of elements in Dictionary.
  176. *
  177. * @return The count of elements.
  178. * @js NA
  179. */
  180. unsigned int count();
  181. /**
  182. * Return all keys of elements.
  183. *
  184. * @return The array contains all keys of elements. It's an autorelease object yet.
  185. * @js NA
  186. */
  187. __Array* allKeys();
  188. /**
  189. * Get all keys according to the specified object.
  190. * @warning We use '==' to compare two objects
  191. * @return The array contains all keys for the specified object. It's an autorelease object yet.
  192. * @js NA
  193. */
  194. __Array* allKeysForObject(Ref* object);
  195. /**
  196. * Get the object according to the specified string key.
  197. *
  198. * @note The dictionary needs to use string as key. If integer is passed, an assert will appear.
  199. * @param key The string key for searching.
  200. * @return The object matches the key. You need to force convert it to the type you know.
  201. * @code
  202. * // Assume that the elements are String* pointers. Convert it by following code.
  203. * String* pStr = static_cast<String*>(pDict->objectForKey("key1"));
  204. * // Do something about pStr.
  205. * // If you don't know the object type, properly you need to use dynamic_cast<SomeType*> to check it.
  206. * String* pStr2 = dynamic_cast<String*>(pDict->objectForKey("key1"));
  207. * if (pStr2 != NULL) {
  208. * // Do something about pStr2
  209. * }
  210. * @endcode
  211. * @see objectForKey(intptr_t)
  212. * @js NA
  213. */
  214. Ref* objectForKey(const std::string& key);
  215. /**
  216. * Get the object according to the specified integer key.
  217. *
  218. * @note The dictionary needs to use integer as key. If string is passed, an assert will appear.
  219. * @param key The integer key for searching.
  220. * @return The object matches the key.
  221. * @see objectForKey(const std::string&)
  222. * @js NA
  223. */
  224. Ref* objectForKey(intptr_t key);
  225. /** Get the value according to the specified string key.
  226. *
  227. * @note Be careful to use this function since it assumes the objects in the dictionary are __String pointer.
  228. * @param key The string key for searching
  229. * @return An instance of String.
  230. * It will return an empty string if the objects aren't __String pointer or the key wasn't found.
  231. * @see valueForKey(intptr_t)
  232. * @js NA
  233. */
  234. const __String* valueForKey(const std::string& key);
  235. /** Get the value according to the specified integer key.
  236. *
  237. * @note Be careful to use this function since it assumes the objects in the dictionary are __String pointer.
  238. * @param key The string key for searching.
  239. * @return An instance of String.
  240. * It will return an empty string if the objects aren't __String pointer or the key wasn't found.
  241. * @see valueForKey(intptr_t)
  242. * @js NA
  243. */
  244. const __String* valueForKey(intptr_t key);
  245. /** Insert an object to dictionary, and match it with the specified string key.
  246. *
  247. * @note When the first time this method is invoked, the key type will be set to string.
  248. * After that you can't setObject with an integer key.
  249. * If the dictionary contains the key you passed, the object matching the key will be released and removed from dictionary.
  250. * Then the new object will be inserted after that.
  251. *
  252. * @param pObject The Object to be inserted.
  253. * @param key The string key for searching.
  254. * @see setObject(Ref*, intptr_t)
  255. * @js NA
  256. */
  257. void setObject(Ref* pObject, const std::string& key);
  258. /** Insert an object to dictionary, and match it with the specified string key.
  259. *
  260. * @note Then the first time this method is invoked, the key type will be set to string.
  261. * After that you can't setObject with an integer key.
  262. * If the dictionary contains the key you passed, the object matching the key will be released and removed from dictionary.
  263. * Then the new object will be inserted after that.
  264. * @param pObject The Object to be inserted.
  265. * @param key The string key for searching.
  266. * @see setObject(Ref*, const std::string&)
  267. * @js NA
  268. */
  269. void setObject(Ref* pObject, intptr_t key);
  270. /**
  271. * Remove an object by the specified string key.
  272. *
  273. * @param key The string key for searching.
  274. * @see removeObjectForKey(intptr_t), removeObjectsForKeys(__Array*),
  275. * removeObjectForElememt(DictElement*), removeAllObjects().
  276. * @js NA
  277. */
  278. void removeObjectForKey(const std::string& key);
  279. /**
  280. * Remove an object by the specified integer key.
  281. *
  282. * @param key The integer key for searching.
  283. * @see removeObjectForKey(const std::string&), removeObjectsForKeys(__Array*),
  284. * removeObjectForElememt(DictElement*), removeAllObjects().
  285. * @js NA
  286. */
  287. void removeObjectForKey(intptr_t key);
  288. /**
  289. * Remove objects by an array of keys.
  290. *
  291. * @param pKeyArray The array contains keys to be removed.
  292. * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t),
  293. * removeObjectForElememt(DictElement*), removeAllObjects().
  294. * @js NA
  295. */
  296. void removeObjectsForKeys(__Array* pKey__Array);
  297. /**
  298. * Remove an object by an element.
  299. *
  300. * @param pElement The element need to be removed.
  301. * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t),
  302. * removeObjectsForKeys(__Array*), removeAllObjects().
  303. * @js NA
  304. * @lua NA
  305. */
  306. void removeObjectForElememt(DictElement* pElement);
  307. /**
  308. * Remove all objects in the dictionary.
  309. *
  310. * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t),
  311. * removeObjectsForKeys(__Array*), removeObjectForElememt(DictElement*).
  312. * @js NA
  313. */
  314. void removeAllObjects();
  315. /**
  316. * Return a random object in the dictionary.
  317. *
  318. * @return The random object.
  319. * @see objectForKey(intptr_t), objectForKey(const std::string&)
  320. * @js NA
  321. * @lua NA
  322. */
  323. Ref* randomObject();
  324. /**
  325. * Create a dictionary.
  326. * @return A dictionary which is an autorelease object.
  327. * @see createWithDictionary(Dictionary*), createWithContentsOfFile(const char*), createWithContentsOfFileThreadSafe(const char*).
  328. * @js NA
  329. */
  330. static __Dictionary* create();
  331. /**
  332. * Create a dictionary with an existing dictionary.
  333. *
  334. * @param srcDict The exist dictionary.
  335. * @return A dictionary which is an autorelease object.
  336. * @see create(), createWithContentsOfFile(const char*), createWithContentsOfFileThreadSafe(const char*).
  337. * @js NA
  338. */
  339. static __Dictionary* createWithDictionary(__Dictionary* srcDict);
  340. /**
  341. * Create a dictionary with a plist file.
  342. * @param pFileName The name of the plist file.
  343. * @return A dictionary which is an autorelease object.
  344. * @see create(), createWithDictionary(Dictionary*), createWithContentsOfFileThreadSafe(const char*).
  345. * @js NA
  346. */
  347. static __Dictionary* createWithContentsOfFile(const char *pFileName);
  348. /**
  349. * Write a dictionary to a plist file.
  350. * @param fullPath The full path of the plist file. You can get writable path by getWritablePath()
  351. * @return true if succeeded, false if failed
  352. * @js NA
  353. * @lua NA
  354. */
  355. bool writeToFile(const char *fullPath);
  356. /**
  357. * Create a dictionary with a plist file.
  358. *
  359. * @note the return object isn't an autorelease object.
  360. * This can make sure not using autorelease pool in a new thread.
  361. * Therefore, you need to manage the lifecycle of the return object.
  362. * It means that when you don't need it, CC_SAFE_RELEASE needs to be invoked.
  363. *
  364. * @param pFileName The name of the plist file.
  365. * @return A dictionary which isn't an autorelease object.
  366. * @js NA
  367. * @lua NA
  368. */
  369. static __Dictionary* createWithContentsOfFileThreadSafe(const char *pFileName);
  370. /* override functions
  371. * @js NA
  372. * @lua NA
  373. */
  374. virtual void acceptVisitor(DataVisitor &visitor);
  375. /**
  376. * @js NA
  377. * @lua NA
  378. */
  379. virtual __Dictionary* clone() const override;
  380. private:
  381. /**
  382. * For internal usage, invoked by setObject.
  383. */
  384. void setObjectUnSafe(Ref* pObject, const std::string& key);
  385. void setObjectUnSafe(Ref* pObject, const intptr_t key);
  386. public:
  387. /**
  388. * All the elements in dictionary.
  389. *
  390. * @note For internal usage, we need to declare this member variable as public since it's used in UT_HASH.
  391. */
  392. DictElement* _elements;
  393. private:
  394. /** The support type of dictionary, it's confirmed when setObject is invoked. */
  395. enum DictType
  396. {
  397. kDictUnknown = 0,
  398. kDictStr,
  399. kDictInt
  400. };
  401. /**
  402. * The type of dictionary, it's assigned to kDictUnknown by default.
  403. */
  404. DictType _dictType;
  405. };
  406. // end of data_structure group
  407. /// @}
  408. NS_CC_END
  409. /// @endcond
  410. #endif /* __CCDICTIONARY_H__ */