array.cpp 23 KB

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