array.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  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 "container_type_validate.h"
  32. #include "core/math/math_funcs.h"
  33. #include "core/object/class_db.h"
  34. #include "core/object/script_language.h"
  35. #include "core/templates/hashfuncs.h"
  36. #include "core/templates/search_array.h"
  37. #include "core/templates/vector.h"
  38. #include "core/variant/callable.h"
  39. #include "core/variant/dictionary.h"
  40. #include "core/variant/variant.h"
  41. struct ArrayPrivate {
  42. SafeRefCount refcount;
  43. Vector<Variant> array;
  44. Variant *read_only = nullptr; // If enabled, a pointer is used to a temporary value that is used to return read-only values.
  45. ContainerTypeValidate typed;
  46. };
  47. void Array::_ref(const Array &p_from) const {
  48. ArrayPrivate *_fp = p_from._p;
  49. ERR_FAIL_NULL(_fp); // Should NOT happen.
  50. if (_fp == _p) {
  51. return; // whatever it is, nothing to do here move along
  52. }
  53. bool success = _fp->refcount.ref();
  54. ERR_FAIL_COND(!success); // should really not happen either
  55. _unref();
  56. _p = _fp;
  57. }
  58. void Array::_unref() const {
  59. if (!_p) {
  60. return;
  61. }
  62. if (_p->refcount.unref()) {
  63. if (_p->read_only) {
  64. memdelete(_p->read_only);
  65. }
  66. memdelete(_p);
  67. }
  68. _p = nullptr;
  69. }
  70. Array::Iterator Array::begin() {
  71. return Iterator(_p->array.ptrw(), _p->read_only);
  72. }
  73. Array::Iterator Array::end() {
  74. return Iterator(_p->array.ptrw() + _p->array.size(), _p->read_only);
  75. }
  76. Array::ConstIterator Array::begin() const {
  77. return ConstIterator(_p->array.ptr(), _p->read_only);
  78. }
  79. Array::ConstIterator Array::end() const {
  80. return ConstIterator(_p->array.ptr() + _p->array.size(), _p->read_only);
  81. }
  82. Variant &Array::operator[](int p_idx) {
  83. if (unlikely(_p->read_only)) {
  84. *_p->read_only = _p->array[p_idx];
  85. return *_p->read_only;
  86. }
  87. return _p->array.write[p_idx];
  88. }
  89. const Variant &Array::operator[](int p_idx) const {
  90. if (unlikely(_p->read_only)) {
  91. *_p->read_only = _p->array[p_idx];
  92. return *_p->read_only;
  93. }
  94. return _p->array[p_idx];
  95. }
  96. int Array::size() const {
  97. return _p->array.size();
  98. }
  99. bool Array::is_empty() const {
  100. return _p->array.is_empty();
  101. }
  102. void Array::clear() {
  103. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  104. _p->array.clear();
  105. }
  106. bool Array::operator==(const Array &p_array) const {
  107. return recursive_equal(p_array, 0);
  108. }
  109. bool Array::operator!=(const Array &p_array) const {
  110. return !recursive_equal(p_array, 0);
  111. }
  112. bool Array::recursive_equal(const Array &p_array, int recursion_count) const {
  113. // Cheap checks
  114. if (_p == p_array._p) {
  115. return true;
  116. }
  117. const Vector<Variant> &a1 = _p->array;
  118. const Vector<Variant> &a2 = p_array._p->array;
  119. const int size = a1.size();
  120. if (size != a2.size()) {
  121. return false;
  122. }
  123. // Heavy O(n) check
  124. if (recursion_count > MAX_RECURSION) {
  125. ERR_PRINT("Max recursion reached");
  126. return true;
  127. }
  128. recursion_count++;
  129. for (int i = 0; i < size; i++) {
  130. if (!a1[i].hash_compare(a2[i], recursion_count, false)) {
  131. return false;
  132. }
  133. }
  134. return true;
  135. }
  136. bool Array::operator<(const Array &p_array) const {
  137. int a_len = size();
  138. int b_len = p_array.size();
  139. int min_cmp = MIN(a_len, b_len);
  140. for (int i = 0; i < min_cmp; i++) {
  141. if (operator[](i) < p_array[i]) {
  142. return true;
  143. } else if (p_array[i] < operator[](i)) {
  144. return false;
  145. }
  146. }
  147. return a_len < b_len;
  148. }
  149. bool Array::operator<=(const Array &p_array) const {
  150. return !operator>(p_array);
  151. }
  152. bool Array::operator>(const Array &p_array) const {
  153. return p_array < *this;
  154. }
  155. bool Array::operator>=(const Array &p_array) const {
  156. return !operator<(p_array);
  157. }
  158. uint32_t Array::hash() const {
  159. return recursive_hash(0);
  160. }
  161. uint32_t Array::recursive_hash(int recursion_count) const {
  162. if (recursion_count > MAX_RECURSION) {
  163. ERR_PRINT("Max recursion reached");
  164. return 0;
  165. }
  166. uint32_t h = hash_murmur3_one_32(Variant::ARRAY);
  167. recursion_count++;
  168. for (int i = 0; i < _p->array.size(); i++) {
  169. h = hash_murmur3_one_32(_p->array[i].recursive_hash(recursion_count), h);
  170. }
  171. return hash_fmix32(h);
  172. }
  173. void Array::operator=(const Array &p_array) {
  174. if (this == &p_array) {
  175. return;
  176. }
  177. _ref(p_array);
  178. }
  179. void Array::assign(const Array &p_array) {
  180. const ContainerTypeValidate &typed = _p->typed;
  181. const ContainerTypeValidate &source_typed = p_array._p->typed;
  182. if (typed == source_typed || typed.type == Variant::NIL || (source_typed.type == Variant::OBJECT && typed.can_reference(source_typed))) {
  183. // from same to same or
  184. // from anything to variants or
  185. // from subclasses to base classes
  186. _p->array = p_array._p->array;
  187. return;
  188. }
  189. const Variant *source = p_array._p->array.ptr();
  190. int size = p_array._p->array.size();
  191. if ((source_typed.type == Variant::NIL && typed.type == Variant::OBJECT) || (source_typed.type == Variant::OBJECT && source_typed.can_reference(typed))) {
  192. // from variants to objects or
  193. // from base classes to subclasses
  194. for (int i = 0; i < size; i++) {
  195. const Variant &element = source[i];
  196. if (element.get_type() != Variant::NIL && (element.get_type() != Variant::OBJECT || !typed.validate_object(element, "assign"))) {
  197. ERR_FAIL_MSG(vformat(R"(Unable to convert array index %d from "%s" to "%s".)", i, Variant::get_type_name(element.get_type()), Variant::get_type_name(typed.type)));
  198. }
  199. }
  200. _p->array = p_array._p->array;
  201. return;
  202. }
  203. if (typed.type == Variant::OBJECT || source_typed.type == Variant::OBJECT) {
  204. ERR_FAIL_MSG(vformat(R"(Cannot assign contents of "Array[%s]" to "Array[%s]".)", Variant::get_type_name(source_typed.type), Variant::get_type_name(typed.type)));
  205. }
  206. Vector<Variant> array;
  207. array.resize(size);
  208. Variant *data = array.ptrw();
  209. if (source_typed.type == Variant::NIL && typed.type != Variant::OBJECT) {
  210. // from variants to primitives
  211. for (int i = 0; i < size; i++) {
  212. const Variant *value = source + i;
  213. if (value->get_type() == typed.type) {
  214. data[i] = *value;
  215. continue;
  216. }
  217. if (!Variant::can_convert_strict(value->get_type(), typed.type)) {
  218. ERR_FAIL_MSG(vformat(R"(Unable to convert array index %d from "%s" to "%s".)", i, Variant::get_type_name(value->get_type()), Variant::get_type_name(typed.type)));
  219. }
  220. Callable::CallError ce;
  221. Variant::construct(typed.type, data[i], &value, 1, ce);
  222. ERR_FAIL_COND_MSG(ce.error, vformat(R"(Unable to convert array index %d from "%s" to "%s".)", i, Variant::get_type_name(value->get_type()), Variant::get_type_name(typed.type)));
  223. }
  224. } else if (Variant::can_convert_strict(source_typed.type, typed.type)) {
  225. // from primitives to different convertible primitives
  226. for (int i = 0; i < size; i++) {
  227. const Variant *value = source + i;
  228. Callable::CallError ce;
  229. Variant::construct(typed.type, data[i], &value, 1, ce);
  230. ERR_FAIL_COND_MSG(ce.error, vformat(R"(Unable to convert array index %d from "%s" to "%s".)", i, Variant::get_type_name(value->get_type()), Variant::get_type_name(typed.type)));
  231. }
  232. } else {
  233. ERR_FAIL_MSG(vformat(R"(Cannot assign contents of "Array[%s]" to "Array[%s]".)", Variant::get_type_name(source_typed.type), Variant::get_type_name(typed.type)));
  234. }
  235. _p->array = array;
  236. }
  237. void Array::push_back(const Variant &p_value) {
  238. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  239. Variant value = p_value;
  240. ERR_FAIL_COND(!_p->typed.validate(value, "push_back"));
  241. _p->array.push_back(value);
  242. }
  243. void Array::append_array(const Array &p_array) {
  244. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  245. Vector<Variant> validated_array = p_array._p->array;
  246. for (int i = 0; i < validated_array.size(); ++i) {
  247. ERR_FAIL_COND(!_p->typed.validate(validated_array.write[i], "append_array"));
  248. }
  249. _p->array.append_array(validated_array);
  250. }
  251. Error Array::resize(int p_new_size) {
  252. ERR_FAIL_COND_V_MSG(_p->read_only, ERR_LOCKED, "Array is in read-only state.");
  253. Variant::Type &variant_type = _p->typed.type;
  254. int old_size = _p->array.size();
  255. Error err = _p->array.resize_zeroed(p_new_size);
  256. if (!err && variant_type != Variant::NIL && variant_type != Variant::OBJECT) {
  257. for (int i = old_size; i < p_new_size; i++) {
  258. VariantInternal::initialize(&_p->array.write[i], variant_type);
  259. }
  260. }
  261. return err;
  262. }
  263. Error Array::insert(int p_pos, const Variant &p_value) {
  264. ERR_FAIL_COND_V_MSG(_p->read_only, ERR_LOCKED, "Array is in read-only state.");
  265. Variant value = p_value;
  266. ERR_FAIL_COND_V(!_p->typed.validate(value, "insert"), ERR_INVALID_PARAMETER);
  267. return _p->array.insert(p_pos, value);
  268. }
  269. void Array::fill(const Variant &p_value) {
  270. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  271. Variant value = p_value;
  272. ERR_FAIL_COND(!_p->typed.validate(value, "fill"));
  273. _p->array.fill(value);
  274. }
  275. void Array::erase(const Variant &p_value) {
  276. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  277. Variant value = p_value;
  278. ERR_FAIL_COND(!_p->typed.validate(value, "erase"));
  279. _p->array.erase(value);
  280. }
  281. Variant Array::front() const {
  282. ERR_FAIL_COND_V_MSG(_p->array.is_empty(), Variant(), "Can't take value from empty array.");
  283. return operator[](0);
  284. }
  285. Variant Array::back() const {
  286. ERR_FAIL_COND_V_MSG(_p->array.is_empty(), Variant(), "Can't take value from empty array.");
  287. return operator[](_p->array.size() - 1);
  288. }
  289. Variant Array::pick_random() const {
  290. ERR_FAIL_COND_V_MSG(_p->array.is_empty(), Variant(), "Can't take value from empty array.");
  291. return operator[](Math::rand() % _p->array.size());
  292. }
  293. int Array::find(const Variant &p_value, int p_from) const {
  294. if (_p->array.size() == 0) {
  295. return -1;
  296. }
  297. Variant value = p_value;
  298. ERR_FAIL_COND_V(!_p->typed.validate(value, "find"), -1);
  299. int ret = -1;
  300. if (p_from < 0 || size() == 0) {
  301. return ret;
  302. }
  303. for (int i = p_from; i < size(); i++) {
  304. if (StringLikeVariantComparator::compare(_p->array[i], value)) {
  305. ret = i;
  306. break;
  307. }
  308. }
  309. return ret;
  310. }
  311. int Array::find_custom(const Callable &p_callable, int p_from) const {
  312. int ret = -1;
  313. if (p_from < 0 || size() == 0) {
  314. return ret;
  315. }
  316. const Variant *argptrs[1];
  317. for (int i = p_from; i < size(); i++) {
  318. const Variant &val = _p->array[i];
  319. argptrs[0] = &val;
  320. Variant res;
  321. Callable::CallError ce;
  322. p_callable.callp(argptrs, 1, res, ce);
  323. if (unlikely(ce.error != Callable::CallError::CALL_OK)) {
  324. ERR_FAIL_V_MSG(ret, vformat("Error calling method from 'find_custom': %s.", Variant::get_callable_error_text(p_callable, argptrs, 1, ce)));
  325. }
  326. ERR_FAIL_COND_V_MSG(res.get_type() != Variant::Type::BOOL, ret, "Error on method from 'find_custom': Return type of callable must be boolean.");
  327. if (res.operator bool()) {
  328. return i;
  329. }
  330. }
  331. return ret;
  332. }
  333. int Array::rfind(const Variant &p_value, int p_from) const {
  334. if (_p->array.size() == 0) {
  335. return -1;
  336. }
  337. Variant value = p_value;
  338. ERR_FAIL_COND_V(!_p->typed.validate(value, "rfind"), -1);
  339. if (p_from < 0) {
  340. // Relative offset from the end
  341. p_from = _p->array.size() + p_from;
  342. }
  343. if (p_from < 0 || p_from >= _p->array.size()) {
  344. // Limit to array boundaries
  345. p_from = _p->array.size() - 1;
  346. }
  347. for (int i = p_from; i >= 0; i--) {
  348. if (StringLikeVariantComparator::compare(_p->array[i], value)) {
  349. return i;
  350. }
  351. }
  352. return -1;
  353. }
  354. int Array::rfind_custom(const Callable &p_callable, int p_from) const {
  355. if (_p->array.size() == 0) {
  356. return -1;
  357. }
  358. if (p_from < 0) {
  359. // Relative offset from the end.
  360. p_from = _p->array.size() + p_from;
  361. }
  362. if (p_from < 0 || p_from >= _p->array.size()) {
  363. // Limit to array boundaries.
  364. p_from = _p->array.size() - 1;
  365. }
  366. const Variant *argptrs[1];
  367. for (int i = p_from; i >= 0; i--) {
  368. const Variant &val = _p->array[i];
  369. argptrs[0] = &val;
  370. Variant res;
  371. Callable::CallError ce;
  372. p_callable.callp(argptrs, 1, res, ce);
  373. if (unlikely(ce.error != Callable::CallError::CALL_OK)) {
  374. ERR_FAIL_V_MSG(-1, vformat("Error calling method from 'rfind_custom': %s.", Variant::get_callable_error_text(p_callable, argptrs, 1, ce)));
  375. }
  376. ERR_FAIL_COND_V_MSG(res.get_type() != Variant::Type::BOOL, -1, "Error on method from 'rfind_custom': Return type of callable must be boolean.");
  377. if (res.operator bool()) {
  378. return i;
  379. }
  380. }
  381. return -1;
  382. }
  383. int Array::count(const Variant &p_value) const {
  384. Variant value = p_value;
  385. ERR_FAIL_COND_V(!_p->typed.validate(value, "count"), 0);
  386. if (_p->array.size() == 0) {
  387. return 0;
  388. }
  389. int amount = 0;
  390. for (int i = 0; i < _p->array.size(); i++) {
  391. if (StringLikeVariantComparator::compare(_p->array[i], value)) {
  392. amount++;
  393. }
  394. }
  395. return amount;
  396. }
  397. bool Array::has(const Variant &p_value) const {
  398. Variant value = p_value;
  399. ERR_FAIL_COND_V(!_p->typed.validate(value, "use 'has'"), false);
  400. return find(value) != -1;
  401. }
  402. void Array::remove_at(int p_pos) {
  403. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  404. _p->array.remove_at(p_pos);
  405. }
  406. void Array::set(int p_idx, const Variant &p_value) {
  407. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  408. Variant value = p_value;
  409. ERR_FAIL_COND(!_p->typed.validate(value, "set"));
  410. operator[](p_idx) = value;
  411. }
  412. const Variant &Array::get(int p_idx) const {
  413. return operator[](p_idx);
  414. }
  415. Array Array::duplicate(bool p_deep) const {
  416. return recursive_duplicate(p_deep, 0);
  417. }
  418. Array Array::recursive_duplicate(bool p_deep, int recursion_count) const {
  419. Array new_arr;
  420. new_arr._p->typed = _p->typed;
  421. if (recursion_count > MAX_RECURSION) {
  422. ERR_PRINT("Max recursion reached");
  423. return new_arr;
  424. }
  425. if (p_deep) {
  426. recursion_count++;
  427. int element_count = size();
  428. new_arr.resize(element_count);
  429. for (int i = 0; i < element_count; i++) {
  430. new_arr[i] = get(i).recursive_duplicate(true, recursion_count);
  431. }
  432. } else {
  433. new_arr._p->array = _p->array;
  434. }
  435. return new_arr;
  436. }
  437. Array Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const {
  438. Array result;
  439. result._p->typed = _p->typed;
  440. ERR_FAIL_COND_V_MSG(p_step == 0, result, "Slice step cannot be zero.");
  441. const int s = size();
  442. if (s == 0 || (p_begin < -s && p_step < 0) || (p_begin >= s && p_step > 0)) {
  443. return result;
  444. }
  445. int begin = CLAMP(p_begin, -s, s - 1);
  446. if (begin < 0) {
  447. begin += s;
  448. }
  449. int end = CLAMP(p_end, -s - 1, s);
  450. if (end < 0) {
  451. end += s;
  452. }
  453. ERR_FAIL_COND_V_MSG(p_step > 0 && begin > end, result, "Slice step is positive, but bounds are decreasing.");
  454. ERR_FAIL_COND_V_MSG(p_step < 0 && begin < end, result, "Slice step is negative, but bounds are increasing.");
  455. int result_size = (end - begin) / p_step + (((end - begin) % p_step != 0) ? 1 : 0);
  456. result.resize(result_size);
  457. for (int src_idx = begin, dest_idx = 0; dest_idx < result_size; ++dest_idx) {
  458. result[dest_idx] = p_deep ? get(src_idx).duplicate(true) : get(src_idx);
  459. src_idx += p_step;
  460. }
  461. return result;
  462. }
  463. Array Array::filter(const Callable &p_callable) const {
  464. Array new_arr;
  465. new_arr.resize(size());
  466. new_arr._p->typed = _p->typed;
  467. int accepted_count = 0;
  468. const Variant *argptrs[1];
  469. for (int i = 0; i < size(); i++) {
  470. argptrs[0] = &get(i);
  471. Variant result;
  472. Callable::CallError ce;
  473. p_callable.callp(argptrs, 1, result, ce);
  474. if (ce.error != Callable::CallError::CALL_OK) {
  475. ERR_FAIL_V_MSG(Array(), vformat("Error calling method from 'filter': %s.", Variant::get_callable_error_text(p_callable, argptrs, 1, ce)));
  476. }
  477. if (result.operator bool()) {
  478. new_arr[accepted_count] = get(i);
  479. accepted_count++;
  480. }
  481. }
  482. new_arr.resize(accepted_count);
  483. return new_arr;
  484. }
  485. Array Array::map(const Callable &p_callable) const {
  486. Array new_arr;
  487. new_arr.resize(size());
  488. const Variant *argptrs[1];
  489. for (int i = 0; i < size(); i++) {
  490. argptrs[0] = &get(i);
  491. Variant result;
  492. Callable::CallError ce;
  493. p_callable.callp(argptrs, 1, result, ce);
  494. if (ce.error != Callable::CallError::CALL_OK) {
  495. ERR_FAIL_V_MSG(Array(), vformat("Error calling method from 'map': %s.", Variant::get_callable_error_text(p_callable, argptrs, 1, ce)));
  496. }
  497. new_arr[i] = result;
  498. }
  499. return new_arr;
  500. }
  501. Variant Array::reduce(const Callable &p_callable, const Variant &p_accum) const {
  502. int start = 0;
  503. Variant ret = p_accum;
  504. if (ret == Variant() && size() > 0) {
  505. ret = front();
  506. start = 1;
  507. }
  508. const Variant *argptrs[2];
  509. for (int i = start; i < size(); i++) {
  510. argptrs[0] = &ret;
  511. argptrs[1] = &get(i);
  512. Variant result;
  513. Callable::CallError ce;
  514. p_callable.callp(argptrs, 2, result, ce);
  515. if (ce.error != Callable::CallError::CALL_OK) {
  516. ERR_FAIL_V_MSG(Variant(), vformat("Error calling method from 'reduce': %s.", Variant::get_callable_error_text(p_callable, argptrs, 2, ce)));
  517. }
  518. ret = result;
  519. }
  520. return ret;
  521. }
  522. bool Array::any(const Callable &p_callable) const {
  523. const Variant *argptrs[1];
  524. for (int i = 0; i < size(); i++) {
  525. argptrs[0] = &get(i);
  526. Variant result;
  527. Callable::CallError ce;
  528. p_callable.callp(argptrs, 1, result, ce);
  529. if (ce.error != Callable::CallError::CALL_OK) {
  530. ERR_FAIL_V_MSG(false, vformat("Error calling method from 'any': %s.", Variant::get_callable_error_text(p_callable, argptrs, 1, ce)));
  531. }
  532. if (result.operator bool()) {
  533. // Return as early as possible when one of the conditions is `true`.
  534. // This improves performance compared to relying on `filter(...).size() >= 1`.
  535. return true;
  536. }
  537. }
  538. return false;
  539. }
  540. bool Array::all(const Callable &p_callable) const {
  541. const Variant *argptrs[1];
  542. for (int i = 0; i < size(); i++) {
  543. argptrs[0] = &get(i);
  544. Variant result;
  545. Callable::CallError ce;
  546. p_callable.callp(argptrs, 1, result, ce);
  547. if (ce.error != Callable::CallError::CALL_OK) {
  548. ERR_FAIL_V_MSG(false, vformat("Error calling method from 'all': %s.", Variant::get_callable_error_text(p_callable, argptrs, 1, ce)));
  549. }
  550. if (!(result.operator bool())) {
  551. // Return as early as possible when one of the inverted conditions is `false`.
  552. // This improves performance compared to relying on `filter(...).size() >= array_size().`.
  553. return false;
  554. }
  555. }
  556. return true;
  557. }
  558. struct _ArrayVariantSort {
  559. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  560. bool valid = false;
  561. Variant res;
  562. Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);
  563. if (!valid) {
  564. res = false;
  565. }
  566. return res;
  567. }
  568. };
  569. void Array::sort() {
  570. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  571. _p->array.sort_custom<_ArrayVariantSort>();
  572. }
  573. void Array::sort_custom(const Callable &p_callable) {
  574. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  575. _p->array.sort_custom<CallableComparator, true>(p_callable);
  576. }
  577. void Array::shuffle() {
  578. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  579. const int n = _p->array.size();
  580. if (n < 2) {
  581. return;
  582. }
  583. Variant *data = _p->array.ptrw();
  584. for (int i = n - 1; i >= 1; i--) {
  585. const int j = Math::rand() % (i + 1);
  586. const Variant tmp = data[j];
  587. data[j] = data[i];
  588. data[i] = tmp;
  589. }
  590. }
  591. int Array::bsearch(const Variant &p_value, bool p_before) const {
  592. Variant value = p_value;
  593. ERR_FAIL_COND_V(!_p->typed.validate(value, "binary search"), -1);
  594. SearchArray<Variant, _ArrayVariantSort> avs;
  595. return avs.bisect(_p->array.ptrw(), _p->array.size(), value, p_before);
  596. }
  597. int Array::bsearch_custom(const Variant &p_value, const Callable &p_callable, bool p_before) const {
  598. Variant value = p_value;
  599. ERR_FAIL_COND_V(!_p->typed.validate(value, "custom binary search"), -1);
  600. return _p->array.bsearch_custom<CallableComparator>(value, p_before, p_callable);
  601. }
  602. void Array::reverse() {
  603. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  604. _p->array.reverse();
  605. }
  606. void Array::push_front(const Variant &p_value) {
  607. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  608. Variant value = p_value;
  609. ERR_FAIL_COND(!_p->typed.validate(value, "push_front"));
  610. _p->array.insert(0, value);
  611. }
  612. Variant Array::pop_back() {
  613. ERR_FAIL_COND_V_MSG(_p->read_only, Variant(), "Array is in read-only state.");
  614. if (!_p->array.is_empty()) {
  615. const int n = _p->array.size() - 1;
  616. const Variant ret = _p->array.get(n);
  617. _p->array.resize(n);
  618. return ret;
  619. }
  620. return Variant();
  621. }
  622. Variant Array::pop_front() {
  623. ERR_FAIL_COND_V_MSG(_p->read_only, Variant(), "Array is in read-only state.");
  624. if (!_p->array.is_empty()) {
  625. const Variant ret = _p->array.get(0);
  626. _p->array.remove_at(0);
  627. return ret;
  628. }
  629. return Variant();
  630. }
  631. Variant Array::pop_at(int p_pos) {
  632. ERR_FAIL_COND_V_MSG(_p->read_only, Variant(), "Array is in read-only state.");
  633. if (_p->array.is_empty()) {
  634. // Return `null` without printing an error to mimic `pop_back()` and `pop_front()` behavior.
  635. return Variant();
  636. }
  637. if (p_pos < 0) {
  638. // Relative offset from the end
  639. p_pos = _p->array.size() + p_pos;
  640. }
  641. ERR_FAIL_INDEX_V_MSG(
  642. p_pos,
  643. _p->array.size(),
  644. Variant(),
  645. vformat(
  646. "The calculated index %s is out of bounds (the array has %s elements). Leaving the array untouched and returning `null`.",
  647. p_pos,
  648. _p->array.size()));
  649. const Variant ret = _p->array.get(p_pos);
  650. _p->array.remove_at(p_pos);
  651. return ret;
  652. }
  653. Variant Array::min() const {
  654. Variant minval;
  655. for (int i = 0; i < size(); i++) {
  656. if (i == 0) {
  657. minval = get(i);
  658. } else {
  659. bool valid;
  660. Variant ret;
  661. Variant test = get(i);
  662. Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid);
  663. if (!valid) {
  664. return Variant(); //not a valid comparison
  665. }
  666. if (bool(ret)) {
  667. //is less
  668. minval = test;
  669. }
  670. }
  671. }
  672. return minval;
  673. }
  674. Variant Array::max() const {
  675. Variant maxval;
  676. for (int i = 0; i < size(); i++) {
  677. if (i == 0) {
  678. maxval = get(i);
  679. } else {
  680. bool valid;
  681. Variant ret;
  682. Variant test = get(i);
  683. Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);
  684. if (!valid) {
  685. return Variant(); //not a valid comparison
  686. }
  687. if (bool(ret)) {
  688. //is greater
  689. maxval = test;
  690. }
  691. }
  692. }
  693. return maxval;
  694. }
  695. const void *Array::id() const {
  696. return _p;
  697. }
  698. Array::Array(const Array &p_from, uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  699. _p = memnew(ArrayPrivate);
  700. _p->refcount.init();
  701. set_typed(p_type, p_class_name, p_script);
  702. assign(p_from);
  703. }
  704. void Array::set_typed(const ContainerType &p_element_type) {
  705. set_typed(p_element_type.builtin_type, p_element_type.class_name, p_element_type.script);
  706. }
  707. void Array::set_typed(uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  708. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  709. ERR_FAIL_COND_MSG(_p->array.size() > 0, "Type can only be set when array is empty.");
  710. ERR_FAIL_COND_MSG(_p->refcount.get() > 1, "Type can only be set when array has no more than one user.");
  711. ERR_FAIL_COND_MSG(_p->typed.type != Variant::NIL, "Type can only be set once.");
  712. ERR_FAIL_COND_MSG(p_class_name != StringName() && p_type != Variant::OBJECT, "Class names can only be set for type OBJECT");
  713. Ref<Script> script = p_script;
  714. ERR_FAIL_COND_MSG(script.is_valid() && p_class_name == StringName(), "Script class can only be set together with base class name");
  715. _p->typed.type = Variant::Type(p_type);
  716. _p->typed.class_name = p_class_name;
  717. _p->typed.script = script;
  718. _p->typed.where = "TypedArray";
  719. }
  720. bool Array::is_typed() const {
  721. return _p->typed.type != Variant::NIL;
  722. }
  723. bool Array::is_same_typed(const Array &p_other) const {
  724. return _p->typed == p_other._p->typed;
  725. }
  726. bool Array::is_same_instance(const Array &p_other) const {
  727. return _p == p_other._p;
  728. }
  729. ContainerType Array::get_element_type() const {
  730. ContainerType type;
  731. type.builtin_type = _p->typed.type;
  732. type.class_name = _p->typed.class_name;
  733. type.script = _p->typed.script;
  734. return type;
  735. }
  736. uint32_t Array::get_typed_builtin() const {
  737. return _p->typed.type;
  738. }
  739. StringName Array::get_typed_class_name() const {
  740. return _p->typed.class_name;
  741. }
  742. Variant Array::get_typed_script() const {
  743. return _p->typed.script;
  744. }
  745. Array Array::create_read_only() {
  746. Array array;
  747. array.make_read_only();
  748. return array;
  749. }
  750. void Array::make_read_only() {
  751. if (_p->read_only == nullptr) {
  752. _p->read_only = memnew(Variant);
  753. }
  754. }
  755. bool Array::is_read_only() const {
  756. return _p->read_only != nullptr;
  757. }
  758. Array::Array(const Array &p_from) {
  759. _p = nullptr;
  760. _ref(p_from);
  761. }
  762. Array::Array() {
  763. _p = memnew(ArrayPrivate);
  764. _p->refcount.init();
  765. }
  766. Array::~Array() {
  767. _unref();
  768. }