array.cpp 26 KB

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