array.cpp 12 KB

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