array.cpp 27 KB

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