array.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. /*************************************************************************/
  2. /* array.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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 "core/hashfuncs.h"
  32. #include "core/math/math_funcs.h"
  33. #include "core/object.h"
  34. #include "core/variant.h"
  35. #include "core/vector.h"
  36. class ArrayPrivate {
  37. public:
  38. SafeRefCount refcount;
  39. Vector<Variant> array;
  40. };
  41. void Array::_ref(const Array &p_from) const {
  42. ArrayPrivate *_fp = p_from._p;
  43. ERR_FAIL_COND(!_fp); // should NOT happen.
  44. if (_fp == _p) {
  45. return; // whatever it is, nothing to do here move along
  46. }
  47. bool success = _fp->refcount.ref();
  48. ERR_FAIL_COND(!success); // should really not happen either
  49. _unref();
  50. _p = p_from._p;
  51. }
  52. void Array::_unref() const {
  53. if (!_p) {
  54. return;
  55. }
  56. if (_p->refcount.unref()) {
  57. memdelete(_p);
  58. }
  59. _p = nullptr;
  60. }
  61. Variant &Array::operator[](int p_idx) {
  62. return _p->array.write[p_idx];
  63. }
  64. const Variant &Array::operator[](int p_idx) const {
  65. return _p->array[p_idx];
  66. }
  67. int Array::size() const {
  68. return _p->array.size();
  69. }
  70. bool Array::empty() const {
  71. return _p->array.empty();
  72. }
  73. void Array::clear() {
  74. _p->array.clear();
  75. }
  76. bool Array::deep_equal(const Array &p_array, int p_recursion_count) const {
  77. // Cheap checks
  78. ERR_FAIL_COND_V_MSG(p_recursion_count > MAX_RECURSION, true, "Max recursion reached");
  79. if (_p == p_array._p) {
  80. return true;
  81. }
  82. const Vector<Variant> &a1 = _p->array;
  83. const Vector<Variant> &a2 = p_array._p->array;
  84. const int size = a1.size();
  85. if (size != a2.size()) {
  86. return false;
  87. }
  88. // Heavy O(n) check
  89. p_recursion_count++;
  90. for (int i = 0; i < size; i++) {
  91. if (!a1[i].deep_equal(a2[i], p_recursion_count)) {
  92. return false;
  93. }
  94. }
  95. return true;
  96. }
  97. bool Array::operator==(const Array &p_array) const {
  98. return _p == p_array._p;
  99. }
  100. uint32_t Array::hash() const {
  101. uint32_t h = hash_djb2_one_32(0);
  102. for (int i = 0; i < _p->array.size(); i++) {
  103. h = hash_djb2_one_32(_p->array[i].hash(), h);
  104. }
  105. return h;
  106. }
  107. void Array::operator=(const Array &p_array) {
  108. _ref(p_array);
  109. }
  110. void Array::push_back(const Variant &p_value) {
  111. _p->array.push_back(p_value);
  112. }
  113. void Array::append_array(const Array &p_array) {
  114. _p->array.append_array(p_array._p->array);
  115. }
  116. Error Array::resize(int p_new_size) {
  117. return _p->array.resize(p_new_size);
  118. }
  119. void Array::insert(int p_pos, const Variant &p_value) {
  120. _p->array.insert(p_pos, p_value);
  121. }
  122. void Array::fill(const Variant &p_value) {
  123. _p->array.fill(p_value);
  124. }
  125. void Array::erase(const Variant &p_value) {
  126. _p->array.erase(p_value);
  127. }
  128. Variant Array::front() const {
  129. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  130. return operator[](0);
  131. }
  132. Variant Array::back() const {
  133. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  134. return operator[](_p->array.size() - 1);
  135. }
  136. int Array::find(const Variant &p_value, int p_from) const {
  137. return _p->array.find(p_value, p_from);
  138. }
  139. int Array::rfind(const Variant &p_value, int p_from) const {
  140. if (_p->array.size() == 0) {
  141. return -1;
  142. }
  143. if (p_from < 0) {
  144. // Relative offset from the end
  145. p_from = _p->array.size() + p_from;
  146. }
  147. if (p_from < 0 || p_from >= _p->array.size()) {
  148. // Limit to array boundaries
  149. p_from = _p->array.size() - 1;
  150. }
  151. for (int i = p_from; i >= 0; i--) {
  152. if (_p->array[i] == p_value) {
  153. return i;
  154. }
  155. }
  156. return -1;
  157. }
  158. int Array::find_last(const Variant &p_value) const {
  159. return rfind(p_value);
  160. }
  161. int Array::count(const Variant &p_value) const {
  162. if (_p->array.size() == 0) {
  163. return 0;
  164. }
  165. int amount = 0;
  166. for (int i = 0; i < _p->array.size(); i++) {
  167. if (_p->array[i] == p_value) {
  168. amount++;
  169. }
  170. }
  171. return amount;
  172. }
  173. bool Array::has(const Variant &p_value) const {
  174. return _p->array.find(p_value, 0) != -1;
  175. }
  176. void Array::remove(int p_pos) {
  177. _p->array.remove(p_pos);
  178. }
  179. void Array::set(int p_idx, const Variant &p_value) {
  180. operator[](p_idx) = p_value;
  181. }
  182. const Variant &Array::get(int p_idx) const {
  183. return operator[](p_idx);
  184. }
  185. Array Array::duplicate(bool p_deep) const {
  186. Array new_arr;
  187. int element_count = size();
  188. new_arr.resize(element_count);
  189. for (int i = 0; i < element_count; i++) {
  190. new_arr[i] = p_deep ? get(i).duplicate(p_deep) : get(i);
  191. }
  192. return new_arr;
  193. }
  194. int Array::_clamp_slice_index(int p_index) const {
  195. int arr_size = size();
  196. int fixed_index = CLAMP(p_index, -arr_size, arr_size - 1);
  197. if (fixed_index < 0) {
  198. fixed_index = arr_size + fixed_index;
  199. }
  200. return fixed_index;
  201. }
  202. Array Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const { // like python, but inclusive on upper bound
  203. Array new_arr;
  204. ERR_FAIL_COND_V_MSG(p_step == 0, new_arr, "Array slice step size cannot be zero.");
  205. if (empty()) { // Don't try to slice empty arrays.
  206. return new_arr;
  207. }
  208. if (p_step > 0) {
  209. if (p_begin >= size() || p_end < -size()) {
  210. return new_arr;
  211. }
  212. } else { // p_step < 0
  213. if (p_begin < -size() || p_end >= size()) {
  214. return new_arr;
  215. }
  216. }
  217. int begin = _clamp_slice_index(p_begin);
  218. int end = _clamp_slice_index(p_end);
  219. int new_arr_size = MAX(((end - begin + p_step) / p_step), 0);
  220. new_arr.resize(new_arr_size);
  221. if (p_step > 0) {
  222. int dest_idx = 0;
  223. for (int idx = begin; idx <= end; idx += p_step) {
  224. ERR_FAIL_COND_V_MSG(dest_idx < 0 || dest_idx >= new_arr_size, Array(), "Bug in Array slice()");
  225. new_arr[dest_idx++] = p_deep ? get(idx).duplicate(p_deep) : get(idx);
  226. }
  227. } else { // p_step < 0
  228. int dest_idx = 0;
  229. for (int idx = begin; idx >= end; idx += p_step) {
  230. ERR_FAIL_COND_V_MSG(dest_idx < 0 || dest_idx >= new_arr_size, Array(), "Bug in Array slice()");
  231. new_arr[dest_idx++] = p_deep ? get(idx).duplicate(p_deep) : get(idx);
  232. }
  233. }
  234. return new_arr;
  235. }
  236. struct _ArrayVariantSort {
  237. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  238. bool valid = false;
  239. Variant res;
  240. Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);
  241. if (!valid) {
  242. res = false;
  243. }
  244. return res;
  245. }
  246. };
  247. Array &Array::sort() {
  248. _p->array.sort_custom<_ArrayVariantSort>();
  249. return *this;
  250. }
  251. struct _ArrayVariantSortCustom {
  252. Object *obj;
  253. StringName func;
  254. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  255. const Variant *args[2] = { &p_l, &p_r };
  256. Variant::CallError err;
  257. bool res = obj->call(func, args, 2, err);
  258. if (err.error != Variant::CallError::CALL_OK) {
  259. res = false;
  260. }
  261. return res;
  262. }
  263. };
  264. Array &Array::sort_custom(Object *p_obj, const StringName &p_function) {
  265. ERR_FAIL_NULL_V(p_obj, *this);
  266. SortArray<Variant, _ArrayVariantSortCustom, true> avs;
  267. avs.compare.obj = p_obj;
  268. avs.compare.func = p_function;
  269. avs.sort(_p->array.ptrw(), _p->array.size());
  270. return *this;
  271. }
  272. void Array::shuffle() {
  273. const int n = _p->array.size();
  274. if (n < 2) {
  275. return;
  276. }
  277. Variant *data = _p->array.ptrw();
  278. for (int i = n - 1; i >= 1; i--) {
  279. const int j = Math::rand() % (i + 1);
  280. const Variant tmp = data[j];
  281. data[j] = data[i];
  282. data[i] = tmp;
  283. }
  284. }
  285. template <typename Less>
  286. _FORCE_INLINE_ int bisect(const Vector<Variant> &p_array, const Variant &p_value, bool p_before, const Less &p_less) {
  287. int lo = 0;
  288. int hi = p_array.size();
  289. if (p_before) {
  290. while (lo < hi) {
  291. const int mid = (lo + hi) / 2;
  292. if (p_less(p_array.get(mid), p_value)) {
  293. lo = mid + 1;
  294. } else {
  295. hi = mid;
  296. }
  297. }
  298. } else {
  299. while (lo < hi) {
  300. const int mid = (lo + hi) / 2;
  301. if (p_less(p_value, p_array.get(mid))) {
  302. hi = mid;
  303. } else {
  304. lo = mid + 1;
  305. }
  306. }
  307. }
  308. return lo;
  309. }
  310. int Array::bsearch(const Variant &p_value, bool p_before) {
  311. return bisect(_p->array, p_value, p_before, _ArrayVariantSort());
  312. }
  313. int Array::bsearch_custom(const Variant &p_value, Object *p_obj, const StringName &p_function, bool p_before) {
  314. ERR_FAIL_NULL_V(p_obj, 0);
  315. _ArrayVariantSortCustom less;
  316. less.obj = p_obj;
  317. less.func = p_function;
  318. return bisect(_p->array, p_value, p_before, less);
  319. }
  320. Array &Array::invert() {
  321. _p->array.invert();
  322. return *this;
  323. }
  324. void Array::push_front(const Variant &p_value) {
  325. _p->array.insert(0, p_value);
  326. }
  327. Variant Array::pop_back() {
  328. if (!_p->array.empty()) {
  329. const int n = _p->array.size() - 1;
  330. const Variant ret = _p->array.get(n);
  331. _p->array.resize(n);
  332. return ret;
  333. }
  334. return Variant();
  335. }
  336. Variant Array::pop_front() {
  337. if (!_p->array.empty()) {
  338. const Variant ret = _p->array.get(0);
  339. _p->array.remove(0);
  340. return ret;
  341. }
  342. return Variant();
  343. }
  344. Variant Array::pick_random() const {
  345. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  346. return operator[](Math::rand() % _p->array.size());
  347. }
  348. Variant Array::pop_at(int p_pos) {
  349. if (_p->array.empty()) {
  350. // Return `null` without printing an error to mimic `pop_back()` and `pop_front()` behavior.
  351. return Variant();
  352. }
  353. if (p_pos < 0) {
  354. // Relative offset from the end
  355. p_pos = _p->array.size() + p_pos;
  356. }
  357. ERR_FAIL_INDEX_V_MSG(
  358. p_pos,
  359. _p->array.size(),
  360. Variant(),
  361. vformat(
  362. "The calculated index %s is out of bounds (the array has %s elements). Leaving the array untouched and returning `null`.",
  363. p_pos,
  364. _p->array.size()));
  365. const Variant ret = _p->array.get(p_pos);
  366. _p->array.remove(p_pos);
  367. return ret;
  368. }
  369. Variant Array::min() const {
  370. Variant minval;
  371. for (int i = 0; i < size(); i++) {
  372. if (i == 0) {
  373. minval = get(i);
  374. } else {
  375. bool valid;
  376. Variant ret;
  377. Variant test = get(i);
  378. Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid);
  379. if (!valid) {
  380. return Variant(); //not a valid comparison
  381. }
  382. if (bool(ret)) {
  383. //is less
  384. minval = test;
  385. }
  386. }
  387. }
  388. return minval;
  389. }
  390. Variant Array::max() const {
  391. Variant maxval;
  392. for (int i = 0; i < size(); i++) {
  393. if (i == 0) {
  394. maxval = get(i);
  395. } else {
  396. bool valid;
  397. Variant ret;
  398. Variant test = get(i);
  399. Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);
  400. if (!valid) {
  401. return Variant(); //not a valid comparison
  402. }
  403. if (bool(ret)) {
  404. //is less
  405. maxval = test;
  406. }
  407. }
  408. }
  409. return maxval;
  410. }
  411. const void *Array::id() const {
  412. return _p;
  413. }
  414. Array::Array(const Array &p_from) {
  415. _p = nullptr;
  416. _ref(p_from);
  417. }
  418. Array::Array() {
  419. _p = memnew(ArrayPrivate);
  420. _p->refcount.init();
  421. }
  422. Array::~Array() {
  423. _unref();
  424. }