array.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. /*************************************************************************/
  2. /* array.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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 "container_type_validate.h"
  32. #include "core/object/class_db.h"
  33. #include "core/object/script_language.h"
  34. #include "core/templates/hashfuncs.h"
  35. #include "core/templates/search_array.h"
  36. #include "core/templates/vector.h"
  37. #include "core/variant/callable.h"
  38. #include "core/variant/variant.h"
  39. class ArrayPrivate {
  40. public:
  41. SafeRefCount refcount;
  42. Vector<Variant> array;
  43. ContainerTypeValidate typed;
  44. };
  45. void Array::_ref(const Array &p_from) const {
  46. ArrayPrivate *_fp = p_from._p;
  47. ERR_FAIL_COND(!_fp); // should NOT happen.
  48. if (_fp == _p) {
  49. return; // whatever it is, nothing to do here move along
  50. }
  51. bool success = _fp->refcount.ref();
  52. ERR_FAIL_COND(!success); // should really not happen either
  53. _unref();
  54. _p = p_from._p;
  55. }
  56. void Array::_unref() const {
  57. if (!_p) {
  58. return;
  59. }
  60. if (_p->refcount.unref()) {
  61. memdelete(_p);
  62. }
  63. _p = nullptr;
  64. }
  65. Variant &Array::operator[](int p_idx) {
  66. return _p->array.write[p_idx];
  67. }
  68. const Variant &Array::operator[](int p_idx) const {
  69. return _p->array[p_idx];
  70. }
  71. int Array::size() const {
  72. return _p->array.size();
  73. }
  74. bool Array::is_empty() const {
  75. return _p->array.is_empty();
  76. }
  77. void Array::clear() {
  78. _p->array.clear();
  79. }
  80. bool Array::operator==(const Array &p_array) const {
  81. return _p == p_array._p;
  82. }
  83. bool Array::operator!=(const Array &p_array) const {
  84. return !operator==(p_array);
  85. }
  86. bool Array::operator<(const Array &p_array) const {
  87. int a_len = size();
  88. int b_len = p_array.size();
  89. int min_cmp = MIN(a_len, b_len);
  90. for (int i = 0; i < min_cmp; i++) {
  91. if (operator[](i) < p_array[i]) {
  92. return true;
  93. } else if (p_array[i] < operator[](i)) {
  94. return false;
  95. }
  96. }
  97. return a_len < b_len;
  98. }
  99. bool Array::operator<=(const Array &p_array) const {
  100. return !operator>(p_array);
  101. }
  102. bool Array::operator>(const Array &p_array) const {
  103. return p_array < *this;
  104. }
  105. bool Array::operator>=(const Array &p_array) const {
  106. return !operator<(p_array);
  107. }
  108. uint32_t Array::hash() const {
  109. uint32_t h = hash_djb2_one_32(0);
  110. for (int i = 0; i < _p->array.size(); i++) {
  111. h = hash_djb2_one_32(_p->array[i].hash(), h);
  112. }
  113. return h;
  114. }
  115. bool Array::_assign(const Array &p_array) {
  116. if (_p->typed.type != Variant::OBJECT && _p->typed.type == p_array._p->typed.type) {
  117. //same type or untyped, just reference, should be fine
  118. _ref(p_array);
  119. } else if (_p->typed.type == Variant::NIL) { //from typed to untyped, must copy, but this is cheap anyway
  120. _p->array = p_array._p->array;
  121. } else if (p_array._p->typed.type == Variant::NIL) { //from untyped to typed, must try to check if they are all valid
  122. if (_p->typed.type == Variant::OBJECT) {
  123. //for objects, it needs full validation, either can be converted or fail
  124. for (int i = 0; i < p_array._p->array.size(); i++) {
  125. if (!_p->typed.validate(p_array._p->array[i], "assign")) {
  126. return false;
  127. }
  128. }
  129. _p->array = p_array._p->array; //then just copy, which is cheap anyway
  130. } else {
  131. //for non objects, we need to check if there is a valid conversion, which needs to happen one by one, so this is the worst case.
  132. Vector<Variant> new_array;
  133. new_array.resize(p_array._p->array.size());
  134. for (int i = 0; i < p_array._p->array.size(); i++) {
  135. Variant src_val = p_array._p->array[i];
  136. if (src_val.get_type() == _p->typed.type) {
  137. new_array.write[i] = src_val;
  138. } else if (Variant::can_convert_strict(src_val.get_type(), _p->typed.type)) {
  139. Variant *ptr = &src_val;
  140. Callable::CallError ce;
  141. Variant::construct(_p->typed.type, new_array.write[i], (const Variant **)&ptr, 1, ce);
  142. if (ce.error != Callable::CallError::CALL_OK) {
  143. ERR_FAIL_V_MSG(false, "Unable to convert array index " + itos(i) + " from '" + Variant::get_type_name(src_val.get_type()) + "' to '" + Variant::get_type_name(_p->typed.type) + "'.");
  144. }
  145. } else {
  146. ERR_FAIL_V_MSG(false, "Unable to convert array index " + itos(i) + " from '" + Variant::get_type_name(src_val.get_type()) + "' to '" + Variant::get_type_name(_p->typed.type) + "'.");
  147. }
  148. }
  149. _p->array = new_array;
  150. }
  151. } else if (_p->typed.can_reference(p_array._p->typed)) { //same type or compatible
  152. _ref(p_array);
  153. } else {
  154. ERR_FAIL_V_MSG(false, "Assignment of arrays of incompatible types.");
  155. }
  156. return true;
  157. }
  158. void Array::operator=(const Array &p_array) {
  159. _ref(p_array);
  160. }
  161. void Array::push_back(const Variant &p_value) {
  162. ERR_FAIL_COND(!_p->typed.validate(p_value, "push_back"));
  163. _p->array.push_back(p_value);
  164. }
  165. void Array::append_array(const Array &p_array) {
  166. ERR_FAIL_COND(!_p->typed.validate(p_array, "append_array"));
  167. _p->array.append_array(p_array._p->array);
  168. }
  169. Error Array::resize(int p_new_size) {
  170. return _p->array.resize(p_new_size);
  171. }
  172. Error Array::insert(int p_pos, const Variant &p_value) {
  173. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "insert"), ERR_INVALID_PARAMETER);
  174. return _p->array.insert(p_pos, p_value);
  175. }
  176. void Array::fill(const Variant &p_value) {
  177. ERR_FAIL_COND(!_p->typed.validate(p_value, "fill"));
  178. _p->array.fill(p_value);
  179. }
  180. void Array::erase(const Variant &p_value) {
  181. ERR_FAIL_COND(!_p->typed.validate(p_value, "erase"));
  182. _p->array.erase(p_value);
  183. }
  184. Variant Array::front() const {
  185. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  186. return operator[](0);
  187. }
  188. Variant Array::back() const {
  189. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  190. return operator[](_p->array.size() - 1);
  191. }
  192. int Array::find(const Variant &p_value, int p_from) const {
  193. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "find"), -1);
  194. return _p->array.find(p_value, p_from);
  195. }
  196. int Array::rfind(const Variant &p_value, int p_from) const {
  197. if (_p->array.size() == 0) {
  198. return -1;
  199. }
  200. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "rfind"), -1);
  201. if (p_from < 0) {
  202. // Relative offset from the end
  203. p_from = _p->array.size() + p_from;
  204. }
  205. if (p_from < 0 || p_from >= _p->array.size()) {
  206. // Limit to array boundaries
  207. p_from = _p->array.size() - 1;
  208. }
  209. for (int i = p_from; i >= 0; i--) {
  210. if (_p->array[i] == p_value) {
  211. return i;
  212. }
  213. }
  214. return -1;
  215. }
  216. int Array::find_last(const Variant &p_value) const {
  217. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "find_last"), -1);
  218. return rfind(p_value);
  219. }
  220. int Array::count(const Variant &p_value) const {
  221. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "count"), 0);
  222. if (_p->array.size() == 0) {
  223. return 0;
  224. }
  225. int amount = 0;
  226. for (int i = 0; i < _p->array.size(); i++) {
  227. if (_p->array[i] == p_value) {
  228. amount++;
  229. }
  230. }
  231. return amount;
  232. }
  233. bool Array::has(const Variant &p_value) const {
  234. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "use 'has'"), false);
  235. return _p->array.find(p_value, 0) != -1;
  236. }
  237. void Array::remove(int p_pos) {
  238. _p->array.remove(p_pos);
  239. }
  240. void Array::set(int p_idx, const Variant &p_value) {
  241. ERR_FAIL_COND(!_p->typed.validate(p_value, "set"));
  242. operator[](p_idx) = p_value;
  243. }
  244. const Variant &Array::get(int p_idx) const {
  245. return operator[](p_idx);
  246. }
  247. Array Array::duplicate(bool p_deep) const {
  248. Array new_arr;
  249. int element_count = size();
  250. new_arr.resize(element_count);
  251. new_arr._p->typed = _p->typed;
  252. for (int i = 0; i < element_count; i++) {
  253. new_arr[i] = p_deep ? get(i).duplicate(p_deep) : get(i);
  254. }
  255. return new_arr;
  256. }
  257. int Array::_clamp_slice_index(int p_index) const {
  258. int arr_size = size();
  259. int fixed_index = CLAMP(p_index, -arr_size, arr_size - 1);
  260. if (fixed_index < 0) {
  261. fixed_index = arr_size + fixed_index;
  262. }
  263. return fixed_index;
  264. }
  265. Array Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const { // like python, but inclusive on upper bound
  266. Array new_arr;
  267. ERR_FAIL_COND_V_MSG(p_step == 0, new_arr, "Array slice step size cannot be zero.");
  268. if (is_empty()) { // Don't try to slice empty arrays.
  269. return new_arr;
  270. }
  271. if (p_step > 0) {
  272. if (p_begin >= size() || p_end < -size()) {
  273. return new_arr;
  274. }
  275. } else { // p_step < 0
  276. if (p_begin < -size() || p_end >= size()) {
  277. return new_arr;
  278. }
  279. }
  280. int begin = _clamp_slice_index(p_begin);
  281. int end = _clamp_slice_index(p_end);
  282. int new_arr_size = MAX(((end - begin + p_step) / p_step), 0);
  283. new_arr.resize(new_arr_size);
  284. if (p_step > 0) {
  285. int dest_idx = 0;
  286. for (int idx = begin; idx <= end; idx += p_step) {
  287. ERR_FAIL_COND_V_MSG(dest_idx < 0 || dest_idx >= new_arr_size, Array(), "Bug in Array slice()");
  288. new_arr[dest_idx++] = p_deep ? get(idx).duplicate(p_deep) : get(idx);
  289. }
  290. } else { // p_step < 0
  291. int dest_idx = 0;
  292. for (int idx = begin; idx >= end; idx += p_step) {
  293. ERR_FAIL_COND_V_MSG(dest_idx < 0 || dest_idx >= new_arr_size, Array(), "Bug in Array slice()");
  294. new_arr[dest_idx++] = p_deep ? get(idx).duplicate(p_deep) : get(idx);
  295. }
  296. }
  297. return new_arr;
  298. }
  299. Array Array::filter(const Callable &p_callable) const {
  300. Array new_arr;
  301. new_arr.resize(size());
  302. int accepted_count = 0;
  303. const Variant *argptrs[1];
  304. for (int i = 0; i < size(); i++) {
  305. argptrs[0] = &get(i);
  306. Variant result;
  307. Callable::CallError ce;
  308. p_callable.call(argptrs, 1, result, ce);
  309. if (ce.error != Callable::CallError::CALL_OK) {
  310. ERR_FAIL_V_MSG(Array(), "Error calling method from 'filter': " + Variant::get_callable_error_text(p_callable, argptrs, 1, ce));
  311. }
  312. if (result.operator bool()) {
  313. new_arr[accepted_count] = get(i);
  314. accepted_count++;
  315. }
  316. }
  317. new_arr.resize(accepted_count);
  318. return new_arr;
  319. }
  320. Array Array::map(const Callable &p_callable) const {
  321. Array new_arr;
  322. new_arr.resize(size());
  323. const Variant *argptrs[1];
  324. for (int i = 0; i < size(); i++) {
  325. argptrs[0] = &get(i);
  326. Variant result;
  327. Callable::CallError ce;
  328. p_callable.call(argptrs, 1, result, ce);
  329. if (ce.error != Callable::CallError::CALL_OK) {
  330. ERR_FAIL_V_MSG(Array(), "Error calling method from 'map': " + Variant::get_callable_error_text(p_callable, argptrs, 1, ce));
  331. }
  332. new_arr[i] = result;
  333. }
  334. return new_arr;
  335. }
  336. Variant Array::reduce(const Callable &p_callable, const Variant &p_accum) const {
  337. int start = 0;
  338. Variant ret = p_accum;
  339. if (ret == Variant() && size() > 0) {
  340. ret = front();
  341. start = 1;
  342. }
  343. const Variant *argptrs[2];
  344. for (int i = start; i < size(); i++) {
  345. argptrs[0] = &ret;
  346. argptrs[1] = &get(i);
  347. Variant result;
  348. Callable::CallError ce;
  349. p_callable.call(argptrs, 2, result, ce);
  350. if (ce.error != Callable::CallError::CALL_OK) {
  351. ERR_FAIL_V_MSG(Variant(), "Error calling method from 'reduce': " + Variant::get_callable_error_text(p_callable, argptrs, 2, ce));
  352. }
  353. ret = result;
  354. }
  355. return ret;
  356. }
  357. struct _ArrayVariantSort {
  358. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  359. bool valid = false;
  360. Variant res;
  361. Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);
  362. if (!valid) {
  363. res = false;
  364. }
  365. return res;
  366. }
  367. };
  368. void Array::sort() {
  369. _p->array.sort_custom<_ArrayVariantSort>();
  370. }
  371. struct _ArrayVariantSortCustom {
  372. Callable func;
  373. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  374. const Variant *args[2] = { &p_l, &p_r };
  375. Callable::CallError err;
  376. Variant res;
  377. func.call(args, 2, res, err);
  378. ERR_FAIL_COND_V_MSG(err.error != Callable::CallError::CALL_OK, false,
  379. "Error calling sorting method: " + Variant::get_callable_error_text(func, args, 1, err));
  380. return res;
  381. }
  382. };
  383. void Array::sort_custom(Callable p_callable) {
  384. SortArray<Variant, _ArrayVariantSortCustom, true> avs;
  385. avs.compare.func = p_callable;
  386. avs.sort(_p->array.ptrw(), _p->array.size());
  387. }
  388. void Array::shuffle() {
  389. const int n = _p->array.size();
  390. if (n < 2) {
  391. return;
  392. }
  393. Variant *data = _p->array.ptrw();
  394. for (int i = n - 1; i >= 1; i--) {
  395. const int j = Math::rand() % (i + 1);
  396. const Variant tmp = data[j];
  397. data[j] = data[i];
  398. data[i] = tmp;
  399. }
  400. }
  401. int Array::bsearch(const Variant &p_value, bool p_before) {
  402. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "binary search"), -1);
  403. SearchArray<Variant, _ArrayVariantSort> avs;
  404. return avs.bisect(_p->array.ptrw(), _p->array.size(), p_value, p_before);
  405. }
  406. int Array::bsearch_custom(const Variant &p_value, Callable p_callable, bool p_before) {
  407. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "custom binary search"), -1);
  408. SearchArray<Variant, _ArrayVariantSortCustom> avs;
  409. avs.compare.func = p_callable;
  410. return avs.bisect(_p->array.ptrw(), _p->array.size(), p_value, p_before);
  411. }
  412. void Array::reverse() {
  413. _p->array.reverse();
  414. }
  415. void Array::push_front(const Variant &p_value) {
  416. ERR_FAIL_COND(!_p->typed.validate(p_value, "push_front"));
  417. _p->array.insert(0, p_value);
  418. }
  419. Variant Array::pop_back() {
  420. if (!_p->array.is_empty()) {
  421. const int n = _p->array.size() - 1;
  422. const Variant ret = _p->array.get(n);
  423. _p->array.resize(n);
  424. return ret;
  425. }
  426. return Variant();
  427. }
  428. Variant Array::pop_front() {
  429. if (!_p->array.is_empty()) {
  430. const Variant ret = _p->array.get(0);
  431. _p->array.remove(0);
  432. return ret;
  433. }
  434. return Variant();
  435. }
  436. Variant Array::pop_at(int p_pos) {
  437. if (_p->array.is_empty()) {
  438. // Return `null` without printing an error to mimic `pop_back()` and `pop_front()` behavior.
  439. return Variant();
  440. }
  441. if (p_pos < 0) {
  442. // Relative offset from the end
  443. p_pos = _p->array.size() + p_pos;
  444. }
  445. ERR_FAIL_INDEX_V_MSG(
  446. p_pos,
  447. _p->array.size(),
  448. Variant(),
  449. vformat(
  450. "The calculated index %s is out of bounds (the array has %s elements). Leaving the array untouched and returning `null`.",
  451. p_pos,
  452. _p->array.size()));
  453. const Variant ret = _p->array.get(p_pos);
  454. _p->array.remove(p_pos);
  455. return ret;
  456. }
  457. Variant Array::min() const {
  458. Variant minval;
  459. for (int i = 0; i < size(); i++) {
  460. if (i == 0) {
  461. minval = get(i);
  462. } else {
  463. bool valid;
  464. Variant ret;
  465. Variant test = get(i);
  466. Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid);
  467. if (!valid) {
  468. return Variant(); //not a valid comparison
  469. }
  470. if (bool(ret)) {
  471. //is less
  472. minval = test;
  473. }
  474. }
  475. }
  476. return minval;
  477. }
  478. Variant Array::max() const {
  479. Variant maxval;
  480. for (int i = 0; i < size(); i++) {
  481. if (i == 0) {
  482. maxval = get(i);
  483. } else {
  484. bool valid;
  485. Variant ret;
  486. Variant test = get(i);
  487. Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);
  488. if (!valid) {
  489. return Variant(); //not a valid comparison
  490. }
  491. if (bool(ret)) {
  492. //is less
  493. maxval = test;
  494. }
  495. }
  496. }
  497. return maxval;
  498. }
  499. const void *Array::id() const {
  500. return _p->array.ptr();
  501. }
  502. Array::Array(const Array &p_from, uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  503. _p = memnew(ArrayPrivate);
  504. _p->refcount.init();
  505. set_typed(p_type, p_class_name, p_script);
  506. _assign(p_from);
  507. }
  508. bool Array::typed_assign(const Array &p_other) {
  509. return _assign(p_other);
  510. }
  511. void Array::set_typed(uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  512. ERR_FAIL_COND_MSG(_p->array.size() > 0, "Type can only be set when array is empty.");
  513. ERR_FAIL_COND_MSG(_p->refcount.get() > 1, "Type can only be set when array has no more than one user.");
  514. ERR_FAIL_COND_MSG(_p->typed.type != Variant::NIL, "Type can only be set once.");
  515. ERR_FAIL_COND_MSG(p_class_name != StringName() && p_type != Variant::OBJECT, "Class names can only be set for type OBJECT");
  516. Ref<Script> script = p_script;
  517. ERR_FAIL_COND_MSG(script.is_valid() && p_class_name == StringName(), "Script class can only be set together with base class name");
  518. _p->typed.type = Variant::Type(p_type);
  519. _p->typed.class_name = p_class_name;
  520. _p->typed.script = script;
  521. _p->typed.where = "TypedArray";
  522. }
  523. bool Array::is_typed() const {
  524. return _p->typed.type != Variant::NIL;
  525. }
  526. uint32_t Array::get_typed_builtin() const {
  527. return _p->typed.type;
  528. }
  529. StringName Array::get_typed_class_name() const {
  530. return _p->typed.class_name;
  531. }
  532. Variant Array::get_typed_script() const {
  533. return _p->typed.script;
  534. }
  535. Array::Array(const Array &p_from) {
  536. _p = nullptr;
  537. _ref(p_from);
  538. }
  539. Array::Array() {
  540. _p = memnew(ArrayPrivate);
  541. _p->refcount.init();
  542. }
  543. Array::~Array() {
  544. _unref();
  545. }