array.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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 "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. return recursive_hash(0);
  102. }
  103. uint32_t Array::recursive_hash(int p_recursion_count) const {
  104. ERR_FAIL_COND_V_MSG(p_recursion_count > MAX_RECURSION, 0, "Max recursion reached");
  105. p_recursion_count++;
  106. uint32_t h = hash_djb2_one_32(0);
  107. for (int i = 0; i < _p->array.size(); i++) {
  108. h = hash_djb2_one_32(_p->array[i].recursive_hash(p_recursion_count), h);
  109. }
  110. return h;
  111. }
  112. void Array::operator=(const Array &p_array) {
  113. _ref(p_array);
  114. }
  115. void Array::push_back(const Variant &p_value) {
  116. _p->array.push_back(p_value);
  117. }
  118. void Array::append_array(const Array &p_array) {
  119. _p->array.append_array(p_array._p->array);
  120. }
  121. Error Array::resize(int p_new_size) {
  122. return _p->array.resize(p_new_size);
  123. }
  124. void Array::insert(int p_pos, const Variant &p_value) {
  125. _p->array.insert(p_pos, p_value);
  126. }
  127. void Array::fill(const Variant &p_value) {
  128. _p->array.fill(p_value);
  129. }
  130. void Array::erase(const Variant &p_value) {
  131. _p->array.erase(p_value);
  132. }
  133. Variant Array::front() const {
  134. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  135. return operator[](0);
  136. }
  137. Variant Array::back() const {
  138. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  139. return operator[](_p->array.size() - 1);
  140. }
  141. int Array::find(const Variant &p_value, int p_from) const {
  142. return _p->array.find(p_value, p_from);
  143. }
  144. int Array::rfind(const Variant &p_value, int p_from) const {
  145. if (_p->array.size() == 0) {
  146. return -1;
  147. }
  148. if (p_from < 0) {
  149. // Relative offset from the end
  150. p_from = _p->array.size() + p_from;
  151. }
  152. if (p_from < 0 || p_from >= _p->array.size()) {
  153. // Limit to array boundaries
  154. p_from = _p->array.size() - 1;
  155. }
  156. for (int i = p_from; i >= 0; i--) {
  157. if (_p->array[i] == p_value) {
  158. return i;
  159. }
  160. }
  161. return -1;
  162. }
  163. int Array::find_last(const Variant &p_value) const {
  164. return rfind(p_value);
  165. }
  166. int Array::count(const Variant &p_value) const {
  167. if (_p->array.size() == 0) {
  168. return 0;
  169. }
  170. int amount = 0;
  171. for (int i = 0; i < _p->array.size(); i++) {
  172. if (_p->array[i] == p_value) {
  173. amount++;
  174. }
  175. }
  176. return amount;
  177. }
  178. bool Array::has(const Variant &p_value) const {
  179. return _p->array.find(p_value, 0) != -1;
  180. }
  181. void Array::remove(int p_pos) {
  182. _p->array.remove(p_pos);
  183. }
  184. void Array::set(int p_idx, const Variant &p_value) {
  185. operator[](p_idx) = p_value;
  186. }
  187. const Variant &Array::get(int p_idx) const {
  188. return operator[](p_idx);
  189. }
  190. Array Array::duplicate(bool p_deep) const {
  191. Array new_arr;
  192. int element_count = size();
  193. new_arr.resize(element_count);
  194. for (int i = 0; i < element_count; i++) {
  195. new_arr[i] = p_deep ? get(i).duplicate(p_deep) : get(i);
  196. }
  197. return new_arr;
  198. }
  199. int Array::_clamp_slice_index(int p_index) const {
  200. int arr_size = size();
  201. int fixed_index = CLAMP(p_index, -arr_size, arr_size - 1);
  202. if (fixed_index < 0) {
  203. fixed_index = arr_size + fixed_index;
  204. }
  205. return fixed_index;
  206. }
  207. Array Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const { // like python, but inclusive on upper bound
  208. Array new_arr;
  209. ERR_FAIL_COND_V_MSG(p_step == 0, new_arr, "Array slice step size cannot be zero.");
  210. if (empty()) { // Don't try to slice empty arrays.
  211. return new_arr;
  212. }
  213. if (p_step > 0) {
  214. if (p_begin >= size() || p_end < -size()) {
  215. return new_arr;
  216. }
  217. } else { // p_step < 0
  218. if (p_begin < -size() || p_end >= size()) {
  219. return new_arr;
  220. }
  221. }
  222. int begin = _clamp_slice_index(p_begin);
  223. int end = _clamp_slice_index(p_end);
  224. int new_arr_size = MAX(((end - begin + p_step) / p_step), 0);
  225. new_arr.resize(new_arr_size);
  226. if (p_step > 0) {
  227. int dest_idx = 0;
  228. for (int idx = begin; idx <= end; idx += p_step) {
  229. ERR_FAIL_COND_V_MSG(dest_idx < 0 || dest_idx >= new_arr_size, Array(), "Bug in Array slice()");
  230. new_arr[dest_idx++] = p_deep ? get(idx).duplicate(p_deep) : get(idx);
  231. }
  232. } else { // p_step < 0
  233. int dest_idx = 0;
  234. for (int idx = begin; idx >= end; idx += p_step) {
  235. ERR_FAIL_COND_V_MSG(dest_idx < 0 || dest_idx >= new_arr_size, Array(), "Bug in Array slice()");
  236. new_arr[dest_idx++] = p_deep ? get(idx).duplicate(p_deep) : get(idx);
  237. }
  238. }
  239. return new_arr;
  240. }
  241. struct _ArrayVariantSort {
  242. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  243. bool valid = false;
  244. Variant res;
  245. Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);
  246. if (!valid) {
  247. res = false;
  248. }
  249. return res;
  250. }
  251. };
  252. Array &Array::sort() {
  253. _p->array.sort_custom<_ArrayVariantSort>();
  254. return *this;
  255. }
  256. struct _ArrayVariantSortCustom {
  257. Object *obj;
  258. StringName func;
  259. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  260. const Variant *args[2] = { &p_l, &p_r };
  261. Variant::CallError err;
  262. bool res = obj->call(func, args, 2, err);
  263. if (err.error != Variant::CallError::CALL_OK) {
  264. res = false;
  265. }
  266. return res;
  267. }
  268. };
  269. Array &Array::sort_custom(Object *p_obj, const StringName &p_function) {
  270. ERR_FAIL_NULL_V(p_obj, *this);
  271. SortArray<Variant, _ArrayVariantSortCustom, true> avs;
  272. avs.compare.obj = p_obj;
  273. avs.compare.func = p_function;
  274. avs.sort(_p->array.ptrw(), _p->array.size());
  275. return *this;
  276. }
  277. void Array::shuffle() {
  278. const int n = _p->array.size();
  279. if (n < 2) {
  280. return;
  281. }
  282. Variant *data = _p->array.ptrw();
  283. for (int i = n - 1; i >= 1; i--) {
  284. const int j = Math::rand() % (i + 1);
  285. const Variant tmp = data[j];
  286. data[j] = data[i];
  287. data[i] = tmp;
  288. }
  289. }
  290. template <typename Less>
  291. _FORCE_INLINE_ int bisect(const Vector<Variant> &p_array, const Variant &p_value, bool p_before, const Less &p_less) {
  292. int lo = 0;
  293. int hi = p_array.size();
  294. if (p_before) {
  295. while (lo < hi) {
  296. const int mid = (lo + hi) / 2;
  297. if (p_less(p_array.get(mid), p_value)) {
  298. lo = mid + 1;
  299. } else {
  300. hi = mid;
  301. }
  302. }
  303. } else {
  304. while (lo < hi) {
  305. const int mid = (lo + hi) / 2;
  306. if (p_less(p_value, p_array.get(mid))) {
  307. hi = mid;
  308. } else {
  309. lo = mid + 1;
  310. }
  311. }
  312. }
  313. return lo;
  314. }
  315. int Array::bsearch(const Variant &p_value, bool p_before) {
  316. return bisect(_p->array, p_value, p_before, _ArrayVariantSort());
  317. }
  318. int Array::bsearch_custom(const Variant &p_value, Object *p_obj, const StringName &p_function, bool p_before) {
  319. ERR_FAIL_NULL_V(p_obj, 0);
  320. _ArrayVariantSortCustom less;
  321. less.obj = p_obj;
  322. less.func = p_function;
  323. return bisect(_p->array, p_value, p_before, less);
  324. }
  325. Array &Array::invert() {
  326. _p->array.invert();
  327. return *this;
  328. }
  329. void Array::push_front(const Variant &p_value) {
  330. _p->array.insert(0, p_value);
  331. }
  332. Variant Array::pop_back() {
  333. if (!_p->array.empty()) {
  334. const int n = _p->array.size() - 1;
  335. const Variant ret = _p->array.get(n);
  336. _p->array.resize(n);
  337. return ret;
  338. }
  339. return Variant();
  340. }
  341. Variant Array::pop_front() {
  342. if (!_p->array.empty()) {
  343. const Variant ret = _p->array.get(0);
  344. _p->array.remove(0);
  345. return ret;
  346. }
  347. return Variant();
  348. }
  349. Variant Array::pick_random() const {
  350. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  351. return operator[](Math::rand() % _p->array.size());
  352. }
  353. Variant Array::pop_at(int p_pos) {
  354. if (_p->array.empty()) {
  355. // Return `null` without printing an error to mimic `pop_back()` and `pop_front()` behavior.
  356. return Variant();
  357. }
  358. if (p_pos < 0) {
  359. // Relative offset from the end
  360. p_pos = _p->array.size() + p_pos;
  361. }
  362. ERR_FAIL_INDEX_V_MSG(
  363. p_pos,
  364. _p->array.size(),
  365. Variant(),
  366. vformat(
  367. "The calculated index %s is out of bounds (the array has %s elements). Leaving the array untouched and returning `null`.",
  368. p_pos,
  369. _p->array.size()));
  370. const Variant ret = _p->array.get(p_pos);
  371. _p->array.remove(p_pos);
  372. return ret;
  373. }
  374. Variant Array::min() const {
  375. Variant minval;
  376. for (int i = 0; i < size(); i++) {
  377. if (i == 0) {
  378. minval = get(i);
  379. } else {
  380. bool valid;
  381. Variant ret;
  382. Variant test = get(i);
  383. Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid);
  384. if (!valid) {
  385. return Variant(); //not a valid comparison
  386. }
  387. if (bool(ret)) {
  388. //is less
  389. minval = test;
  390. }
  391. }
  392. }
  393. return minval;
  394. }
  395. Variant Array::max() const {
  396. Variant maxval;
  397. for (int i = 0; i < size(); i++) {
  398. if (i == 0) {
  399. maxval = get(i);
  400. } else {
  401. bool valid;
  402. Variant ret;
  403. Variant test = get(i);
  404. Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);
  405. if (!valid) {
  406. return Variant(); //not a valid comparison
  407. }
  408. if (bool(ret)) {
  409. //is less
  410. maxval = test;
  411. }
  412. }
  413. }
  414. return maxval;
  415. }
  416. const void *Array::id() const {
  417. return _p;
  418. }
  419. Array::Array(const Array &p_from) {
  420. _p = nullptr;
  421. _ref(p_from);
  422. }
  423. Array::Array() {
  424. _p = memnew(ArrayPrivate);
  425. _p->refcount.init();
  426. }
  427. Array::~Array() {
  428. _unref();
  429. }