array.cpp 27 KB

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