array.cpp 25 KB

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