array.cpp 27 KB

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