1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/functional/bind.h"
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/allocator/partition_alloc_features.h"
#include "base/allocator/partition_alloc_support.h"
#include "base/allocator/partition_allocator/src/partition_alloc/dangling_raw_ptr_checks.h"
#include "base/allocator/partition_allocator/src/partition_alloc/partition_alloc_buildflags.h"
#include "base/allocator/partition_allocator/src/partition_alloc/partition_alloc_for_testing.h"
#include "base/allocator/partition_allocator/src/partition_alloc/partition_root.h"
#include "base/functional/callback.h"
#include "base/functional/disallow_unretained.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ref.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::ByMove;
using ::testing::Mock;
using ::testing::Return;
using ::testing::StrictMock;
namespace base {
namespace {
class AllowsUnretained {};
class BansUnretained {
public:
DISALLOW_UNRETAINED();
};
class BansUnretainedInPrivate {
DISALLOW_UNRETAINED();
};
class DerivedButBaseBansUnretained : public BansUnretained {};
static_assert(internal::TypeSupportsUnretainedV<AllowsUnretained>);
static_assert(!internal::TypeSupportsUnretainedV<BansUnretained>);
static_assert(!internal::TypeSupportsUnretainedV<BansUnretainedInPrivate>);
static_assert(!internal::TypeSupportsUnretainedV<DerivedButBaseBansUnretained>);
class NoRef {
public:
NoRef() = default;
NoRef(const NoRef&) = delete;
// Particularly important in this test to ensure no copies are made.
NoRef& operator=(const NoRef&) = delete;
MOCK_METHOD0(VoidMethod0, void());
MOCK_CONST_METHOD0(VoidConstMethod0, void());
MOCK_METHOD0(IntMethod0, int());
MOCK_CONST_METHOD0(IntConstMethod0, int());
MOCK_METHOD1(VoidMethodWithIntArg, void(int));
MOCK_METHOD0(UniquePtrMethod0, std::unique_ptr<int>());
};
class HasRef : public NoRef {
public:
HasRef() = default;
HasRef(const HasRef&) = delete;
// Particularly important in this test to ensure no copies are made.
HasRef& operator=(const HasRef&) = delete;
MOCK_CONST_METHOD0(AddRef, void());
MOCK_CONST_METHOD0(Release, bool());
MOCK_CONST_METHOD0(HasAtLeastOneRef, bool());
};
class HasRefPrivateDtor : public HasRef {
private:
~HasRefPrivateDtor() = default;
};
static const int kParentValue = 1;
static const int kChildValue = 2;
class Parent {
public:
void AddRef() const {}
void Release() const {}
bool HasAtLeastOneRef() const { return true; }
virtual void VirtualSet() { value = kParentValue; }
void NonVirtualSet() { value = kParentValue; }
int value;
};
class Child : public Parent {
public:
void VirtualSet() override { value = kChildValue; }
void NonVirtualSet() { value = kChildValue; }
};
class NoRefParent {
public:
virtual void VirtualSet() { value = kParentValue; }
void NonVirtualSet() { value = kParentValue; }
int value;
};
class NoRefChild : public NoRefParent {
void VirtualSet() override { value = kChildValue; }
void NonVirtualSet() { value = kChildValue; }
};
// Used for probing the number of copies and moves that occur if a type must be
// coerced during argument forwarding in the Run() methods.
struct DerivedCopyMoveCounter {
DerivedCopyMoveCounter(int* copies,
int* assigns,
int* move_constructs,
int* move_assigns)
: copies_(copies),
assigns_(assigns),
move_constructs_(move_constructs),
move_assigns_(move_assigns) {}
raw_ptr<int> copies_;
raw_ptr<int> assigns_;
raw_ptr<int> move_constructs_;
raw_ptr<int> move_assigns_;
};
// Used for probing the number of copies and moves in an argument.
class CopyMoveCounter {
public:
CopyMoveCounter(int* copies,
int* assigns,
int* move_constructs,
int* move_assigns)
: copies_(copies),
assigns_(assigns),
move_constructs_(move_constructs),
move_assigns_(move_assigns) {}
CopyMoveCounter(const CopyMoveCounter& other)
: copies_(other.copies_),
assigns_(other.assigns_),
move_constructs_(other.move_constructs_),
move_assigns_(other.move_assigns_) {
(*copies_)++;
}
CopyMoveCounter(CopyMoveCounter&& other)
: copies_(other.copies_),
assigns_(other.assigns_),
move_constructs_(other.move_constructs_),
move_assigns_(other.move_assigns_) {
(*move_constructs_)++;
}
// Probing for copies from coercion.
explicit CopyMoveCounter(const DerivedCopyMoveCounter& other)
: copies_(other.copies_),
assigns_(other.assigns_),
move_constructs_(other.move_constructs_),
move_assigns_(other.move_assigns_) {
(*copies_)++;
}
// Probing for moves from coercion.
explicit CopyMoveCounter(DerivedCopyMoveCounter&& other)
: copies_(other.copies_),
assigns_(other.assigns_),
move_constructs_(other.move_constructs_),
move_assigns_(other.move_assigns_) {
(*move_constructs_)++;
}
const CopyMoveCounter& operator=(const CopyMoveCounter& rhs) {
copies_ = rhs.copies_;
assigns_ = rhs.assigns_;
move_constructs_ = rhs.move_constructs_;
move_assigns_ = rhs.move_assigns_;
(*assigns_)++;
return *this;
}
const CopyMoveCounter& operator=(CopyMoveCounter&& rhs) {
copies_ = rhs.copies_;
assigns_ = rhs.assigns_;
move_constructs_ = rhs.move_constructs_;
move_assigns_ = rhs.move_assigns_;
(*move_assigns_)++;
return *this;
}
int copies() const { return *copies_; }
private:
raw_ptr<int> copies_;
raw_ptr<int> assigns_;
raw_ptr<int> move_constructs_;
raw_ptr<int> move_assigns_;
};
// Used for probing the number of copies in an argument. The instance is a
// copyable and non-movable type.
class CopyCounter {
public:
CopyCounter(int* copies, int* assigns)
: counter_(copies, assigns, nullptr, nullptr) {}
CopyCounter(const CopyCounter& other) = default;
CopyCounter& operator=(const CopyCounter& other) = default;
explicit CopyCounter(const DerivedCopyMoveCounter& other) : counter_(other) {}
int copies() const { return counter_.copies(); }
private:
CopyMoveCounter counter_;
};
// Used for probing the number of moves in an argument. The instance is a
// non-copyable and movable type.
class MoveCounter {
public:
MoveCounter(int* move_constructs, int* move_assigns)
: counter_(nullptr, nullptr, move_constructs, move_assigns) {}
MoveCounter(MoveCounter&& other) : counter_(std::move(other.counter_)) {}
MoveCounter& operator=(MoveCounter&& other) {
counter_ = std::move(other.counter_);
return *this;
}
explicit MoveCounter(DerivedCopyMoveCounter&& other)
: counter_(std::move(other)) {}
private:
CopyMoveCounter counter_;
};
class DeleteCounter {
public:
explicit DeleteCounter(int* deletes) : deletes_(deletes) {}
~DeleteCounter() { (*deletes_)++; }
void VoidMethod0() {}
private:
raw_ptr<int> deletes_;
};
template <typename T>
T PassThru(T scoper) {
return scoper;
}
// Some test functions that we can Bind to.
template <typename T>
T PolymorphicIdentity(T t) {
return t;
}
template <typename... Ts>
struct VoidPolymorphic {
static void Run(Ts... t) {}
};
int Identity(int n) {
return n;
}
int ArrayGet(const int array[], int n) {
return array[n];
}
int Sum(int a, int b, int c, int d, int e, int f) {
return a + b + c + d + e + f;
}
const char* CStringIdentity(const char* s) {
return s;
}
int GetCopies(const CopyMoveCounter& counter) {
return counter.copies();
}
int UnwrapNoRefParent(NoRefParent p) {
return p.value;
}
int UnwrapNoRefParentPtr(NoRefParent* p) {
return p->value;
}
int UnwrapNoRefParentConstRef(const NoRefParent& p) {
return p.value;
}
void RefArgSet(int& n) {
n = 2;
}
void PtrArgSet(int* n) {
*n = 2;
}
int FunctionWithWeakFirstParam(WeakPtr<NoRef> o, int n) {
return n;
}
int FunctionWithScopedRefptrFirstParam(const scoped_refptr<HasRef>& o, int n) {
return n;
}
void TakesACallback(const RepeatingClosure& callback) {
callback.Run();
}
int Noexcept() noexcept {
return 42;
}
class NoexceptFunctor {
public:
int operator()() noexcept { return 42; }
};
class ConstNoexceptFunctor {
public:
int operator()() noexcept { return 42; }
};
class BindTest : public ::testing::Test {
public:
BindTest() {
const_has_ref_ptr_ = &has_ref_;
const_no_ref_ptr_ = &no_ref_;
static_func_mock_ptr = &static_func_mock_;
}
BindTest(const BindTest&) = delete;
BindTest& operator=(const BindTest&) = delete;
~BindTest() override = default;
static void VoidFunc0() { static_func_mock_ptr->VoidMethod0(); }
static int IntFunc0() { return static_func_mock_ptr->IntMethod0(); }
int NoexceptMethod() noexcept { return 42; }
int ConstNoexceptMethod() const noexcept { return 42; }
protected:
StrictMock<NoRef> no_ref_;
StrictMock<HasRef> has_ref_;
raw_ptr<const HasRef> const_has_ref_ptr_;
raw_ptr<const NoRef> const_no_ref_ptr_;
StrictMock<NoRef> static_func_mock_;
// Used by the static functions to perform expectations.
static StrictMock<NoRef>* static_func_mock_ptr;
};
StrictMock<NoRef>* BindTest::static_func_mock_ptr;
StrictMock<NoRef>* g_func_mock_ptr;
void VoidFunc0() {
g_func_mock_ptr->VoidMethod0();
}
int IntFunc0() {
return g_func_mock_ptr->IntMethod0();
}
TEST_F(BindTest, BasicTest) {
RepeatingCallback<int(int, int, int)> cb = BindRepeating(&Sum, 32, 16, 8);
EXPECT_EQ(92, cb.Run(13, 12, 11));
RepeatingCallback<int(int, int, int, int, int, int)> c1 = BindRepeating(&Sum);
EXPECT_EQ(69, c1.Run(14, 13, 12, 11, 10, 9));
RepeatingCallback<int(int, int, int)> c2 = BindRepeating(c1, 32, 16, 8);
EXPECT_EQ(86, c2.Run(11, 10, 9));
RepeatingCallback<int()> c3 = BindRepeating(c2, 4, 2, 1);
EXPECT_EQ(63, c3.Run());
}
// Test that currying the rvalue result of another BindRepeating() works
// correctly.
// - rvalue should be usable as argument to BindRepeating().
// - multiple runs of resulting RepeatingCallback remain valid.
TEST_F(BindTest, CurryingRvalueResultOfBind) {
int n = 0;
RepeatingClosure cb =
BindRepeating(&TakesACallback, BindRepeating(&PtrArgSet, &n));
// If we implement BindRepeating() such that the return value has
// auto_ptr-like semantics, the second call here will fail because ownership
// of the internal BindState<> would have been transferred to a *temporary*
// construction of a RepeatingCallback object on the first call.
cb.Run();
EXPECT_EQ(2, n);
n = 0;
cb.Run();
EXPECT_EQ(2, n);
}
TEST_F(BindTest, RepeatingCallbackBasicTest) {
RepeatingCallback<int(int)> c0 = BindRepeating(&Sum, 1, 2, 4, 8, 16);
// RepeatingCallback can run via a lvalue-reference.
EXPECT_EQ(63, c0.Run(32));
// It is valid to call a RepeatingCallback more than once.
EXPECT_EQ(54, c0.Run(23));
// BindRepeating can handle a RepeatingCallback as the target functor.
RepeatingCallback<int()> c1 = BindRepeating(c0, 11);
// RepeatingCallback can run via a rvalue-reference.
EXPECT_EQ(42, std::move(c1).Run());
// BindRepeating can handle a rvalue-reference of RepeatingCallback.
EXPECT_EQ(32, BindRepeating(std::move(c0), 1).Run());
}
TEST_F(BindTest, OnceCallbackBasicTest) {
OnceCallback<int(int)> c0 = BindOnce(&Sum, 1, 2, 4, 8, 16);
// OnceCallback can run via a rvalue-reference.
EXPECT_EQ(63, std::move(c0).Run(32));
// After running via the rvalue-reference, the value of the OnceCallback
// is undefined. The implementation simply clears the instance after the
// invocation.
EXPECT_TRUE(c0.is_null());
c0 = BindOnce(&Sum, 2, 3, 5, 7, 11);
// BindOnce can handle a rvalue-reference of OnceCallback as the target
// functor.
OnceCallback<int()> c1 = BindOnce(std::move(c0), 13);
EXPECT_EQ(41, std::move(c1).Run());
RepeatingCallback<int(int)> c2 = BindRepeating(&Sum, 2, 3, 5, 7, 11);
EXPECT_EQ(41, BindOnce(c2, 13).Run());
}
// IgnoreResult adapter test.
// - Function with return value.
// - Method with return value.
// - Const Method with return.
// - Method with return value bound to WeakPtr<>.
// - Const Method with return bound to WeakPtr<>.
TEST_F(BindTest, IgnoreResultForRepeating) {
EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
EXPECT_CALL(has_ref_, AddRef()).Times(2);
EXPECT_CALL(has_ref_, Release()).Times(2);
EXPECT_CALL(has_ref_, HasAtLeastOneRef()).WillRepeatedly(Return(true));
EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(10));
EXPECT_CALL(has_ref_, IntConstMethod0()).WillOnce(Return(11));
EXPECT_CALL(no_ref_, IntMethod0()).WillOnce(Return(12));
EXPECT_CALL(no_ref_, IntConstMethod0()).WillOnce(Return(13));
RepeatingClosure normal_func_cb = BindRepeating(IgnoreResult(&IntFunc0));
normal_func_cb.Run();
RepeatingClosure non_void_method_cb =
BindRepeating(IgnoreResult(&HasRef::IntMethod0), &has_ref_);
non_void_method_cb.Run();
RepeatingClosure non_void_const_method_cb =
BindRepeating(IgnoreResult(&HasRef::IntConstMethod0), &has_ref_);
non_void_const_method_cb.Run();
WeakPtrFactory<NoRef> weak_factory(&no_ref_);
WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_.get());
RepeatingClosure non_void_weak_method_cb = BindRepeating(
IgnoreResult(&NoRef::IntMethod0), weak_factory.GetWeakPtr());
non_void_weak_method_cb.Run();
RepeatingClosure non_void_weak_const_method_cb = BindRepeating(
IgnoreResult(&NoRef::IntConstMethod0), weak_factory.GetWeakPtr());
non_void_weak_const_method_cb.Run();
weak_factory.InvalidateWeakPtrs();
non_void_weak_const_method_cb.Run();
non_void_weak_method_cb.Run();
}
TEST_F(BindTest, IgnoreResultForOnce) {
EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
EXPECT_CALL(has_ref_, AddRef()).Times(2);
EXPECT_CALL(has_ref_, Release()).Times(2);
EXPECT_CALL(has_ref_, HasAtLeastOneRef()).WillRepeatedly(Return(true));
EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(10));
EXPECT_CALL(has_ref_, IntConstMethod0()).WillOnce(Return(11));
OnceClosure normal_func_cb = BindOnce(IgnoreResult(&IntFunc0));
std::move(normal_func_cb).Run();
OnceClosure non_void_method_cb =
BindOnce(IgnoreResult(&HasRef::IntMethod0), &has_ref_);
std::move(non_void_method_cb).Run();
OnceClosure non_void_const_method_cb =
BindOnce(IgnoreResult(&HasRef::IntConstMethod0), &has_ref_);
std::move(non_void_const_method_cb).Run();
WeakPtrFactory<NoRef> weak_factory(&no_ref_);
WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_.get());
OnceClosure non_void_weak_method_cb =
BindOnce(IgnoreResult(&NoRef::IntMethod0), weak_factory.GetWeakPtr());
OnceClosure non_void_weak_const_method_cb = BindOnce(
IgnoreResult(&NoRef::IntConstMethod0), weak_factory.GetWeakPtr());
weak_factory.InvalidateWeakPtrs();
std::move(non_void_weak_const_method_cb).Run();
std::move(non_void_weak_method_cb).Run();
}
TEST_F(BindTest, IgnoreResultForRepeatingCallback) {
std::string s;
RepeatingCallback<int(int)> cb = BindRepeating(
[](std::string* s, int i) {
*s += "Run" + base::NumberToString(i);
return 5;
},
&s);
RepeatingCallback<void(int)> noreturn = BindRepeating(IgnoreResult(cb));
noreturn.Run(2);
EXPECT_EQ(s, "Run2");
}
TEST_F(BindTest, IgnoreResultForOnceCallback) {
std::string s;
OnceCallback<int(int)> cb = BindOnce(
[](std::string* s, int i) {
*s += "Run" + base::NumberToString(i);
return 5;
},
&s);
OnceCallback<void(int)> noreturn = BindOnce(IgnoreResult(std::move(cb)));
std::move(noreturn).Run(2);
EXPECT_EQ(s, "Run2");
}
void SetFromRef(int& ref) {
EXPECT_EQ(ref, 1);
ref = 2;
EXPECT_EQ(ref, 2);
}
TEST_F(BindTest, BindOnceWithNonConstRef) {
int v = 1;
// Mutates `v` because it's not bound to callback instead it's forwarded by
// Run().
auto cb1 = BindOnce(SetFromRef);
std::move(cb1).Run(v);
EXPECT_EQ(v, 2);
v = 1;
// Mutates `v` through std::reference_wrapper bound to callback.
auto cb2 = BindOnce(SetFromRef, std::ref(v));
std::move(cb2).Run();
EXPECT_EQ(v, 2);
v = 1;
// Everything past here following will make a copy of the argument. The copy
// will be mutated and leave `v` unmodified.
auto cb3 = BindOnce(SetFromRef, base::OwnedRef(v));
std::move(cb3).Run();
EXPECT_EQ(v, 1);
int& ref = v;
auto cb4 = BindOnce(SetFromRef, base::OwnedRef(ref));
std::move(cb4).Run();
EXPECT_EQ(v, 1);
const int cv = 1;
auto cb5 = BindOnce(SetFromRef, base::OwnedRef(cv));
std::move(cb5).Run();
EXPECT_EQ(cv, 1);
const int& cref = v;
auto cb6 = BindOnce(SetFromRef, base::OwnedRef(cref));
std::move(cb6).Run();
EXPECT_EQ(cref, 1);
auto cb7 = BindOnce(SetFromRef, base::OwnedRef(1));
std::move(cb7).Run();
}
TEST_F(BindTest, BindRepeatingWithNonConstRef) {
int v = 1;
// Mutates `v` because it's not bound to callback instead it's forwarded by
// Run().
auto cb1 = BindRepeating(SetFromRef);
std::move(cb1).Run(v);
EXPECT_EQ(v, 2);
v = 1;
// Mutates `v` through std::reference_wrapper bound to callback.
auto cb2 = BindRepeating(SetFromRef, std::ref(v));
std::move(cb2).Run();
EXPECT_EQ(v, 2);
v = 1;
// Everything past here following will make a copy of the argument. The copy
// will be mutated and leave `v` unmodified.
auto cb3 = BindRepeating(SetFromRef, base::OwnedRef(v));
std::move(cb3).Run();
EXPECT_EQ(v, 1);
int& ref = v;
auto cb4 = BindRepeating(SetFromRef, base::OwnedRef(ref));
std::move(cb4).Run();
EXPECT_EQ(v, 1);
const int cv = 1;
auto cb5 = BindRepeating(SetFromRef, base::OwnedRef(cv));
std::move(cb5).Run();
EXPECT_EQ(cv, 1);
const int& cref = v;
auto cb6 = BindRepeating(SetFromRef, base::OwnedRef(cref));
std::move(cb6).Run();
EXPECT_EQ(cref, 1);
auto cb7 = BindRepeating(SetFromRef, base::OwnedRef(1));
std::move(cb7).Run();
}
// Functions that take reference parameters.
// - Forced reference parameter type still stores a copy.
// - Forced const reference parameter type still stores a copy.
TEST_F(BindTest, ReferenceArgumentBindingForRepeating) {
int n = 1;
int& ref_n = n;
const int& const_ref_n = n;
RepeatingCallback<int()> ref_copies_cb = BindRepeating(&Identity, ref_n);
EXPECT_EQ(n, ref_copies_cb.Run());
n++;
EXPECT_EQ(n - 1, ref_copies_cb.Run());
RepeatingCallback<int()> const_ref_copies_cb =
BindRepeating(&Identity, const_ref_n);
EXPECT_EQ(n, const_ref_copies_cb.Run());
n++;
EXPECT_EQ(n - 1, const_ref_copies_cb.Run());
}
TEST_F(BindTest, ReferenceArgumentBindingForOnce) {
int n = 1;
int& ref_n = n;
const int& const_ref_n = n;
OnceCallback<int()> ref_copies_cb = BindOnce(&Identity, ref_n);
n++;
EXPECT_EQ(n - 1, std::move(ref_copies_cb).Run());
OnceCallback<int()> const_ref_copies_cb = BindOnce(&Identity, const_ref_n);
n++;
EXPECT_EQ(n - 1, std::move(const_ref_copies_cb).Run());
}
// Check that we can pass in arrays and have them be stored as a pointer.
// - Array of values stores a pointer.
// - Array of const values stores a pointer.
TEST_F(BindTest, ArrayArgumentBindingForRepeating) {
int array[4] = {1, 1, 1, 1};
const int(*const_array_ptr)[4] = &array;
RepeatingCallback<int()> array_cb = BindRepeating(&ArrayGet, array, 1);
EXPECT_EQ(1, array_cb.Run());
RepeatingCallback<int()> const_array_cb =
BindRepeating(&ArrayGet, *const_array_ptr, 1);
EXPECT_EQ(1, const_array_cb.Run());
array[1] = 3;
EXPECT_EQ(3, array_cb.Run());
EXPECT_EQ(3, const_array_cb.Run());
}
TEST_F(BindTest, ArrayArgumentBindingForOnce) {
int array[4] = {1, 1, 1, 1};
const int(*const_array_ptr)[4] = &array;
OnceCallback<int()> array_cb = BindOnce(&ArrayGet, array, 1);
OnceCallback<int()> const_array_cb = BindOnce(&ArrayGet, *const_array_ptr, 1);
array[1] = 3;
EXPECT_EQ(3, std::move(array_cb).Run());
EXPECT_EQ(3, std::move(const_array_cb).Run());
}
// WeakPtr() support.
// - Method bound to WeakPtr<> to non-const object.
// - Const method bound to WeakPtr<> to non-const object.
// - Const method bound to WeakPtr<> to const object.
// - Normal Function with WeakPtr<> as P1 can have return type and is
// not canceled.
TEST_F(BindTest, WeakPtrForRepeating) {
EXPECT_CALL(no_ref_, VoidMethod0());
EXPECT_CALL(no_ref_, VoidConstMethod0()).Times(2);
WeakPtrFactory<NoRef> weak_factory(&no_ref_);
WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_.get());
RepeatingClosure method_cb =
BindRepeating(&NoRef::VoidMethod0, weak_factory.GetWeakPtr());
method_cb.Run();
RepeatingClosure const_method_cb =
BindRepeating(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
const_method_cb.Run();
RepeatingClosure const_method_const_ptr_cb =
BindRepeating(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
const_method_const_ptr_cb.Run();
RepeatingCallback<int(int)> normal_func_cb =
BindRepeating(&FunctionWithWeakFirstParam, weak_factory.GetWeakPtr());
EXPECT_EQ(1, normal_func_cb.Run(1));
weak_factory.InvalidateWeakPtrs();
const_weak_factory.InvalidateWeakPtrs();
method_cb.Run();
const_method_cb.Run();
const_method_const_ptr_cb.Run();
// Still runs even after the pointers are invalidated.
EXPECT_EQ(2, normal_func_cb.Run(2));
}
TEST_F(BindTest, WeakPtrForOnce) {
WeakPtrFactory<NoRef> weak_factory(&no_ref_);
WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_.get());
OnceClosure method_cb =
BindOnce(&NoRef::VoidMethod0, weak_factory.GetWeakPtr());
OnceClosure const_method_cb =
BindOnce(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
OnceClosure const_method_const_ptr_cb =
BindOnce(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
OnceCallback<int(int)> normal_func_cb =
BindOnce(&FunctionWithWeakFirstParam, weak_factory.GetWeakPtr());
weak_factory.InvalidateWeakPtrs();
const_weak_factory.InvalidateWeakPtrs();
std::move(method_cb).Run();
std::move(const_method_cb).Run();
std::move(const_method_const_ptr_cb).Run();
// Still runs even after the pointers are invalidated.
EXPECT_EQ(2, std::move(normal_func_cb).Run(2));
}
// std::cref() wrapper support.
// - Binding w/o std::cref takes a copy.
// - Binding a std::cref takes a reference.
// - Binding std::cref to a function std::cref does not copy on invoke.
TEST_F(BindTest, StdCrefForRepeating) {
int n = 1;
RepeatingCallback<int()> copy_cb = BindRepeating(&Identity, n);
RepeatingCallback<int()> const_ref_cb =
BindRepeating(&Identity, std::cref(n));
EXPECT_EQ(n, copy_cb.Run());
EXPECT_EQ(n, const_ref_cb.Run());
n++;
EXPECT_EQ(n - 1, copy_cb.Run());
EXPECT_EQ(n, const_ref_cb.Run());
int copies = 0;
int assigns = 0;
int move_constructs = 0;
int move_assigns = 0;
CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
RepeatingCallback<int()> all_const_ref_cb =
BindRepeating(&GetCopies, std::cref(counter));
EXPECT_EQ(0, all_const_ref_cb.Run());
EXPECT_EQ(0, copies);
EXPECT_EQ(0, assigns);
EXPECT_EQ(0, move_constructs);
EXPECT_EQ(0, move_assigns);
}
TEST_F(BindTest, StdCrefForOnce) {
int n = 1;
OnceCallback<int()> copy_cb = BindOnce(&Identity, n);
OnceCallback<int()> const_ref_cb = BindOnce(&Identity, std::cref(n));
n++;
EXPECT_EQ(n - 1, std::move(copy_cb).Run());
EXPECT_EQ(n, std::move(const_ref_cb).Run());
int copies = 0;
int assigns = 0;
int move_constructs = 0;
int move_assigns = 0;
CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
OnceCallback<int()> all_const_ref_cb =
BindOnce(&GetCopies, std::cref(counter));
EXPECT_EQ(0, std::move(all_const_ref_cb).Run());
EXPECT_EQ(0, copies);
EXPECT_EQ(0, assigns);
EXPECT_EQ(0, move_constructs);
EXPECT_EQ(0, move_assigns);
}
// Test Owned() support.
TEST_F(BindTest, OwnedForRepeatingRawPtr) {
int deletes = 0;
DeleteCounter* counter = new DeleteCounter(&deletes);
// If we don't capture, delete happens on Callback destruction/reset.
// return the same value.
RepeatingCallback<DeleteCounter*()> no_capture_cb =
BindRepeating(&PolymorphicIdentity<DeleteCounter*>, Owned(counter));
ASSERT_EQ(counter, no_capture_cb.Run());
ASSERT_EQ(counter, no_capture_cb.Run());
EXPECT_EQ(0, deletes);
no_capture_cb.Reset(); // This should trigger a delete.
EXPECT_EQ(1, deletes);
deletes = 0;
counter = new DeleteCounter(&deletes);
RepeatingClosure own_object_cb =
BindRepeating(&DeleteCounter::VoidMethod0, Owned(counter));
own_object_cb.Run();
EXPECT_EQ(0, deletes);
own_object_cb.Reset();
EXPECT_EQ(1, deletes);
}
TEST_F(BindTest, OwnedForOnceRawPtr) {
int deletes = 0;
DeleteCounter* counter = new DeleteCounter(&deletes);
// If we don't capture, delete happens on Callback destruction/reset.
// return the same value.
OnceCallback<DeleteCounter*()> no_capture_cb =
BindOnce(&PolymorphicIdentity<DeleteCounter*>, Owned(counter));
EXPECT_EQ(0, deletes);
no_capture_cb.Reset(); // This should trigger a delete.
EXPECT_EQ(1, deletes);
deletes = 0;
counter = new DeleteCounter(&deletes);
OnceClosure own_object_cb =
BindOnce(&DeleteCounter::VoidMethod0, Owned(counter));
EXPECT_EQ(0, deletes);
own_object_cb.Reset();
EXPECT_EQ(1, deletes);
}
TEST_F(BindTest, OwnedForRepeatingUniquePtr) {
int deletes = 0;
auto counter = std::make_unique<DeleteCounter>(&deletes);
DeleteCounter* raw_counter = counter.get();
// If we don't capture, delete happens on Callback destruction/reset.
// return the same value.
RepeatingCallback<DeleteCounter*()> no_capture_cb = BindRepeating(
&PolymorphicIdentity<DeleteCounter*>, Owned(std::move(counter)));
ASSERT_EQ(raw_counter, no_capture_cb.Run());
ASSERT_EQ(raw_counter, no_capture_cb.Run());
EXPECT_EQ(0, deletes);
no_capture_cb.Reset(); // This should trigger a delete.
EXPECT_EQ(1, deletes);
deletes = 0;
counter = std::make_unique<DeleteCounter>(&deletes);
RepeatingClosure own_object_cb =
BindRepeating(&DeleteCounter::VoidMethod0, Owned(std::move(counter)));
own_object_cb.Run();
EXPECT_EQ(0, deletes);
own_object_cb.Reset();
EXPECT_EQ(1, deletes);
}
TEST_F(BindTest, OwnedForOnceUniquePtr) {
int deletes = 0;
auto counter = std::make_unique<DeleteCounter>(&deletes);
// If we don't capture, delete happens on Callback destruction/reset.
// return the same value.
OnceCallback<DeleteCounter*()> no_capture_cb =
BindOnce(&PolymorphicIdentity<DeleteCounter*>, Owned(std::move(counter)));
EXPECT_EQ(0, deletes);
no_capture_cb.Reset(); // This should trigger a delete.
EXPECT_EQ(1, deletes);
deletes = 0;
counter = std::make_unique<DeleteCounter>(&deletes);
OnceClosure own_object_cb =
BindOnce(&DeleteCounter::VoidMethod0, Owned(std::move(counter)));
EXPECT_EQ(0, deletes);
own_object_cb.Reset();
EXPECT_EQ(1, deletes);
}
// Tests OwnedRef
TEST_F(BindTest, OwnedRefForCounter) {
int counter = 0;
RepeatingCallback<int()> counter_callback =
BindRepeating([](int& counter) { return ++counter; }, OwnedRef(counter));
EXPECT_EQ(1, counter_callback.Run());
EXPECT_EQ(2, counter_callback.Run());
EXPECT_EQ(3, counter_callback.Run());
EXPECT_EQ(4, counter_callback.Run());
EXPECT_EQ(0, counter); // counter should remain unchanged.
}
TEST_F(BindTest, OwnedRefForIgnoringArguments) {
OnceCallback<std::string(std::string)> echo_callback =
BindOnce([](int& ignore, std::string s) { return s; }, OwnedRef(0));
EXPECT_EQ("Hello World", std::move(echo_callback).Run("Hello World"));
}
template <typename T>
class BindVariantsTest : public ::testing::Test {};
struct RepeatingTestConfig {
template <typename Signature>
using CallbackType = RepeatingCallback<Signature>;
using ClosureType = RepeatingClosure;
template <typename F, typename... Args>
static CallbackType<internal::MakeUnboundRunType<F, Args...>> Bind(
F&& f,
Args&&... args) {
return BindRepeating(std::forward<F>(f), std::forward<Args>(args)...);
}
};
struct OnceTestConfig {
template <typename Signature>
using CallbackType = OnceCallback<Signature>;
using ClosureType = OnceClosure;
template <typename F, typename... Args>
static CallbackType<internal::MakeUnboundRunType<F, Args...>> Bind(
F&& f,
Args&&... args) {
return BindOnce(std::forward<F>(f), std::forward<Args>(args)...);
}
};
using BindVariantsTestConfig =
::testing::Types<RepeatingTestConfig, OnceTestConfig>;
TYPED_TEST_SUITE(BindVariantsTest, BindVariantsTestConfig);
template <typename TypeParam, typename Signature>
using CallbackType = typename TypeParam::template CallbackType<Signature>;
// Function type support.
// - Normal function.
// - Normal function bound with non-refcounted first argument.
// - Method bound to non-const object.
// - Method bound to scoped_refptr.
// - Const method bound to non-const object.
// - Const method bound to const object.
// - Derived classes can be used with pointers to non-virtual base functions.
// - Derived classes can be used with pointers to virtual base functions (and
// preserve virtual dispatch).
TYPED_TEST(BindVariantsTest, FunctionTypeSupport) {
using ClosureType = typename TypeParam::ClosureType;
StrictMock<HasRef> has_ref;
StrictMock<NoRef> no_ref;
StrictMock<NoRef> static_func_mock;
const HasRef* const_has_ref_ptr = &has_ref;
g_func_mock_ptr = &static_func_mock;
EXPECT_CALL(static_func_mock, VoidMethod0());
EXPECT_CALL(has_ref, AddRef()).Times(4);
EXPECT_CALL(has_ref, Release()).Times(4);
EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
EXPECT_CALL(has_ref, VoidMethod0()).Times(2);
EXPECT_CALL(has_ref, VoidConstMethod0()).Times(2);
ClosureType normal_cb = TypeParam::Bind(&VoidFunc0);
CallbackType<TypeParam, NoRef*()> normal_non_refcounted_cb =
TypeParam::Bind(&PolymorphicIdentity<NoRef*>, &no_ref);
std::move(normal_cb).Run();
EXPECT_EQ(&no_ref, std::move(normal_non_refcounted_cb).Run());
ClosureType method_cb = TypeParam::Bind(&HasRef::VoidMethod0, &has_ref);
ClosureType method_refptr_cb =
TypeParam::Bind(&HasRef::VoidMethod0, WrapRefCounted(&has_ref));
ClosureType const_method_nonconst_obj_cb =
TypeParam::Bind(&HasRef::VoidConstMethod0, &has_ref);
ClosureType const_method_const_obj_cb =
TypeParam::Bind(&HasRef::VoidConstMethod0, const_has_ref_ptr);
std::move(method_cb).Run();
std::move(method_refptr_cb).Run();
std::move(const_method_nonconst_obj_cb).Run();
std::move(const_method_const_obj_cb).Run();
Child child;
child.value = 0;
ClosureType virtual_set_cb = TypeParam::Bind(&Parent::VirtualSet, &child);
std::move(virtual_set_cb).Run();
EXPECT_EQ(kChildValue, child.value);
child.value = 0;
ClosureType non_virtual_set_cb =
TypeParam::Bind(&Parent::NonVirtualSet, &child);
std::move(non_virtual_set_cb).Run();
EXPECT_EQ(kParentValue, child.value);
}
// Return value support.
// - Function with return value.
// - Method with return value.
// - Const method with return value.
// - Move-only return value.
TYPED_TEST(BindVariantsTest, ReturnValues) {
StrictMock<NoRef> static_func_mock;
StrictMock<HasRef> has_ref;
g_func_mock_ptr = &static_func_mock;
const HasRef* const_has_ref_ptr = &has_ref;
EXPECT_CALL(static_func_mock, IntMethod0()).WillOnce(Return(1337));
EXPECT_CALL(has_ref, AddRef()).Times(4);
EXPECT_CALL(has_ref, Release()).Times(4);
EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
EXPECT_CALL(has_ref, IntMethod0()).WillOnce(Return(31337));
EXPECT_CALL(has_ref, IntConstMethod0())
.WillOnce(Return(41337))
.WillOnce(Return(51337));
EXPECT_CALL(has_ref, UniquePtrMethod0())
.WillOnce(Return(ByMove(std::make_unique<int>(42))));
CallbackType<TypeParam, int()> normal_cb = TypeParam::Bind(&IntFunc0);
CallbackType<TypeParam, int()> method_cb =
TypeParam::Bind(&HasRef::IntMethod0, &has_ref);
CallbackType<TypeParam, int()> const_method_nonconst_obj_cb =
TypeParam::Bind(&HasRef::IntConstMethod0, &has_ref);
CallbackType<TypeParam, int()> const_method_const_obj_cb =
TypeParam::Bind(&HasRef::IntConstMethod0, const_has_ref_ptr);
CallbackType<TypeParam, std::unique_ptr<int>()> move_only_rv_cb =
TypeParam::Bind(&HasRef::UniquePtrMethod0, &has_ref);
EXPECT_EQ(1337, std::move(normal_cb).Run());
EXPECT_EQ(31337, std::move(method_cb).Run());
EXPECT_EQ(41337, std::move(const_method_nonconst_obj_cb).Run());
EXPECT_EQ(51337, std::move(const_method_const_obj_cb).Run());
EXPECT_EQ(42, *std::move(move_only_rv_cb).Run());
}
// Argument binding tests.
// - Argument binding to primitive.
// - Argument binding to primitive pointer.
// - Argument binding to a literal integer.
// - Argument binding to a literal string.
// - Argument binding with template function.
// - Argument binding to an object.
// - Argument binding to pointer to incomplete type.
// - Argument gets type converted.
// - Pointer argument gets converted.
// - Const Reference forces conversion.
TYPED_TEST(BindVariantsTest, ArgumentBinding) {
int n = 2;
EXPECT_EQ(n, TypeParam::Bind(&Identity, n).Run());
EXPECT_EQ(&n, TypeParam::Bind(&PolymorphicIdentity<int*>, &n).Run());
EXPECT_EQ(3, TypeParam::Bind(&Identity, 3).Run());
EXPECT_STREQ("hi", TypeParam::Bind(&CStringIdentity, "hi").Run());
EXPECT_EQ(4, TypeParam::Bind(&PolymorphicIdentity<int>, 4).Run());
NoRefParent p;
p.value = 5;
EXPECT_EQ(5, TypeParam::Bind(&UnwrapNoRefParent, p).Run());
NoRefChild c;
c.value = 6;
EXPECT_EQ(6, TypeParam::Bind(&UnwrapNoRefParent, c).Run());
c.value = 7;
EXPECT_EQ(7, TypeParam::Bind(&UnwrapNoRefParentPtr, &c).Run());
c.value = 8;
EXPECT_EQ(8, TypeParam::Bind(&UnwrapNoRefParentConstRef, c).Run());
}
// Unbound argument type support tests.
// - Unbound value.
// - Unbound pointer.
// - Unbound reference.
// - Unbound const reference.
// - Unbound unsized array.
// - Unbound sized array.
// - Unbound array-of-arrays.
TYPED_TEST(BindVariantsTest, UnboundArgumentTypeSupport) {
CallbackType<TypeParam, void(int)> unbound_value_cb =
TypeParam::Bind(&VoidPolymorphic<int>::Run);
CallbackType<TypeParam, void(int*)> unbound_pointer_cb =
TypeParam::Bind(&VoidPolymorphic<int*>::Run);
CallbackType<TypeParam, void(int&)> unbound_ref_cb =
TypeParam::Bind(&VoidPolymorphic<int&>::Run);
CallbackType<TypeParam, void(const int&)> unbound_const_ref_cb =
TypeParam::Bind(&VoidPolymorphic<const int&>::Run);
CallbackType<TypeParam, void(int[])> unbound_unsized_array_cb =
TypeParam::Bind(&VoidPolymorphic<int[]>::Run);
CallbackType<TypeParam, void(int[2])> unbound_sized_array_cb =
TypeParam::Bind(&VoidPolymorphic<int[2]>::Run);
CallbackType<TypeParam, void(int[][2])> unbound_array_of_arrays_cb =
TypeParam::Bind(&VoidPolymorphic<int[][2]>::Run);
CallbackType<TypeParam, void(int&)> unbound_ref_with_bound_arg =
TypeParam::Bind(&VoidPolymorphic<int, int&>::Run, 1);
}
// Function with unbound reference parameter.
// - Original parameter is modified by callback.
TYPED_TEST(BindVariantsTest, UnboundReferenceSupport) {
int n = 0;
CallbackType<TypeParam, void(int&)> unbound_ref_cb =
TypeParam::Bind(&RefArgSet);
std::move(unbound_ref_cb).Run(n);
EXPECT_EQ(2, n);
}
// Unretained() wrapper support.
// - Method bound to Unretained() non-const object.
// - Const method bound to Unretained() non-const object.
// - Const method bound to Unretained() const object.
TYPED_TEST(BindVariantsTest, Unretained) {
StrictMock<NoRef> no_ref;
const NoRef* const_no_ref_ptr = &no_ref;
EXPECT_CALL(no_ref, VoidMethod0());
EXPECT_CALL(no_ref, VoidConstMethod0()).Times(2);
TypeParam::Bind(&NoRef::VoidMethod0, Unretained(&no_ref)).Run();
TypeParam::Bind(&NoRef::VoidConstMethod0, Unretained(&no_ref)).Run();
TypeParam::Bind(&NoRef::VoidConstMethod0, Unretained(const_no_ref_ptr)).Run();
}
TYPED_TEST(BindVariantsTest, ScopedRefptr) {
StrictMock<HasRef> has_ref;
EXPECT_CALL(has_ref, AddRef()).Times(1);
EXPECT_CALL(has_ref, Release()).Times(1);
EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
const scoped_refptr<HasRef> refptr(&has_ref);
CallbackType<TypeParam, int()> scoped_refptr_const_ref_cb = TypeParam::Bind(
&FunctionWithScopedRefptrFirstParam, std::cref(refptr), 1);
EXPECT_EQ(1, std::move(scoped_refptr_const_ref_cb).Run());
}
TYPED_TEST(BindVariantsTest, UniquePtrReceiver) {
std::unique_ptr<StrictMock<NoRef>> no_ref(new StrictMock<NoRef>);
EXPECT_CALL(*no_ref, VoidMethod0()).Times(1);
TypeParam::Bind(&NoRef::VoidMethod0, std::move(no_ref)).Run();
}
TYPED_TEST(BindVariantsTest, ImplicitRefPtrReceiver) {
StrictMock<HasRef> has_ref;
EXPECT_CALL(has_ref, AddRef()).Times(1);
EXPECT_CALL(has_ref, Release()).Times(1);
EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
HasRef* ptr = &has_ref;
auto ptr_cb = TypeParam::Bind(&HasRef::HasAtLeastOneRef, ptr);
EXPECT_EQ(1, std::move(ptr_cb).Run());
}
TYPED_TEST(BindVariantsTest, RawPtrReceiver) {
StrictMock<HasRef> has_ref;
EXPECT_CALL(has_ref, AddRef()).Times(1);
EXPECT_CALL(has_ref, Release()).Times(1);
EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
raw_ptr<HasRef> rawptr(&has_ref);
auto rawptr_cb = TypeParam::Bind(&HasRef::HasAtLeastOneRef, rawptr);
EXPECT_EQ(1, std::move(rawptr_cb).Run());
}
TYPED_TEST(BindVariantsTest, UnretainedRawRefReceiver) {
StrictMock<HasRef> has_ref;
EXPECT_CALL(has_ref, AddRef()).Times(0);
EXPECT_CALL(has_ref, Release()).Times(0);
EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
raw_ref<HasRef> raw_has_ref(has_ref);
auto has_ref_cb =
TypeParam::Bind(&HasRef::HasAtLeastOneRef, Unretained(raw_has_ref));
EXPECT_EQ(1, std::move(has_ref_cb).Run());
StrictMock<NoRef> no_ref;
EXPECT_CALL(has_ref, IntMethod0()).WillRepeatedly(Return(1));
raw_ref<NoRef> raw_no_ref(has_ref);
auto no_ref_cb = TypeParam::Bind(&NoRef::IntMethod0, Unretained(raw_no_ref));
EXPECT_EQ(1, std::move(no_ref_cb).Run());
}
// Tests for Passed() wrapper support:
// - Passed() can be constructed from a pointer to scoper.
// - Passed() can be constructed from a scoper rvalue.
// - Using Passed() gives Callback Ownership.
// - Ownership is transferred from Callback to callee on the first Run().
// - Callback supports unbound arguments.
template <typename T>
class BindMoveOnlyTypeTest : public ::testing::Test {};
struct CustomDeleter {
void operator()(DeleteCounter* c) { delete c; }
};
using MoveOnlyTypesToTest =
::testing::Types<std::unique_ptr<DeleteCounter>,
std::unique_ptr<DeleteCounter, CustomDeleter>>;
TYPED_TEST_SUITE(BindMoveOnlyTypeTest, MoveOnlyTypesToTest);
TYPED_TEST(BindMoveOnlyTypeTest, PassedToBoundCallback) {
int deletes = 0;
TypeParam ptr(new DeleteCounter(&deletes));
RepeatingCallback<TypeParam()> callback =
BindRepeating(&PassThru<TypeParam>, Passed(&ptr));
EXPECT_FALSE(ptr.get());
EXPECT_EQ(0, deletes);
// If we never invoke the Callback, it retains ownership and deletes.
callback.Reset();
EXPECT_EQ(1, deletes);
}
TYPED_TEST(BindMoveOnlyTypeTest, PassedWithRvalue) {
int deletes = 0;
RepeatingCallback<TypeParam()> callback = BindRepeating(
&PassThru<TypeParam>, Passed(TypeParam(new DeleteCounter(&deletes))));
EXPECT_EQ(0, deletes);
// If we never invoke the Callback, it retains ownership and deletes.
callback.Reset();
EXPECT_EQ(1, deletes);
}
// Check that ownership can be transferred back out.
TYPED_TEST(BindMoveOnlyTypeTest, ReturnMoveOnlyType) {
int deletes = 0;
DeleteCounter* counter = new DeleteCounter(&deletes);
RepeatingCallback<TypeParam()> callback =
BindRepeating(&PassThru<TypeParam>, Passed(TypeParam(counter)));
TypeParam result = callback.Run();
ASSERT_EQ(counter, result.get());
EXPECT_EQ(0, deletes);
// Resetting does not delete since ownership was transferred.
callback.Reset();
EXPECT_EQ(0, deletes);
// Ensure that we actually did get ownership.
result.reset();
EXPECT_EQ(1, deletes);
}
TYPED_TEST(BindMoveOnlyTypeTest, UnboundForwarding) {
int deletes = 0;
TypeParam ptr(new DeleteCounter(&deletes));
// Test unbound argument forwarding.
RepeatingCallback<TypeParam(TypeParam)> cb_unbound =
BindRepeating(&PassThru<TypeParam>);
cb_unbound.Run(std::move(ptr));
EXPECT_EQ(1, deletes);
}
void VerifyVector(const std::vector<std::unique_ptr<int>>& v) {
ASSERT_EQ(1u, v.size());
EXPECT_EQ(12345, *v[0]);
}
std::vector<std::unique_ptr<int>> AcceptAndReturnMoveOnlyVector(
std::vector<std::unique_ptr<int>> v) {
VerifyVector(v);
return v;
}
// Test that a vector containing move-only types can be used with Callback.
TEST_F(BindTest, BindMoveOnlyVector) {
using MoveOnlyVector = std::vector<std::unique_ptr<int>>;
MoveOnlyVector v;
v.push_back(std::make_unique<int>(12345));
// Early binding should work:
base::RepeatingCallback<MoveOnlyVector()> bound_cb =
base::BindRepeating(&AcceptAndReturnMoveOnlyVector, Passed(&v));
MoveOnlyVector intermediate_result = bound_cb.Run();
VerifyVector(intermediate_result);
// As should passing it as an argument to Run():
base::RepeatingCallback<MoveOnlyVector(MoveOnlyVector)> unbound_cb =
base::BindRepeating(&AcceptAndReturnMoveOnlyVector);
MoveOnlyVector final_result = unbound_cb.Run(std::move(intermediate_result));
VerifyVector(final_result);
}
// Argument copy-constructor usage for non-reference copy-only parameters.
// - Bound arguments are only copied once.
// - Forwarded arguments are only copied once.
// - Forwarded arguments with coercions are only copied twice (once for the
// coercion, and one for the final dispatch).
TEST_F(BindTest, ArgumentCopies) {
int copies = 0;
int assigns = 0;
CopyCounter counter(&copies, &assigns);
BindRepeating(&VoidPolymorphic<CopyCounter>::Run, counter);
EXPECT_EQ(1, copies);
EXPECT_EQ(0, assigns);
copies = 0;
assigns = 0;
BindRepeating(&VoidPolymorphic<CopyCounter>::Run,
CopyCounter(&copies, &assigns));
EXPECT_EQ(1, copies);
EXPECT_EQ(0, assigns);
copies = 0;
assigns = 0;
BindRepeating(&VoidPolymorphic<CopyCounter>::Run).Run(counter);
EXPECT_EQ(2, copies);
EXPECT_EQ(0, assigns);
copies = 0;
assigns = 0;
BindRepeating(&VoidPolymorphic<CopyCounter>::Run)
.Run(CopyCounter(&copies, &assigns));
EXPECT_EQ(1, copies);
EXPECT_EQ(0, assigns);
copies = 0;
assigns = 0;
DerivedCopyMoveCounter derived(&copies, &assigns, nullptr, nullptr);
BindRepeating(&VoidPolymorphic<CopyCounter>::Run).Run(CopyCounter(derived));
EXPECT_EQ(2, copies);
EXPECT_EQ(0, assigns);
copies = 0;
assigns = 0;
BindRepeating(&VoidPolymorphic<CopyCounter>::Run)
.Run(CopyCounter(
DerivedCopyMoveCounter(&copies, &assigns, nullptr, nullptr)));
EXPECT_EQ(2, copies);
EXPECT_EQ(0, assigns);
}
// Argument move-constructor usage for move-only parameters.
// - Bound arguments passed by move are not copied.
TEST_F(BindTest, ArgumentMoves) {
int move_constructs = 0;
int move_assigns = 0;
BindRepeating(&VoidPolymorphic<const MoveCounter&>::Run,
MoveCounter(&move_constructs, &move_assigns));
EXPECT_EQ(1, move_constructs);
EXPECT_EQ(0, move_assigns);
// TODO(tzik): Support binding move-only type into a non-reference parameter
// of a variant of Callback.
move_constructs = 0;
move_assigns = 0;
BindRepeating(&VoidPolymorphic<MoveCounter>::Run)
.Run(MoveCounter(&move_constructs, &move_assigns));
EXPECT_EQ(1, move_constructs);
EXPECT_EQ(0, move_assigns);
move_constructs = 0;
move_assigns = 0;
BindRepeating(&VoidPolymorphic<MoveCounter>::Run)
.Run(MoveCounter(DerivedCopyMoveCounter(
nullptr, nullptr, &move_constructs, &move_assigns)));
EXPECT_EQ(2, move_constructs);
EXPECT_EQ(0, move_assigns);
}
// Argument constructor usage for non-reference movable-copyable
// parameters.
// - Bound arguments passed by move are not copied.
// - Forwarded arguments are only copied once.
// - Forwarded arguments with coercions are only copied once and moved once.
TEST_F(BindTest, ArgumentCopiesAndMoves) {
int copies = 0;
int assigns = 0;
int move_constructs = 0;
int move_assigns = 0;
CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run, counter);
EXPECT_EQ(1, copies);
EXPECT_EQ(0, assigns);
EXPECT_EQ(0, move_constructs);
EXPECT_EQ(0, move_assigns);
copies = 0;
assigns = 0;
move_constructs = 0;
move_assigns = 0;
BindRepeating(
&VoidPolymorphic<CopyMoveCounter>::Run,
CopyMoveCounter(&copies, &assigns, &move_constructs, &move_assigns));
EXPECT_EQ(0, copies);
EXPECT_EQ(0, assigns);
EXPECT_EQ(1, move_constructs);
EXPECT_EQ(0, move_assigns);
copies = 0;
assigns = 0;
move_constructs = 0;
move_assigns = 0;
BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run).Run(counter);
EXPECT_EQ(1, copies);
EXPECT_EQ(0, assigns);
EXPECT_EQ(1, move_constructs);
EXPECT_EQ(0, move_assigns);
copies = 0;
assigns = 0;
move_constructs = 0;
move_assigns = 0;
BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run)
.Run(CopyMoveCounter(&copies, &assigns, &move_constructs, &move_assigns));
EXPECT_EQ(0, copies);
EXPECT_EQ(0, assigns);
EXPECT_EQ(1, move_constructs);
EXPECT_EQ(0, move_assigns);
DerivedCopyMoveCounter derived_counter(&copies, &assigns, &move_constructs,
&move_assigns);
copies = 0;
assigns = 0;
move_constructs = 0;
move_assigns = 0;
BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run)
.Run(CopyMoveCounter(derived_counter));
EXPECT_EQ(1, copies);
EXPECT_EQ(0, assigns);
EXPECT_EQ(1, move_constructs);
EXPECT_EQ(0, move_assigns);
copies = 0;
assigns = 0;
move_constructs = 0;
move_assigns = 0;
BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run)
.Run(CopyMoveCounter(DerivedCopyMoveCounter(
&copies, &assigns, &move_constructs, &move_assigns)));
EXPECT_EQ(0, copies);
EXPECT_EQ(0, assigns);
EXPECT_EQ(2, move_constructs);
EXPECT_EQ(0, move_assigns);
}
TEST_F(BindTest, CapturelessLambda) {
EXPECT_FALSE(internal::IsCallableObject<void>::value);
EXPECT_FALSE(internal::IsCallableObject<int>::value);
EXPECT_FALSE(internal::IsCallableObject<void (*)()>::value);
EXPECT_FALSE(internal::IsCallableObject<void (NoRef::*)()>::value);
auto f = [] {};
EXPECT_TRUE(internal::IsCallableObject<decltype(f)>::value);
int i = 0;
auto g = [i] { (void)i; };
EXPECT_TRUE(internal::IsCallableObject<decltype(g)>::value);
auto h = [](int, double) { return 'k'; };
EXPECT_TRUE((std::is_same_v<char(int, double),
internal::ExtractCallableRunType<decltype(h)>>));
EXPECT_EQ(42, BindRepeating([] { return 42; }).Run());
EXPECT_EQ(42, BindRepeating([](int i) { return i * 7; }, 6).Run());
int x = 1;
base::RepeatingCallback<void(int)> cb =
BindRepeating([](int* x, int i) { *x *= i; }, Unretained(&x));
cb.Run(6);
EXPECT_EQ(6, x);
cb.Run(7);
EXPECT_EQ(42, x);
}
TEST_F(BindTest, EmptyFunctor) {
struct NonEmptyFunctor {
int operator()() const { return x; }
int x = 42;
};
struct EmptyFunctor {
int operator()() { return 42; }
};
struct EmptyFunctorConst {
int operator()() const { return 42; }
};
EXPECT_TRUE(internal::IsCallableObject<NonEmptyFunctor>::value);
EXPECT_TRUE(internal::IsCallableObject<EmptyFunctor>::value);
EXPECT_TRUE(internal::IsCallableObject<EmptyFunctorConst>::value);
EXPECT_EQ(42, BindOnce(EmptyFunctor()).Run());
EXPECT_EQ(42, BindOnce(EmptyFunctorConst()).Run());
EXPECT_EQ(42, BindRepeating(EmptyFunctorConst()).Run());
}
TEST_F(BindTest, CapturingLambdaForTesting) {
// Test copyable lambdas.
int x = 6;
EXPECT_EQ(42, BindLambdaForTesting([=](int y) { return x * y; }).Run(7));
EXPECT_EQ(42,
BindLambdaForTesting([=](int y) mutable { return x *= y; }).Run(7));
auto f = [x](std::unique_ptr<int> y) { return x * *y; };
EXPECT_EQ(42, BindLambdaForTesting(f).Run(std::make_unique<int>(7)));
// Test move-only lambdas.
auto y = std::make_unique<int>(7);
auto g = [y = std::move(y)](int& x) mutable {
return x * *std::exchange(y, nullptr);
};
EXPECT_EQ(42, BindLambdaForTesting(std::move(g)).Run(x));
y = std::make_unique<int>(7);
auto h = [x, y = std::move(y)] { return x * *y; };
EXPECT_EQ(42, BindLambdaForTesting(std::move(h)).Run());
}
TEST_F(BindTest, Cancellation) {
EXPECT_CALL(no_ref_, VoidMethodWithIntArg(_)).Times(2);
WeakPtrFactory<NoRef> weak_factory(&no_ref_);
RepeatingCallback<void(int)> cb =
BindRepeating(&NoRef::VoidMethodWithIntArg, weak_factory.GetWeakPtr());
RepeatingClosure cb2 = BindRepeating(cb, 8);
OnceClosure cb3 = BindOnce(cb, 8);
OnceCallback<void(int)> cb4 =
BindOnce(&NoRef::VoidMethodWithIntArg, weak_factory.GetWeakPtr());
EXPECT_FALSE(cb4.IsCancelled());
OnceClosure cb5 = BindOnce(std::move(cb4), 8);
EXPECT_FALSE(cb.IsCancelled());
EXPECT_FALSE(cb2.IsCancelled());
EXPECT_FALSE(cb3.IsCancelled());
EXPECT_FALSE(cb5.IsCancelled());
cb.Run(6);
cb2.Run();
weak_factory.InvalidateWeakPtrs();
EXPECT_TRUE(cb.IsCancelled());
EXPECT_TRUE(cb2.IsCancelled());
EXPECT_TRUE(cb3.IsCancelled());
EXPECT_TRUE(cb5.IsCancelled());
cb.Run(6);
cb2.Run();
std::move(cb3).Run();
std::move(cb5).Run();
}
TEST_F(BindTest, OnceCallback) {
// Check if Callback variants have declarations of conversions as expected.
// Copy constructor and assignment of RepeatingCallback.
static_assert(
std::is_constructible_v<RepeatingClosure, const RepeatingClosure&>,
"RepeatingClosure should be copyable.");
static_assert(std::is_assignable_v<RepeatingClosure, const RepeatingClosure&>,
"RepeatingClosure should be copy-assignable.");
// Move constructor and assignment of RepeatingCallback.
static_assert(std::is_constructible_v<RepeatingClosure, RepeatingClosure&&>,
"RepeatingClosure should be movable.");
static_assert(std::is_assignable_v<RepeatingClosure, RepeatingClosure&&>,
"RepeatingClosure should be move-assignable");
// Conversions from OnceCallback to RepeatingCallback.
static_assert(!std::is_constructible_v<RepeatingClosure, const OnceClosure&>,
"OnceClosure should not be convertible to RepeatingClosure.");
static_assert(!std::is_assignable_v<RepeatingClosure, const OnceClosure&>,
"OnceClosure should not be convertible to RepeatingClosure.");
// Destructive conversions from OnceCallback to RepeatingCallback.
static_assert(!std::is_constructible_v<RepeatingClosure, OnceClosure&&>,
"OnceClosure should not be convertible to RepeatingClosure.");
static_assert(!std::is_assignable_v<RepeatingClosure, OnceClosure&&>,
"OnceClosure should not be convertible to RepeatingClosure.");
// Copy constructor and assignment of OnceCallback.
static_assert(!std::is_constructible_v<OnceClosure, const OnceClosure&>,
"OnceClosure should not be copyable.");
static_assert(!std::is_assignable_v<OnceClosure, const OnceClosure&>,
"OnceClosure should not be copy-assignable");
// Move constructor and assignment of OnceCallback.
static_assert(std::is_constructible_v<OnceClosure, OnceClosure&&>,
"OnceClosure should be movable.");
static_assert(std::is_assignable_v<OnceClosure, OnceClosure&&>,
"OnceClosure should be move-assignable.");
// Conversions from RepeatingCallback to OnceCallback.
static_assert(std::is_constructible_v<OnceClosure, const RepeatingClosure&>,
"RepeatingClosure should be convertible to OnceClosure.");
static_assert(std::is_assignable_v<OnceClosure, const RepeatingClosure&>,
"RepeatingClosure should be convertible to OnceClosure.");
// Destructive conversions from RepeatingCallback to OnceCallback.
static_assert(std::is_constructible_v<OnceClosure, RepeatingClosure&&>,
"RepeatingClosure should be convertible to OnceClosure.");
static_assert(std::is_assignable_v<OnceClosure, RepeatingClosure&&>,
"RepeatingClosure should be covretible to OnceClosure.");
OnceClosure cb = BindOnce(&VoidPolymorphic<>::Run);
std::move(cb).Run();
// RepeatingCallback should be convertible to OnceCallback.
OnceClosure cb2 = BindRepeating(&VoidPolymorphic<>::Run);
std::move(cb2).Run();
RepeatingClosure cb3 = BindRepeating(&VoidPolymorphic<>::Run);
cb = cb3;
std::move(cb).Run();
cb = std::move(cb2);
OnceCallback<void(int)> cb4 =
BindOnce(&VoidPolymorphic<std::unique_ptr<int>, int>::Run,
std::make_unique<int>(0));
BindOnce(std::move(cb4), 1).Run();
}
// Callback construction and assignment tests.
// - Construction from an InvokerStorageHolder should not cause ref/deref.
// - Assignment from other callback should only cause one ref
//
// TODO(ajwong): Is there actually a way to test this?
#if BUILDFLAG(IS_WIN)
int __fastcall FastCallFunc(int n) {
return n;
}
int __stdcall StdCallFunc(int n) {
return n;
}
// Windows specific calling convention support.
// - Can bind a __fastcall function.
// - Can bind a __stdcall function.
// - Can bind const and non-const __stdcall methods.
TEST_F(BindTest, WindowsCallingConventions) {
auto fastcall_cb = BindRepeating(&FastCallFunc, 1);
EXPECT_EQ(1, fastcall_cb.Run());
auto stdcall_cb = BindRepeating(&StdCallFunc, 2);
EXPECT_EQ(2, stdcall_cb.Run());
class MethodHolder {
public:
int __stdcall Func(int n) { return n; }
int __stdcall ConstFunc(int n) const { return -n; }
};
MethodHolder obj;
auto stdcall_method_cb =
BindRepeating(&MethodHolder::Func, base::Unretained(&obj), 1);
EXPECT_EQ(1, stdcall_method_cb.Run());
const MethodHolder const_obj;
auto stdcall_const_method_cb =
BindRepeating(&MethodHolder::ConstFunc, base::Unretained(&const_obj), 1);
EXPECT_EQ(-1, stdcall_const_method_cb.Run());
}
#endif
// Test unwrapping the various wrapping functions.
TEST_F(BindTest, UnwrapUnretained) {
int i = 0;
auto unretained = Unretained(&i);
EXPECT_EQ(&i, internal::Unwrap(unretained));
EXPECT_EQ(&i, internal::Unwrap(std::move(unretained)));
}
TEST_F(BindTest, UnwrapRetainedRef) {
auto p = MakeRefCounted<RefCountedData<int>>();
auto retained_ref = RetainedRef(p);
EXPECT_EQ(p.get(), internal::Unwrap(retained_ref));
EXPECT_EQ(p.get(), internal::Unwrap(std::move(retained_ref)));
}
TEST_F(BindTest, UnwrapOwned) {
{
int* p = new int;
auto owned = Owned(p);
EXPECT_EQ(p, internal::Unwrap(owned));
EXPECT_EQ(p, internal::Unwrap(std::move(owned)));
}
{
auto p = std::make_unique<int>();
int* raw_p = p.get();
auto owned = Owned(std::move(p));
EXPECT_EQ(raw_p, internal::Unwrap(owned));
EXPECT_EQ(raw_p, internal::Unwrap(std::move(owned)));
}
}
TEST_F(BindTest, UnwrapPassed) {
int* p = new int;
auto passed = Passed(WrapUnique(p));
EXPECT_EQ(p, internal::Unwrap(passed).get());
p = new int;
EXPECT_EQ(p, internal::Unwrap(Passed(WrapUnique(p))).get());
}
TEST_F(BindTest, BindNoexcept) {
EXPECT_EQ(42, base::BindOnce(&Noexcept).Run());
EXPECT_EQ(
42,
base::BindOnce(&BindTest::NoexceptMethod, base::Unretained(this)).Run());
EXPECT_EQ(
42, base::BindOnce(&BindTest::ConstNoexceptMethod, base::Unretained(this))
.Run());
EXPECT_EQ(42, base::BindOnce(NoexceptFunctor()).Run());
EXPECT_EQ(42, base::BindOnce(ConstNoexceptFunctor()).Run());
}
int PingPong(int* i_ptr) {
return *i_ptr;
}
TEST_F(BindTest, BindAndCallbacks) {
int i = 123;
raw_ptr<int> p = &i;
auto callback = base::BindOnce(PingPong, base::Unretained(p));
int res = std::move(callback).Run();
EXPECT_EQ(123, res);
}
TEST_F(BindTest, ConvertibleArgs) {
// Create two types S and T, such that you can convert a T to an S, but you
// cannot construct an S from a T.
struct T;
class S {
friend struct T;
explicit S(const T&) {}
};
struct T {
// NOLINTNEXTLINE(google-explicit-constructor)
operator S() const { return S(*this); }
};
static_assert(!std::is_constructible_v<S, T>);
static_assert(std::is_convertible_v<T, S>);
// Ensure it's possible to pass a T to a function expecting an S.
void (*foo)(S) = +[](S) {};
const T t;
auto callback = base::BindOnce(foo, t);
std::move(callback).Run();
}
} // namespace
// This simulates a race weak pointer that, unlike our `base::WeakPtr<>`,
// may become invalidated between `operator bool()` is tested and `Lock()`
// is called in the implementation of `Unwrap()`.
template <typename T>
struct MockRacyWeakPtr {
explicit MockRacyWeakPtr(T*) {}
T* Lock() const { return nullptr; }
explicit operator bool() const { return true; }
};
template <typename T>
struct IsWeakReceiver<MockRacyWeakPtr<T>> : std::true_type {};
template <typename T>
struct BindUnwrapTraits<MockRacyWeakPtr<T>> {
static T* Unwrap(const MockRacyWeakPtr<T>& o) { return o.Lock(); }
};
template <typename T>
struct MaybeValidTraits<MockRacyWeakPtr<T>> {
static bool MaybeValid(const MockRacyWeakPtr<T>& o) { return true; }
};
namespace {
// Note this only covers a case of racy weak pointer invalidation. Other
// weak pointer scenarios (such as a valid pointer) are covered
// in BindTest.WeakPtrFor{Once,Repeating}.
TEST_F(BindTest, BindRacyWeakPtrTest) {
MockRacyWeakPtr<NoRef> weak(&no_ref_);
RepeatingClosure cb = base::BindRepeating(&NoRef::VoidMethod0, weak);
cb.Run();
}
// Test null callbacks cause a DCHECK.
TEST(BindDeathTest, NullCallback) {
base::RepeatingCallback<void(int)> null_cb;
ASSERT_TRUE(null_cb.is_null());
EXPECT_CHECK_DEATH(base::BindRepeating(null_cb, 42));
}
TEST(BindDeathTest, NullFunctionPointer) {
void (*null_function)(int) = nullptr;
EXPECT_DCHECK_DEATH(base::BindRepeating(null_function, 42));
}
TEST(BindDeathTest, NullCallbackWithoutBoundArgs) {
base::OnceCallback<void(int)> null_cb;
ASSERT_TRUE(null_cb.is_null());
EXPECT_CHECK_DEATH(base::BindOnce(std::move(null_cb)));
}
TEST(BindDeathTest, BanFirstOwnerOfRefCountedType) {
StrictMock<HasRef> has_ref;
EXPECT_DCHECK_DEATH({
EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillOnce(Return(false));
base::BindOnce(&HasRef::VoidMethod0, &has_ref);
});
EXPECT_DCHECK_DEATH({
raw_ptr<HasRef> rawptr(&has_ref);
EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillOnce(Return(false));
base::BindOnce(&HasRef::VoidMethod0, rawptr);
});
}
#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
void HandleOOM(size_t unused_size) {
LOG(FATAL) << "Out of memory";
}
// Basic set of options to mostly only enable `BackupRefPtr::kEnabled`.
// This avoids the boilerplate of having too much options enabled for simple
// testing purpose.
static constexpr partition_alloc::PartitionOptions
kOnlyEnableBackupRefPtrOptions = {
.backup_ref_ptr = partition_alloc::PartitionOptions::kEnabled,
};
class BindUnretainedDanglingInternalFixture : public BindTest {
public:
void SetUp() override {
partition_alloc::PartitionAllocGlobalInit(HandleOOM);
enabled_feature_list_.InitWithFeaturesAndParameters(
{{features::kPartitionAllocUnretainedDanglingPtr, {{"mode", "crash"}}}},
{/* disabled_features */});
allocator::InstallUnretainedDanglingRawPtrChecks();
}
void TearDown() override {
enabled_feature_list_.Reset();
allocator::InstallUnretainedDanglingRawPtrChecks();
}
// In unit tests, allocations being tested need to live in a separate PA
// root so the test code doesn't interfere with various counters. Following
// methods are helpers for managing allocations inside the separate allocator
// root.
template <typename T,
RawPtrTraits Traits = RawPtrTraits::kEmpty,
typename... Args>
raw_ptr<T, Traits> Alloc(Args&&... args) {
void* ptr = allocator_.root()->Alloc(sizeof(T), "");
T* p = new (reinterpret_cast<T*>(ptr)) T(std::forward<Args>(args)...);
return raw_ptr<T, Traits>(p);
}
template <typename T, RawPtrTraits Traits>
void Free(raw_ptr<T, Traits>& ptr) {
allocator_.root()->Free(ptr.ExtractAsDangling());
}
private:
test::ScopedFeatureList enabled_feature_list_;
partition_alloc::PartitionAllocatorForTesting allocator_{
kOnlyEnableBackupRefPtrOptions};
};
class BindUnretainedDanglingTest
: public BindUnretainedDanglingInternalFixture {};
class BindUnretainedDanglingDeathTest
: public BindUnretainedDanglingInternalFixture {};
bool PtrCheckFn(int* p) {
return p != nullptr;
}
bool RefCheckFn(const int& p) {
return true;
}
bool MayBeDanglingCheckFn(MayBeDangling<int> p) {
return p != nullptr;
}
bool MayBeDanglingAndDummyTraitCheckFn(
MayBeDangling<int, RawPtrTraits::kDummyForTest> p) {
return p != nullptr;
}
class ClassWithWeakPtr {
public:
ClassWithWeakPtr() = default;
void RawPtrArg(int* p) { *p = 123; }
void RawRefArg(int& p) { p = 123; }
WeakPtr<ClassWithWeakPtr> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
private:
WeakPtrFactory<ClassWithWeakPtr> weak_factory_{this};
};
TEST_F(BindUnretainedDanglingTest, UnretainedNoDanglingPtr) {
raw_ptr<int> p = Alloc<int>(3);
auto callback = base::BindOnce(PingPong, base::Unretained(p));
EXPECT_EQ(std::move(callback).Run(), 3);
Free(p);
}
TEST_F(BindUnretainedDanglingTest, UnsafeDanglingPtr) {
raw_ptr<int> p = Alloc<int>(3);
auto callback = base::BindOnce(MayBeDanglingCheckFn, base::UnsafeDangling(p));
Free(p);
EXPECT_EQ(std::move(callback).Run(), true);
}
TEST_F(BindUnretainedDanglingTest, UnsafeDanglingPtrWithDummyTrait) {
raw_ptr<int, RawPtrTraits::kDummyForTest> p =
Alloc<int, RawPtrTraits::kDummyForTest>(3);
auto callback = base::BindOnce(MayBeDanglingAndDummyTraitCheckFn,
base::UnsafeDangling(p));
Free(p);
EXPECT_EQ(std::move(callback).Run(), true);
}
TEST_F(BindUnretainedDanglingTest,
UnsafeDanglingPtrWithDummyAndDanglingTraits) {
raw_ptr<int, RawPtrTraits::kDummyForTest | RawPtrTraits::kMayDangle> p =
Alloc<int, RawPtrTraits::kDummyForTest | RawPtrTraits::kMayDangle>(3);
auto callback = base::BindOnce(MayBeDanglingAndDummyTraitCheckFn,
base::UnsafeDangling(p));
Free(p);
EXPECT_EQ(std::move(callback).Run(), true);
}
TEST_F(BindUnretainedDanglingTest, UnsafeDanglingPtrNoRawPtrReceiver) {
std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
int val = 0;
auto callback =
base::BindOnce(&ClassWithWeakPtr::RawPtrArg,
base::UnsafeDangling(r.get()), base::Unretained(&val));
std::move(callback).Run();
EXPECT_EQ(val, 123);
}
TEST_F(BindUnretainedDanglingTest, UnsafeDanglingUntriagedPtr) {
raw_ptr<int> p = Alloc<int>(3);
auto callback = base::BindOnce(PtrCheckFn, base::UnsafeDanglingUntriaged(p));
Free(p);
EXPECT_EQ(std::move(callback).Run(), true);
}
TEST_F(BindUnretainedDanglingTest, UnretainedWeakReceiverValidNoDangling) {
raw_ptr<int> p = Alloc<int>(3);
std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
auto callback = base::BindOnce(&ClassWithWeakPtr::RawPtrArg, r->GetWeakPtr(),
base::Unretained(p));
std::move(callback).Run();
EXPECT_EQ(*p, 123);
Free(p);
}
TEST_F(BindUnretainedDanglingTest, UnretainedRefWeakReceiverValidNoDangling) {
raw_ptr<int> p = Alloc<int>(3);
int& ref = *p;
std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
auto callback = base::BindOnce(&ClassWithWeakPtr::RawRefArg, r->GetWeakPtr(),
std::ref(ref));
std::move(callback).Run();
EXPECT_EQ(*p, 123);
Free(p);
}
TEST_F(BindUnretainedDanglingTest, UnretainedWeakReceiverInvalidNoDangling) {
raw_ptr<int> p = Alloc<int>(3);
std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
auto callback = base::BindOnce(&ClassWithWeakPtr::RawPtrArg, r->GetWeakPtr(),
base::Unretained(p));
r.reset();
Free(p);
std::move(callback).Run();
// Should reach this point without crashing; there is a dangling pointer, but
// the callback is cancelled because the WeakPtr is already invalidated.
}
TEST_F(BindUnretainedDanglingTest, UnretainedRefWeakReceiverInvalidNoDangling) {
raw_ptr<int> p = Alloc<int>(3);
int& ref = *p;
std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
auto callback = base::BindOnce(&ClassWithWeakPtr::RawRefArg, r->GetWeakPtr(),
std::ref(ref));
r.reset();
Free(p);
std::move(callback).Run();
// Should reach this point without crashing; there is a dangling pointer, but
// the callback is cancelled because the WeakPtr is already invalidated.
}
TEST_F(BindUnretainedDanglingTest, UnretainedRefUnsafeDangling) {
raw_ptr<int> p = Alloc<int>(3);
int& ref = *p;
auto callback =
base::BindOnce(RefCheckFn, base::UnsafeDangling(base::raw_ref<int>(ref)));
Free(p);
EXPECT_EQ(std::move(callback).Run(), true);
// Should reach this point without crashing; there is a dangling pointer, but
// the we marked the reference as `UnsafeDangling`.
}
TEST_F(BindUnretainedDanglingTest, UnretainedRefUnsafeDanglingUntriaged) {
raw_ptr<int> p = Alloc<int>(3);
int& ref = *p;
auto callback = base::BindOnce(
RefCheckFn, base::UnsafeDanglingUntriaged(base::raw_ref<const int>(ref)));
Free(p);
EXPECT_EQ(std::move(callback).Run(), true);
// Should reach this point without crashing; there is a dangling pointer, but
// the we marked the reference as `UnsafeDanglingUntriaged`.
}
// Death tests misbehave on Android, http://crbug.com/643760.
#if defined(GTEST_HAS_DEATH_TEST) && !BUILDFLAG(IS_ANDROID)
int FuncWithRefArgument(int& i_ptr) {
return i_ptr;
}
TEST_F(BindUnretainedDanglingDeathTest, UnretainedDanglingPtr) {
raw_ptr<int> p = Alloc<int>(3);
auto callback = base::BindOnce(PingPong, base::Unretained(p));
Free(p);
EXPECT_DEATH(std::move(callback).Run(), "");
}
TEST_F(BindUnretainedDanglingDeathTest, UnretainedRefDanglingPtr) {
raw_ptr<int> p = Alloc<int>(3);
int& ref = *p;
auto callback = base::BindOnce(FuncWithRefArgument, std::ref(ref));
Free(p);
EXPECT_DEATH(std::move(callback).Run(), "");
}
TEST_F(BindUnretainedDanglingDeathTest,
UnretainedRefWithManualUnretainedDanglingPtr) {
raw_ptr<int> p = Alloc<int>(3);
int& ref = *p;
auto callback = base::BindOnce(FuncWithRefArgument,
base::Unretained(base::raw_ref<int>(ref)));
Free(p);
EXPECT_DEATH(std::move(callback).Run(), "");
}
TEST_F(BindUnretainedDanglingDeathTest, UnretainedWeakReceiverDangling) {
raw_ptr<int> p = Alloc<int>(3);
std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
auto callback = base::BindOnce(&ClassWithWeakPtr::RawPtrArg, r->GetWeakPtr(),
base::Unretained(p));
Free(p);
EXPECT_DEATH(std::move(callback).Run(), "");
}
#endif // defined(GTEST_HAS_DEATH_TEST) && !BUILDFLAG(IS_ANDROID)
#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
} // namespace
} // namespace base
|