array.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  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::reserve(int p_new_size) {
  266. ERR_FAIL_COND_V_MSG(_p->read_only, ERR_LOCKED, "Array is in read-only state.");
  267. return _p->array.reserve(p_new_size);
  268. }
  269. Error Array::insert(int p_pos, const Variant &p_value) {
  270. ERR_FAIL_COND_V_MSG(_p->read_only, ERR_LOCKED, "Array is in read-only state.");
  271. Variant value = p_value;
  272. ERR_FAIL_COND_V(!_p->typed.validate(value, "insert"), ERR_INVALID_PARAMETER);
  273. if (p_pos < 0) {
  274. // Relative offset from the end.
  275. p_pos = _p->array.size() + p_pos;
  276. }
  277. 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()));
  278. return _p->array.insert(p_pos, std::move(value));
  279. }
  280. void Array::fill(const Variant &p_value) {
  281. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  282. Variant value = p_value;
  283. ERR_FAIL_COND(!_p->typed.validate(value, "fill"));
  284. _p->array.fill(std::move(value));
  285. }
  286. void Array::erase(const Variant &p_value) {
  287. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  288. Variant value = p_value;
  289. ERR_FAIL_COND(!_p->typed.validate(value, "erase"));
  290. _p->array.erase(value);
  291. }
  292. Variant Array::front() const {
  293. ERR_FAIL_COND_V_MSG(_p->array.is_empty(), Variant(), "Can't take value from empty array.");
  294. return operator[](0);
  295. }
  296. Variant Array::back() const {
  297. ERR_FAIL_COND_V_MSG(_p->array.is_empty(), Variant(), "Can't take value from empty array.");
  298. return operator[](_p->array.size() - 1);
  299. }
  300. Variant Array::pick_random() const {
  301. ERR_FAIL_COND_V_MSG(_p->array.is_empty(), Variant(), "Can't take value from empty array.");
  302. return operator[](Math::rand() % _p->array.size());
  303. }
  304. int Array::find(const Variant &p_value, int p_from) const {
  305. if (_p->array.is_empty()) {
  306. return -1;
  307. }
  308. Variant value = p_value;
  309. ERR_FAIL_COND_V(!_p->typed.validate(value, "find"), -1);
  310. int ret = -1;
  311. if (p_from < 0 || size() == 0) {
  312. return ret;
  313. }
  314. for (int i = p_from; i < size(); i++) {
  315. if (StringLikeVariantComparator::compare(_p->array[i], value)) {
  316. ret = i;
  317. break;
  318. }
  319. }
  320. return ret;
  321. }
  322. int Array::find_custom(const Callable &p_callable, int p_from) const {
  323. int ret = -1;
  324. if (p_from < 0 || size() == 0) {
  325. return ret;
  326. }
  327. const Variant *argptrs[1];
  328. for (int i = p_from; i < size(); i++) {
  329. const Variant &val = _p->array[i];
  330. argptrs[0] = &val;
  331. Variant res;
  332. Callable::CallError ce;
  333. p_callable.callp(argptrs, 1, res, ce);
  334. if (unlikely(ce.error != Callable::CallError::CALL_OK)) {
  335. ERR_FAIL_V_MSG(ret, vformat("Error calling method from 'find_custom': %s.", Variant::get_callable_error_text(p_callable, argptrs, 1, ce)));
  336. }
  337. 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.");
  338. if (res.operator bool()) {
  339. return i;
  340. }
  341. }
  342. return ret;
  343. }
  344. int Array::rfind(const Variant &p_value, int p_from) const {
  345. if (_p->array.is_empty()) {
  346. return -1;
  347. }
  348. Variant value = p_value;
  349. ERR_FAIL_COND_V(!_p->typed.validate(value, "rfind"), -1);
  350. if (p_from < 0) {
  351. // Relative offset from the end
  352. p_from = _p->array.size() + p_from;
  353. }
  354. if (p_from < 0 || p_from >= _p->array.size()) {
  355. // Limit to array boundaries
  356. p_from = _p->array.size() - 1;
  357. }
  358. for (int i = p_from; i >= 0; i--) {
  359. if (StringLikeVariantComparator::compare(_p->array[i], value)) {
  360. return i;
  361. }
  362. }
  363. return -1;
  364. }
  365. int Array::rfind_custom(const Callable &p_callable, int p_from) const {
  366. if (_p->array.is_empty()) {
  367. return -1;
  368. }
  369. if (p_from < 0) {
  370. // Relative offset from the end.
  371. p_from = _p->array.size() + p_from;
  372. }
  373. if (p_from < 0 || p_from >= _p->array.size()) {
  374. // Limit to array boundaries.
  375. p_from = _p->array.size() - 1;
  376. }
  377. const Variant *argptrs[1];
  378. for (int i = p_from; i >= 0; i--) {
  379. const Variant &val = _p->array[i];
  380. argptrs[0] = &val;
  381. Variant res;
  382. Callable::CallError ce;
  383. p_callable.callp(argptrs, 1, res, ce);
  384. if (unlikely(ce.error != Callable::CallError::CALL_OK)) {
  385. ERR_FAIL_V_MSG(-1, vformat("Error calling method from 'rfind_custom': %s.", Variant::get_callable_error_text(p_callable, argptrs, 1, ce)));
  386. }
  387. 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.");
  388. if (res.operator bool()) {
  389. return i;
  390. }
  391. }
  392. return -1;
  393. }
  394. int Array::count(const Variant &p_value) const {
  395. Variant value = p_value;
  396. ERR_FAIL_COND_V(!_p->typed.validate(value, "count"), 0);
  397. if (_p->array.is_empty()) {
  398. return 0;
  399. }
  400. int amount = 0;
  401. for (int i = 0; i < _p->array.size(); i++) {
  402. if (StringLikeVariantComparator::compare(_p->array[i], value)) {
  403. amount++;
  404. }
  405. }
  406. return amount;
  407. }
  408. bool Array::has(const Variant &p_value) const {
  409. Variant value = p_value;
  410. ERR_FAIL_COND_V(!_p->typed.validate(value, "use 'has'"), false);
  411. return find(value) != -1;
  412. }
  413. void Array::remove_at(int p_pos) {
  414. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  415. if (p_pos < 0) {
  416. // Relative offset from the end.
  417. p_pos = _p->array.size() + p_pos;
  418. }
  419. 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()));
  420. _p->array.remove_at(p_pos);
  421. }
  422. void Array::set(int p_idx, const Variant &p_value) {
  423. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  424. Variant value = p_value;
  425. ERR_FAIL_COND(!_p->typed.validate(value, "set"));
  426. _p->array.write[p_idx] = std::move(value);
  427. }
  428. const Variant &Array::get(int p_idx) const {
  429. return operator[](p_idx);
  430. }
  431. Array Array::duplicate(bool p_deep) const {
  432. return recursive_duplicate(p_deep, RESOURCE_DEEP_DUPLICATE_NONE, 0);
  433. }
  434. Array Array::duplicate_deep(ResourceDeepDuplicateMode p_deep_subresources_mode) const {
  435. return recursive_duplicate(true, p_deep_subresources_mode, 0);
  436. }
  437. Array Array::recursive_duplicate(bool p_deep, ResourceDeepDuplicateMode p_deep_subresources_mode, int recursion_count) const {
  438. Array new_arr;
  439. new_arr._p->typed = _p->typed;
  440. if (recursion_count > MAX_RECURSION) {
  441. ERR_PRINT("Max recursion reached");
  442. return new_arr;
  443. }
  444. if (p_deep) {
  445. bool is_call_chain_end = recursion_count == 0;
  446. recursion_count++;
  447. int element_count = size();
  448. new_arr.resize(element_count);
  449. Variant *write = new_arr._p->array.ptrw();
  450. for (int i = 0; i < element_count; i++) {
  451. write[i] = get(i).recursive_duplicate(true, p_deep_subresources_mode, recursion_count);
  452. }
  453. // Variant::recursive_duplicate() may have created a remap cache by now.
  454. if (is_call_chain_end) {
  455. Resource::_teardown_duplicate_from_variant();
  456. }
  457. } else {
  458. new_arr._p->array = _p->array;
  459. }
  460. return new_arr;
  461. }
  462. Array Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const {
  463. Array result;
  464. result._p->typed = _p->typed;
  465. ERR_FAIL_COND_V_MSG(p_step == 0, result, "Slice step cannot be zero.");
  466. const int s = size();
  467. if (s == 0 || (p_begin < -s && p_step < 0) || (p_begin >= s && p_step > 0)) {
  468. return result;
  469. }
  470. int begin = CLAMP(p_begin, -s, s - 1);
  471. if (begin < 0) {
  472. begin += s;
  473. }
  474. int end = CLAMP(p_end, -s - 1, s);
  475. if (end < 0) {
  476. end += s;
  477. }
  478. ERR_FAIL_COND_V_MSG(p_step > 0 && begin > end, result, "Slice step is positive, but bounds are decreasing.");
  479. ERR_FAIL_COND_V_MSG(p_step < 0 && begin < end, result, "Slice step is negative, but bounds are increasing.");
  480. int result_size = (end - begin) / p_step + (((end - begin) % p_step != 0) ? 1 : 0);
  481. result.resize(result_size);
  482. Variant *write = result._p->array.ptrw();
  483. for (int src_idx = begin, dest_idx = 0; dest_idx < result_size; ++dest_idx) {
  484. write[dest_idx] = p_deep ? get(src_idx).duplicate(true) : get(src_idx);
  485. src_idx += p_step;
  486. }
  487. return result;
  488. }
  489. Array Array::filter(const Callable &p_callable) const {
  490. Array new_arr;
  491. new_arr.resize(size());
  492. new_arr._p->typed = _p->typed;
  493. int accepted_count = 0;
  494. const Variant *argptrs[1];
  495. Variant *write = new_arr._p->array.ptrw();
  496. for (int i = 0; i < size(); i++) {
  497. argptrs[0] = &get(i);
  498. Variant result;
  499. Callable::CallError ce;
  500. p_callable.callp(argptrs, 1, result, ce);
  501. if (ce.error != Callable::CallError::CALL_OK) {
  502. ERR_FAIL_V_MSG(Array(), vformat("Error calling method from 'filter': %s.", Variant::get_callable_error_text(p_callable, argptrs, 1, ce)));
  503. }
  504. if (result.operator bool()) {
  505. write[accepted_count] = get(i);
  506. accepted_count++;
  507. }
  508. }
  509. new_arr.resize(accepted_count);
  510. return new_arr;
  511. }
  512. Array Array::map(const Callable &p_callable) const {
  513. Array new_arr;
  514. new_arr.resize(size());
  515. const Variant *argptrs[1];
  516. Variant *write = new_arr._p->array.ptrw();
  517. for (int i = 0; i < size(); i++) {
  518. argptrs[0] = &get(i);
  519. Callable::CallError ce;
  520. p_callable.callp(argptrs, 1, write[i], ce);
  521. if (ce.error != Callable::CallError::CALL_OK) {
  522. ERR_FAIL_V_MSG(Array(), vformat("Error calling method from 'map': %s.", Variant::get_callable_error_text(p_callable, argptrs, 1, ce)));
  523. }
  524. }
  525. return new_arr;
  526. }
  527. Variant Array::reduce(const Callable &p_callable, const Variant &p_accum) const {
  528. int start = 0;
  529. Variant ret = p_accum;
  530. if (ret == Variant() && size() > 0) {
  531. ret = front();
  532. start = 1;
  533. }
  534. const Variant *argptrs[2];
  535. for (int i = start; i < size(); i++) {
  536. argptrs[0] = &ret;
  537. argptrs[1] = &get(i);
  538. Variant result;
  539. Callable::CallError ce;
  540. p_callable.callp(argptrs, 2, result, ce);
  541. if (ce.error != Callable::CallError::CALL_OK) {
  542. ERR_FAIL_V_MSG(Variant(), vformat("Error calling method from 'reduce': %s.", Variant::get_callable_error_text(p_callable, argptrs, 2, ce)));
  543. }
  544. ret = result;
  545. }
  546. return ret;
  547. }
  548. bool Array::any(const Callable &p_callable) const {
  549. const Variant *argptrs[1];
  550. for (int i = 0; i < size(); i++) {
  551. argptrs[0] = &get(i);
  552. Variant result;
  553. Callable::CallError ce;
  554. p_callable.callp(argptrs, 1, result, ce);
  555. if (ce.error != Callable::CallError::CALL_OK) {
  556. ERR_FAIL_V_MSG(false, vformat("Error calling method from 'any': %s.", Variant::get_callable_error_text(p_callable, argptrs, 1, ce)));
  557. }
  558. if (result.operator bool()) {
  559. // Return as early as possible when one of the conditions is `true`.
  560. // This improves performance compared to relying on `filter(...).size() >= 1`.
  561. return true;
  562. }
  563. }
  564. return false;
  565. }
  566. bool Array::all(const Callable &p_callable) const {
  567. const Variant *argptrs[1];
  568. for (int i = 0; i < size(); i++) {
  569. argptrs[0] = &get(i);
  570. Variant result;
  571. Callable::CallError ce;
  572. p_callable.callp(argptrs, 1, result, ce);
  573. if (ce.error != Callable::CallError::CALL_OK) {
  574. ERR_FAIL_V_MSG(false, vformat("Error calling method from 'all': %s.", Variant::get_callable_error_text(p_callable, argptrs, 1, ce)));
  575. }
  576. if (!(result.operator bool())) {
  577. // Return as early as possible when one of the inverted conditions is `false`.
  578. // This improves performance compared to relying on `filter(...).size() >= array_size().`.
  579. return false;
  580. }
  581. }
  582. return true;
  583. }
  584. struct _ArrayVariantSort {
  585. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  586. bool valid = false;
  587. Variant res;
  588. Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);
  589. if (!valid) {
  590. res = false;
  591. }
  592. return res;
  593. }
  594. };
  595. void Array::sort() {
  596. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  597. _p->array.sort_custom<_ArrayVariantSort>();
  598. }
  599. void Array::sort_custom(const Callable &p_callable) {
  600. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  601. _p->array.sort_custom<CallableComparator, true>(p_callable);
  602. }
  603. void Array::shuffle() {
  604. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  605. const int n = _p->array.size();
  606. if (n < 2) {
  607. return;
  608. }
  609. Variant *data = _p->array.ptrw();
  610. for (int i = n - 1; i >= 1; i--) {
  611. const int j = Math::rand() % (i + 1);
  612. SWAP(data[i], data[j]);
  613. }
  614. }
  615. int Array::bsearch(const Variant &p_value, bool p_before) const {
  616. Variant value = p_value;
  617. ERR_FAIL_COND_V(!_p->typed.validate(value, "binary search"), -1);
  618. return _p->array.span().bisect<_ArrayVariantSort>(value, p_before);
  619. }
  620. int Array::bsearch_custom(const Variant &p_value, const Callable &p_callable, bool p_before) const {
  621. Variant value = p_value;
  622. ERR_FAIL_COND_V(!_p->typed.validate(value, "custom binary search"), -1);
  623. return _p->array.bsearch_custom<CallableComparator>(value, p_before, p_callable);
  624. }
  625. void Array::reverse() {
  626. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  627. _p->array.reverse();
  628. }
  629. void Array::push_front(const Variant &p_value) {
  630. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  631. Variant value = p_value;
  632. ERR_FAIL_COND(!_p->typed.validate(value, "push_front"));
  633. _p->array.insert(0, std::move(value));
  634. }
  635. Variant Array::pop_back() {
  636. ERR_FAIL_COND_V_MSG(_p->read_only, Variant(), "Array is in read-only state.");
  637. if (!_p->array.is_empty()) {
  638. const int n = _p->array.size() - 1;
  639. const Variant ret = _p->array.get(n);
  640. _p->array.resize(n);
  641. return ret;
  642. }
  643. return Variant();
  644. }
  645. Variant Array::pop_front() {
  646. ERR_FAIL_COND_V_MSG(_p->read_only, Variant(), "Array is in read-only state.");
  647. if (!_p->array.is_empty()) {
  648. const Variant ret = _p->array.get(0);
  649. _p->array.remove_at(0);
  650. return ret;
  651. }
  652. return Variant();
  653. }
  654. Variant Array::pop_at(int p_pos) {
  655. ERR_FAIL_COND_V_MSG(_p->read_only, Variant(), "Array is in read-only state.");
  656. if (_p->array.is_empty()) {
  657. // Return `null` without printing an error to mimic `pop_back()` and `pop_front()` behavior.
  658. return Variant();
  659. }
  660. if (p_pos < 0) {
  661. // Relative offset from the end
  662. p_pos = _p->array.size() + p_pos;
  663. }
  664. ERR_FAIL_INDEX_V_MSG(
  665. p_pos,
  666. _p->array.size(),
  667. Variant(),
  668. vformat(
  669. "The calculated index %s is out of bounds (the array has %s elements). Leaving the array untouched and returning `null`.",
  670. p_pos,
  671. _p->array.size()));
  672. const Variant ret = _p->array.get(p_pos);
  673. _p->array.remove_at(p_pos);
  674. return ret;
  675. }
  676. Variant Array::min() const {
  677. int array_size = size();
  678. if (array_size == 0) {
  679. return Variant();
  680. }
  681. int min_index = 0;
  682. Variant is_less;
  683. for (int i = 1; i < array_size; i++) {
  684. bool valid;
  685. Variant::evaluate(Variant::OP_LESS, _p->array[i], _p->array[min_index], is_less, valid);
  686. if (!valid) {
  687. return Variant(); //not a valid comparison
  688. }
  689. if (bool(is_less)) {
  690. min_index = i;
  691. }
  692. }
  693. return _p->array[min_index];
  694. }
  695. Variant Array::max() const {
  696. int array_size = size();
  697. if (array_size == 0) {
  698. return Variant();
  699. }
  700. int max_index = 0;
  701. Variant is_greater;
  702. for (int i = 1; i < array_size; i++) {
  703. bool valid;
  704. Variant::evaluate(Variant::OP_GREATER, _p->array[i], _p->array[max_index], is_greater, valid);
  705. if (!valid) {
  706. return Variant(); //not a valid comparison
  707. }
  708. if (bool(is_greater)) {
  709. max_index = i;
  710. }
  711. }
  712. return _p->array[max_index];
  713. }
  714. const void *Array::id() const {
  715. return _p;
  716. }
  717. Array::Array(const Array &p_from, uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  718. _p = memnew(ArrayPrivate);
  719. _p->refcount.init();
  720. set_typed(p_type, p_class_name, p_script);
  721. assign(p_from);
  722. }
  723. void Array::set_typed(const ContainerType &p_element_type) {
  724. set_typed(p_element_type.builtin_type, p_element_type.class_name, p_element_type.script);
  725. }
  726. void Array::set_typed(uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  727. ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
  728. ERR_FAIL_COND_MSG(_p->array.size() > 0, "Type can only be set when array is empty.");
  729. ERR_FAIL_COND_MSG(_p->refcount.get() > 1, "Type can only be set when array has no more than one user.");
  730. ERR_FAIL_COND_MSG(_p->typed.type != Variant::NIL, "Type can only be set once.");
  731. ERR_FAIL_COND_MSG(p_class_name != StringName() && p_type != Variant::OBJECT, "Class names can only be set for type OBJECT");
  732. Ref<Script> script = p_script;
  733. ERR_FAIL_COND_MSG(script.is_valid() && p_class_name == StringName(), "Script class can only be set together with base class name");
  734. _p->typed.type = Variant::Type(p_type);
  735. _p->typed.class_name = p_class_name;
  736. _p->typed.script = script;
  737. _p->typed.where = "TypedArray";
  738. }
  739. bool Array::is_typed() const {
  740. return _p->typed.type != Variant::NIL;
  741. }
  742. bool Array::is_same_typed(const Array &p_other) const {
  743. return _p->typed == p_other._p->typed;
  744. }
  745. bool Array::is_same_instance(const Array &p_other) const {
  746. return _p == p_other._p;
  747. }
  748. ContainerType Array::get_element_type() const {
  749. ContainerType type;
  750. type.builtin_type = _p->typed.type;
  751. type.class_name = _p->typed.class_name;
  752. type.script = _p->typed.script;
  753. return type;
  754. }
  755. uint32_t Array::get_typed_builtin() const {
  756. return _p->typed.type;
  757. }
  758. StringName Array::get_typed_class_name() const {
  759. return _p->typed.class_name;
  760. }
  761. Variant Array::get_typed_script() const {
  762. return _p->typed.script;
  763. }
  764. Array Array::create_read_only() {
  765. Array array;
  766. array.make_read_only();
  767. return array;
  768. }
  769. void Array::make_read_only() {
  770. if (_p->read_only == nullptr) {
  771. _p->read_only = memnew(Variant);
  772. }
  773. }
  774. bool Array::is_read_only() const {
  775. return _p->read_only != nullptr;
  776. }
  777. Span<Variant> Array::span() const {
  778. return _p->array.span();
  779. }
  780. Array::Array(const Array &p_from) {
  781. _p = nullptr;
  782. _ref(p_from);
  783. }
  784. Array::Array(std::initializer_list<Variant> p_init) {
  785. _p = memnew(ArrayPrivate);
  786. _p->refcount.init();
  787. _p->array = Vector<Variant>(p_init);
  788. }
  789. Array::Array() {
  790. _p = memnew(ArrayPrivate);
  791. _p->refcount.init();
  792. }
  793. Array::~Array() {
  794. _unref();
  795. }