array.cpp 27 KB

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