array.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. /**************************************************************************/
  2. /* array.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "array.h"
  31. #include "core/hashfuncs.h"
  32. #include "core/object.h"
  33. #include "core/variant.h"
  34. #include "core/vector.h"
  35. class ArrayPrivate {
  36. public:
  37. SafeRefCount refcount;
  38. Vector<Variant> array;
  39. };
  40. void Array::_ref(const Array &p_from) const {
  41. ArrayPrivate *_fp = p_from._p;
  42. ERR_FAIL_COND(!_fp); // should NOT happen.
  43. if (_fp == _p) {
  44. return; // whatever it is, nothing to do here move along
  45. }
  46. bool success = _fp->refcount.ref();
  47. ERR_FAIL_COND(!success); // should really not happen either
  48. _unref();
  49. _p = p_from._p;
  50. }
  51. void Array::_unref() const {
  52. if (!_p) {
  53. return;
  54. }
  55. if (_p->refcount.unref()) {
  56. memdelete(_p);
  57. }
  58. _p = nullptr;
  59. }
  60. Variant &Array::operator[](int p_idx) {
  61. return _p->array.write[p_idx];
  62. }
  63. const Variant &Array::operator[](int p_idx) const {
  64. return _p->array[p_idx];
  65. }
  66. int Array::size() const {
  67. return _p->array.size();
  68. }
  69. bool Array::empty() const {
  70. return _p->array.empty();
  71. }
  72. void Array::clear() {
  73. _p->array.clear();
  74. }
  75. bool Array::deep_equal(const Array &p_array, int p_recursion_count) const {
  76. // Cheap checks
  77. ERR_FAIL_COND_V_MSG(p_recursion_count > MAX_RECURSION, true, "Max recursion reached");
  78. if (_p == p_array._p) {
  79. return true;
  80. }
  81. const Vector<Variant> &a1 = _p->array;
  82. const Vector<Variant> &a2 = p_array._p->array;
  83. const int size = a1.size();
  84. if (size != a2.size()) {
  85. return false;
  86. }
  87. // Heavy O(n) check
  88. p_recursion_count++;
  89. for (int i = 0; i < size; i++) {
  90. if (!a1[i].deep_equal(a2[i], p_recursion_count)) {
  91. return false;
  92. }
  93. }
  94. return true;
  95. }
  96. bool Array::operator==(const Array &p_array) const {
  97. return _p == p_array._p;
  98. }
  99. uint32_t Array::hash() const {
  100. return recursive_hash(0);
  101. }
  102. uint32_t Array::recursive_hash(int p_recursion_count) const {
  103. ERR_FAIL_COND_V_MSG(p_recursion_count > MAX_RECURSION, 0, "Max recursion reached");
  104. p_recursion_count++;
  105. uint32_t h = hash_djb2_one_32(0);
  106. for (int i = 0; i < _p->array.size(); i++) {
  107. h = hash_djb2_one_32(_p->array[i].recursive_hash(p_recursion_count), h);
  108. }
  109. return h;
  110. }
  111. void Array::operator=(const Array &p_array) {
  112. _ref(p_array);
  113. }
  114. void Array::push_back(const Variant &p_value) {
  115. _p->array.push_back(p_value);
  116. }
  117. void Array::append_array(const Array &p_array) {
  118. _p->array.append_array(p_array._p->array);
  119. }
  120. Error Array::resize(int p_new_size) {
  121. return _p->array.resize(p_new_size);
  122. }
  123. void Array::insert(int p_pos, const Variant &p_value) {
  124. _p->array.insert(p_pos, p_value);
  125. }
  126. void Array::fill(const Variant &p_value) {
  127. _p->array.fill(p_value);
  128. }
  129. void Array::erase(const Variant &p_value) {
  130. _p->array.erase(p_value);
  131. }
  132. Variant Array::front() const {
  133. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  134. return operator[](0);
  135. }
  136. Variant Array::back() const {
  137. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  138. return operator[](_p->array.size() - 1);
  139. }
  140. int Array::find(const Variant &p_value, int p_from) const {
  141. return _p->array.find(p_value, p_from);
  142. }
  143. int Array::rfind(const Variant &p_value, int p_from) const {
  144. if (_p->array.size() == 0) {
  145. return -1;
  146. }
  147. if (p_from < 0) {
  148. // Relative offset from the end
  149. p_from = _p->array.size() + p_from;
  150. }
  151. if (p_from < 0 || p_from >= _p->array.size()) {
  152. // Limit to array boundaries
  153. p_from = _p->array.size() - 1;
  154. }
  155. for (int i = p_from; i >= 0; i--) {
  156. if (_p->array[i] == p_value) {
  157. return i;
  158. }
  159. }
  160. return -1;
  161. }
  162. int Array::find_last(const Variant &p_value) const {
  163. return rfind(p_value);
  164. }
  165. int Array::count(const Variant &p_value) const {
  166. if (_p->array.size() == 0) {
  167. return 0;
  168. }
  169. int amount = 0;
  170. for (int i = 0; i < _p->array.size(); i++) {
  171. if (_p->array[i] == p_value) {
  172. amount++;
  173. }
  174. }
  175. return amount;
  176. }
  177. bool Array::has(const Variant &p_value) const {
  178. return _p->array.find(p_value, 0) != -1;
  179. }
  180. void Array::remove(int p_pos) {
  181. _p->array.remove(p_pos);
  182. }
  183. void Array::set(int p_idx, const Variant &p_value) {
  184. operator[](p_idx) = p_value;
  185. }
  186. const Variant &Array::get(int p_idx) const {
  187. return operator[](p_idx);
  188. }
  189. Array Array::duplicate(bool p_deep) const {
  190. Array new_arr;
  191. int element_count = size();
  192. new_arr.resize(element_count);
  193. for (int i = 0; i < element_count; i++) {
  194. new_arr[i] = p_deep ? get(i).duplicate(p_deep) : get(i);
  195. }
  196. return new_arr;
  197. }
  198. int Array::_clamp_slice_index(int p_index) const {
  199. int arr_size = size();
  200. int fixed_index = CLAMP(p_index, -arr_size, arr_size - 1);
  201. if (fixed_index < 0) {
  202. fixed_index = arr_size + fixed_index;
  203. }
  204. return fixed_index;
  205. }
  206. Array Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const { // like python, but inclusive on upper bound
  207. Array new_arr;
  208. ERR_FAIL_COND_V_MSG(p_step == 0, new_arr, "Array slice step size cannot be zero.");
  209. if (empty()) { // Don't try to slice empty arrays.
  210. return new_arr;
  211. }
  212. if (p_step > 0) {
  213. if (p_begin >= size() || p_end < -size()) {
  214. return new_arr;
  215. }
  216. } else { // p_step < 0
  217. if (p_begin < -size() || p_end >= size()) {
  218. return new_arr;
  219. }
  220. }
  221. int begin = _clamp_slice_index(p_begin);
  222. int end = _clamp_slice_index(p_end);
  223. int new_arr_size = MAX(((end - begin + p_step) / p_step), 0);
  224. new_arr.resize(new_arr_size);
  225. if (p_step > 0) {
  226. int dest_idx = 0;
  227. for (int idx = begin; idx <= end; idx += p_step) {
  228. ERR_FAIL_COND_V_MSG(dest_idx < 0 || dest_idx >= new_arr_size, Array(), "Bug in Array slice()");
  229. new_arr[dest_idx++] = p_deep ? get(idx).duplicate(p_deep) : get(idx);
  230. }
  231. } else { // p_step < 0
  232. int dest_idx = 0;
  233. for (int idx = begin; idx >= end; idx += p_step) {
  234. ERR_FAIL_COND_V_MSG(dest_idx < 0 || dest_idx >= new_arr_size, Array(), "Bug in Array slice()");
  235. new_arr[dest_idx++] = p_deep ? get(idx).duplicate(p_deep) : get(idx);
  236. }
  237. }
  238. return new_arr;
  239. }
  240. struct _ArrayVariantSort {
  241. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  242. bool valid = false;
  243. Variant res;
  244. Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);
  245. if (!valid) {
  246. res = false;
  247. }
  248. return res;
  249. }
  250. };
  251. Array &Array::sort() {
  252. _p->array.sort_custom<_ArrayVariantSort>();
  253. return *this;
  254. }
  255. struct _ArrayVariantSortCustom {
  256. Object *obj;
  257. StringName func;
  258. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  259. const Variant *args[2] = { &p_l, &p_r };
  260. Variant::CallError err;
  261. bool res = obj->call(func, args, 2, err);
  262. if (err.error != Variant::CallError::CALL_OK) {
  263. res = false;
  264. }
  265. return res;
  266. }
  267. };
  268. Array &Array::sort_custom(Object *p_obj, const StringName &p_function) {
  269. ERR_FAIL_NULL_V(p_obj, *this);
  270. SortArray<Variant, _ArrayVariantSortCustom, true> avs;
  271. avs.compare.obj = p_obj;
  272. avs.compare.func = p_function;
  273. avs.sort(_p->array.ptrw(), _p->array.size());
  274. return *this;
  275. }
  276. void Array::shuffle() {
  277. const int n = _p->array.size();
  278. if (n < 2) {
  279. return;
  280. }
  281. Variant *data = _p->array.ptrw();
  282. for (int i = n - 1; i >= 1; i--) {
  283. const int j = Math::rand() % (i + 1);
  284. const Variant tmp = data[j];
  285. data[j] = data[i];
  286. data[i] = tmp;
  287. }
  288. }
  289. template <typename Less>
  290. _FORCE_INLINE_ int bisect(const Vector<Variant> &p_array, const Variant &p_value, bool p_before, const Less &p_less) {
  291. int lo = 0;
  292. int hi = p_array.size();
  293. if (p_before) {
  294. while (lo < hi) {
  295. const int mid = (lo + hi) / 2;
  296. if (p_less(p_array.get(mid), p_value)) {
  297. lo = mid + 1;
  298. } else {
  299. hi = mid;
  300. }
  301. }
  302. } else {
  303. while (lo < hi) {
  304. const int mid = (lo + hi) / 2;
  305. if (p_less(p_value, p_array.get(mid))) {
  306. hi = mid;
  307. } else {
  308. lo = mid + 1;
  309. }
  310. }
  311. }
  312. return lo;
  313. }
  314. int Array::bsearch(const Variant &p_value, bool p_before) {
  315. return bisect(_p->array, p_value, p_before, _ArrayVariantSort());
  316. }
  317. int Array::bsearch_custom(const Variant &p_value, Object *p_obj, const StringName &p_function, bool p_before) {
  318. ERR_FAIL_NULL_V(p_obj, 0);
  319. _ArrayVariantSortCustom less;
  320. less.obj = p_obj;
  321. less.func = p_function;
  322. return bisect(_p->array, p_value, p_before, less);
  323. }
  324. Array &Array::invert() {
  325. _p->array.invert();
  326. return *this;
  327. }
  328. void Array::push_front(const Variant &p_value) {
  329. _p->array.insert(0, p_value);
  330. }
  331. Variant Array::pop_back() {
  332. if (!_p->array.empty()) {
  333. const int n = _p->array.size() - 1;
  334. const Variant ret = _p->array.get(n);
  335. _p->array.resize(n);
  336. return ret;
  337. }
  338. return Variant();
  339. }
  340. Variant Array::pop_front() {
  341. if (!_p->array.empty()) {
  342. const Variant ret = _p->array.get(0);
  343. _p->array.remove(0);
  344. return ret;
  345. }
  346. return Variant();
  347. }
  348. Variant Array::pop_at(int p_pos) {
  349. if (_p->array.empty()) {
  350. // Return `null` without printing an error to mimic `pop_back()` and `pop_front()` behavior.
  351. return Variant();
  352. }
  353. if (p_pos < 0) {
  354. // Relative offset from the end
  355. p_pos = _p->array.size() + p_pos;
  356. }
  357. ERR_FAIL_INDEX_V_MSG(
  358. p_pos,
  359. _p->array.size(),
  360. Variant(),
  361. vformat(
  362. "The calculated index %s is out of bounds (the array has %s elements). Leaving the array untouched and returning `null`.",
  363. p_pos,
  364. _p->array.size()));
  365. const Variant ret = _p->array.get(p_pos);
  366. _p->array.remove(p_pos);
  367. return ret;
  368. }
  369. Variant Array::min() const {
  370. Variant minval;
  371. for (int i = 0; i < size(); i++) {
  372. if (i == 0) {
  373. minval = get(i);
  374. } else {
  375. bool valid;
  376. Variant ret;
  377. Variant test = get(i);
  378. Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid);
  379. if (!valid) {
  380. return Variant(); //not a valid comparison
  381. }
  382. if (bool(ret)) {
  383. //is less
  384. minval = test;
  385. }
  386. }
  387. }
  388. return minval;
  389. }
  390. Variant Array::max() const {
  391. Variant maxval;
  392. for (int i = 0; i < size(); i++) {
  393. if (i == 0) {
  394. maxval = get(i);
  395. } else {
  396. bool valid;
  397. Variant ret;
  398. Variant test = get(i);
  399. Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);
  400. if (!valid) {
  401. return Variant(); //not a valid comparison
  402. }
  403. if (bool(ret)) {
  404. //is less
  405. maxval = test;
  406. }
  407. }
  408. }
  409. return maxval;
  410. }
  411. const void *Array::id() const {
  412. return _p;
  413. }
  414. Array::Array(const Array &p_from) {
  415. _p = nullptr;
  416. _ref(p_from);
  417. }
  418. Array::Array() {
  419. _p = memnew(ArrayPrivate);
  420. _p->refcount.init();
  421. }
  422. Array::~Array() {
  423. _unref();
  424. }