array.cpp 27 KB

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