array.cpp 26 KB

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