array.cpp 25 KB

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