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 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
|
// Package immutable provides immutable collection types.
//
// Introduction
//
// Immutable collections provide an efficient, safe way to share collections
// of data while minimizing locks. The collections in this package provide
// List, Map, and SortedMap implementations. These act similarly to slices
// and maps, respectively, except that altering a collection returns a new
// copy of the collection with that change.
//
// Because collections are unable to change, they are safe for multiple
// goroutines to read from at the same time without a mutex. However, these
// types of collections come with increased CPU & memory usage as compared
// with Go's built-in collection types so please evaluate for your specific
// use.
//
// Collection Types
//
// The List type provides an API similar to Go slices. They allow appending,
// prepending, and updating of elements. Elements can also be fetched by index
// or iterated over using a ListIterator.
//
// The Map & SortedMap types provide an API similar to Go maps. They allow
// values to be assigned to unique keys and allow for the deletion of keys.
// Values can be fetched by key and key/value pairs can be iterated over using
// the appropriate iterator type. Both map types provide the same API. The
// SortedMap, however, provides iteration over sorted keys while the Map
// provides iteration over unsorted keys. Maps improved performance and memory
// usage as compared to SortedMaps.
//
// Hashing and Sorting
//
// Map types require the use of a Hasher implementation to calculate hashes for
// their keys and check for key equality. SortedMaps require the use of a
// Comparer implementation to sort keys in the map.
//
// These collection types automatically provide built-in hasher and comparers
// for int, string, and byte slice keys. If you are using one of these key types
// then simply pass a nil into the constructor. Otherwise you will need to
// implement a custom Hasher or Comparer type. Please see the provided
// implementations for reference.
package immutable
import (
"bytes"
"fmt"
"math/bits"
"sort"
"strings"
)
// List is a dense, ordered, indexed collections. They are analogous to slices
// in Go. They can be updated by appending to the end of the list, prepending
// values to the beginning of the list, or updating existing indexes in the
// list.
type List struct {
root listNode // root node
origin int // offset to zero index element
size int // total number of elements in use
}
// NewList returns a new empty instance of List.
func NewList() *List {
return &List{
root: &listLeafNode{},
}
}
// clone returns a copy of the list.
func (l *List) clone() *List {
other := *l
return &other
}
// Len returns the number of elements in the list.
func (l *List) Len() int {
return l.size
}
// cap returns the total number of possible elements for the current depth.
func (l *List) cap() int {
return 1 << (l.root.depth() * listNodeBits)
}
// Get returns the value at the given index. Similar to slices, this method will
// panic if index is below zero or is greater than or equal to the list size.
func (l *List) Get(index int) interface{} {
if index < 0 || index >= l.size {
panic(fmt.Sprintf("immutable.List.Get: index %d out of bounds", index))
}
return l.root.get(l.origin + index)
}
// Set returns a new list with value set at index. Similar to slices, this
// method will panic if index is below zero or if the index is greater than
// or equal to the list size.
func (l *List) Set(index int, value interface{}) *List {
return l.set(index, value, false)
}
func (l *List) set(index int, value interface{}, mutable bool) *List {
if index < 0 || index >= l.size {
panic(fmt.Sprintf("immutable.List.Set: index %d out of bounds", index))
}
other := l
if !mutable {
other = l.clone()
}
other.root = other.root.set(l.origin+index, value, mutable)
return other
}
// Append returns a new list with value added to the end of the list.
func (l *List) Append(value interface{}) *List {
return l.append(value, false)
}
func (l *List) append(value interface{}, mutable bool) *List {
other := l
if !mutable {
other = l.clone()
}
// Expand list to the right if no slots remain.
if other.size+other.origin >= l.cap() {
newRoot := &listBranchNode{d: other.root.depth() + 1}
newRoot.children[0] = other.root
other.root = newRoot
}
// Increase size and set the last element to the new value.
other.size++
other.root = other.root.set(other.origin+other.size-1, value, mutable)
return other
}
// Prepend returns a new list with value added to the beginning of the list.
func (l *List) Prepend(value interface{}) *List {
return l.prepend(value, false)
}
func (l *List) prepend(value interface{}, mutable bool) *List {
other := l
if !mutable {
other = l.clone()
}
// Expand list to the left if no slots remain.
if other.origin == 0 {
newRoot := &listBranchNode{d: other.root.depth() + 1}
newRoot.children[listNodeSize-1] = other.root
other.root = newRoot
other.origin += (listNodeSize - 1) << (other.root.depth() * listNodeBits)
}
// Increase size and move origin back. Update first element to value.
other.size++
other.origin--
other.root = other.root.set(other.origin, value, mutable)
return other
}
// Slice returns a new list of elements between start index and end index.
// Similar to slices, this method will panic if start or end are below zero or
// greater than the list size. A panic will also occur if start is greater than
// end.
//
// Unlike Go slices, references to inaccessible elements will be automatically
// removed so they can be garbage collected.
func (l *List) Slice(start, end int) *List {
return l.slice(start, end, false)
}
func (l *List) slice(start, end int, mutable bool) *List {
// Panics similar to Go slices.
if start < 0 || start > l.size {
panic(fmt.Sprintf("immutable.List.Slice: start index %d out of bounds", start))
} else if end < 0 || end > l.size {
panic(fmt.Sprintf("immutable.List.Slice: end index %d out of bounds", end))
} else if start > end {
panic(fmt.Sprintf("immutable.List.Slice: invalid slice index: [%d:%d]", start, end))
}
// Return the same list if the start and end are the entire range.
if start == 0 && end == l.size {
return l
}
// Create copy, if immutable.
other := l
if !mutable {
other = l.clone()
}
// Update origin/size.
other.origin = l.origin + start
other.size = end - start
// Contract tree while the start & end are in the same child node.
for other.root.depth() > 1 {
i := (other.origin >> (other.root.depth() * listNodeBits)) & listNodeMask
j := ((other.origin + other.size - 1) >> (other.root.depth() * listNodeBits)) & listNodeMask
if i != j {
break // branch contains at least two nodes, exit
}
// Replace the current root with the single child & update origin offset.
other.origin -= i << (other.root.depth() * listNodeBits)
other.root = other.root.(*listBranchNode).children[i]
}
// Ensure all references are removed before start & after end.
other.root = other.root.deleteBefore(other.origin, mutable)
other.root = other.root.deleteAfter(other.origin+other.size-1, mutable)
return other
}
// Iterator returns a new iterator for this list positioned at the first index.
func (l *List) Iterator() *ListIterator {
itr := &ListIterator{list: l}
itr.First()
return itr
}
// ListBuilder represents an efficient builder for creating Lists.
//
// Lists returned from the builder are safe to use even after you continue to
// use the builder. However, for efficiency, you should only retrieve your list
// after you have completed building it.
type ListBuilder struct {
list *List // current state
mutable bool // if true, next mutation will operate in-place.
}
// NewListBuilder returns a new instance of ListBuilder to build on a base list.
func NewListBuilder(list *List) *ListBuilder {
return &ListBuilder{list: list}
}
// List returns the current copy of the list.
// The returned list is safe to use even if after the builder continues to be used.
func (b *ListBuilder) List() *List {
list := b.list
b.mutable = false
return list
}
// Len returns the number of elements in the underlying list.
func (b *ListBuilder) Len() int {
return b.list.Len()
}
// Get returns the value at the given index. Similar to slices, this method will
// panic if index is below zero or is greater than or equal to the list size.
func (b *ListBuilder) Get(index int) interface{} {
return b.list.Get(index)
}
// Set updates the value at the given index. Similar to slices, this method will
// panic if index is below zero or if the index is greater than or equal to the
// list size.
func (b *ListBuilder) Set(index int, value interface{}) {
b.list = b.list.set(index, value, b.mutable)
b.mutable = true
}
// Append adds value to the end of the list.
func (b *ListBuilder) Append(value interface{}) {
b.list = b.list.append(value, b.mutable)
b.mutable = true
}
// Prepend adds value to the beginning of the list.
func (b *ListBuilder) Prepend(value interface{}) {
b.list = b.list.prepend(value, b.mutable)
b.mutable = true
}
// Slice updates the list with a sublist of elements between start and end index.
// See List.Slice() for more details.
func (b *ListBuilder) Slice(start, end int) {
b.list = b.list.slice(start, end, b.mutable)
b.mutable = true
}
// Constants for bit shifts used for levels in the List trie.
const (
listNodeBits = 5
listNodeSize = 1 << listNodeBits
listNodeMask = listNodeSize - 1
)
// listNode represents either a branch or leaf node in a List.
type listNode interface {
depth() uint
get(index int) interface{}
set(index int, v interface{}, mutable bool) listNode
containsBefore(index int) bool
containsAfter(index int) bool
deleteBefore(index int, mutable bool) listNode
deleteAfter(index int, mutable bool) listNode
}
// newListNode returns a leaf node for depth zero, otherwise returns a branch node.
func newListNode(depth uint) listNode {
if depth == 0 {
return &listLeafNode{}
}
return &listBranchNode{d: depth}
}
// listBranchNode represents a branch of a List tree at a given depth.
type listBranchNode struct {
d uint // depth
children [listNodeSize]listNode
}
// depth returns the depth of this branch node from the leaf.
func (n *listBranchNode) depth() uint { return n.d }
// get returns the child node at the segment of the index for this depth.
func (n *listBranchNode) get(index int) interface{} {
idx := (index >> (n.d * listNodeBits)) & listNodeMask
return n.children[idx].get(index)
}
// set recursively updates the value at index for each lower depth from the node.
func (n *listBranchNode) set(index int, v interface{}, mutable bool) listNode {
idx := (index >> (n.d * listNodeBits)) & listNodeMask
// Find child for the given value in the branch. Create new if it doesn't exist.
child := n.children[idx]
if child == nil {
child = newListNode(n.depth() - 1)
}
// Return a copy of this branch with the new child.
var other *listBranchNode
if mutable {
other = n
} else {
tmp := *n
other = &tmp
}
other.children[idx] = child.set(index, v, mutable)
return other
}
// containsBefore returns true if non-nil values exists between [0,index).
func (n *listBranchNode) containsBefore(index int) bool {
idx := (index >> (n.d * listNodeBits)) & listNodeMask
// Quickly check if any direct children exist before this segment of the index.
for i := 0; i < idx; i++ {
if n.children[i] != nil {
return true
}
}
// Recursively check for children directly at the given index at this segment.
if n.children[idx] != nil && n.children[idx].containsBefore(index) {
return true
}
return false
}
// containsAfter returns true if non-nil values exists between (index,listNodeSize).
func (n *listBranchNode) containsAfter(index int) bool {
idx := (index >> (n.d * listNodeBits)) & listNodeMask
// Quickly check if any direct children exist after this segment of the index.
for i := idx + 1; i < len(n.children); i++ {
if n.children[i] != nil {
return true
}
}
// Recursively check for children directly at the given index at this segment.
if n.children[idx] != nil && n.children[idx].containsAfter(index) {
return true
}
return false
}
// deleteBefore returns a new node with all elements before index removed.
func (n *listBranchNode) deleteBefore(index int, mutable bool) listNode {
// Ignore if no nodes exist before the given index.
if !n.containsBefore(index) {
return n
}
// Return a copy with any nodes prior to the index removed.
idx := (index >> (n.d * listNodeBits)) & listNodeMask
var other *listBranchNode
if mutable {
other = n
for i := 0; i < idx; i++ {
n.children[i] = nil
}
} else {
other = &listBranchNode{d: n.d}
copy(other.children[idx:][:], n.children[idx:][:])
}
if other.children[idx] != nil {
other.children[idx] = other.children[idx].deleteBefore(index, mutable)
}
return other
}
// deleteBefore returns a new node with all elements before index removed.
func (n *listBranchNode) deleteAfter(index int, mutable bool) listNode {
// Ignore if no nodes exist after the given index.
if !n.containsAfter(index) {
return n
}
// Return a copy with any nodes after the index removed.
idx := (index >> (n.d * listNodeBits)) & listNodeMask
var other *listBranchNode
if mutable {
other = n
for i := idx + 1; i < len(n.children); i++ {
n.children[i] = nil
}
} else {
other = &listBranchNode{d: n.d}
copy(other.children[:idx+1], n.children[:idx+1])
}
if other.children[idx] != nil {
other.children[idx] = other.children[idx].deleteAfter(index, mutable)
}
return other
}
// listLeafNode represents a leaf node in a List.
type listLeafNode struct {
children [listNodeSize]interface{}
}
// depth always returns 0 for leaf nodes.
func (n *listLeafNode) depth() uint { return 0 }
// get returns the value at the given index.
func (n *listLeafNode) get(index int) interface{} {
return n.children[index&listNodeMask]
}
// set returns a copy of the node with the value at the index updated to v.
func (n *listLeafNode) set(index int, v interface{}, mutable bool) listNode {
idx := index & listNodeMask
var other *listLeafNode
if mutable {
other = n
} else {
tmp := *n
other = &tmp
}
other.children[idx] = v
return other
}
// containsBefore returns true if non-nil values exists between [0,index).
func (n *listLeafNode) containsBefore(index int) bool {
idx := index & listNodeMask
for i := 0; i < idx; i++ {
if n.children[i] != nil {
return true
}
}
return false
}
// containsAfter returns true if non-nil values exists between (index,listNodeSize).
func (n *listLeafNode) containsAfter(index int) bool {
idx := index & listNodeMask
for i := idx + 1; i < len(n.children); i++ {
if n.children[i] != nil {
return true
}
}
return false
}
// deleteBefore returns a new node with all elements before index removed.
func (n *listLeafNode) deleteBefore(index int, mutable bool) listNode {
if !n.containsBefore(index) {
return n
}
idx := index & listNodeMask
var other *listLeafNode
if mutable {
other = n
for i := 0; i < idx; i++ {
other.children[i] = nil
}
} else {
other = &listLeafNode{}
copy(other.children[idx:][:], n.children[idx:][:])
}
return other
}
// deleteBefore returns a new node with all elements before index removed.
func (n *listLeafNode) deleteAfter(index int, mutable bool) listNode {
if !n.containsAfter(index) {
return n
}
idx := index & listNodeMask
var other *listLeafNode
if mutable {
other = n
for i := idx + 1; i < len(n.children); i++ {
other.children[i] = nil
}
} else {
other = &listLeafNode{}
copy(other.children[:idx+1][:], n.children[:idx+1][:])
}
return other
}
// ListIterator represents an ordered iterator over a list.
type ListIterator struct {
list *List // source list
index int // current index position
stack [32]listIteratorElem // search stack
depth int // stack depth
}
// Done returns true if no more elements remain in the iterator.
func (itr *ListIterator) Done() bool {
return itr.index < 0 || itr.index >= itr.list.Len()
}
// First positions the iterator on the first index.
// If source list is empty then no change is made.
func (itr *ListIterator) First() {
if itr.list.Len() != 0 {
itr.Seek(0)
}
}
// Last positions the iterator on the last index.
// If source list is empty then no change is made.
func (itr *ListIterator) Last() {
if n := itr.list.Len(); n != 0 {
itr.Seek(n - 1)
}
}
// Seek moves the iterator position to the given index in the list.
// Similar to Go slices, this method will panic if index is below zero or if
// the index is greater than or equal to the list size.
func (itr *ListIterator) Seek(index int) {
// Panic similar to Go slices.
if index < 0 || index >= itr.list.Len() {
panic(fmt.Sprintf("immutable.ListIterator.Seek: index %d out of bounds", index))
}
itr.index = index
// Reset to the bottom of the stack at seek to the correct position.
itr.stack[0] = listIteratorElem{node: itr.list.root}
itr.depth = 0
itr.seek(index)
}
// Next returns the current index and its value & moves the iterator forward.
// Returns an index of -1 if the there are no more elements to return.
func (itr *ListIterator) Next() (index int, value interface{}) {
// Exit immediately if there are no elements remaining.
if itr.Done() {
return -1, nil
}
// Retrieve current index & value.
elem := &itr.stack[itr.depth]
index, value = itr.index, elem.node.(*listLeafNode).children[elem.index]
// Increase index. If index is at the end then return immediately.
itr.index++
if itr.Done() {
return index, value
}
// Move up stack until we find a node that has remaining position ahead.
for ; itr.depth > 0 && itr.stack[itr.depth].index >= listNodeSize-1; itr.depth-- {
}
// Seek to correct position from current depth.
itr.seek(itr.index)
return index, value
}
// Prev returns the current index and value and moves the iterator backward.
// Returns an index of -1 if the there are no more elements to return.
func (itr *ListIterator) Prev() (index int, value interface{}) {
// Exit immediately if there are no elements remaining.
if itr.Done() {
return -1, nil
}
// Retrieve current index & value.
elem := &itr.stack[itr.depth]
index, value = itr.index, elem.node.(*listLeafNode).children[elem.index]
// Decrease index. If index is past the beginning then return immediately.
itr.index--
if itr.Done() {
return index, value
}
// Move up stack until we find a node that has remaining position behind.
for ; itr.depth > 0 && itr.stack[itr.depth].index == 0; itr.depth-- {
}
// Seek to correct position from current depth.
itr.seek(itr.index)
return index, value
}
// seek positions the stack to the given index from the current depth.
// Elements and indexes below the current depth are assumed to be correct.
func (itr *ListIterator) seek(index int) {
// Iterate over each level until we reach a leaf node.
for {
elem := &itr.stack[itr.depth]
elem.index = ((itr.list.origin + index) >> (elem.node.depth() * listNodeBits)) & listNodeMask
switch node := elem.node.(type) {
case *listBranchNode:
child := node.children[elem.index]
itr.stack[itr.depth+1] = listIteratorElem{node: child}
itr.depth++
case *listLeafNode:
return
}
}
}
// listIteratorElem represents the node and it's child index within the stack.
type listIteratorElem struct {
node listNode
index int
}
// Size thresholds for each type of branch node.
const (
maxArrayMapSize = 8
maxBitmapIndexedSize = 16
)
// Segment bit shifts within the map tree.
const (
mapNodeBits = 5
mapNodeSize = 1 << mapNodeBits
mapNodeMask = mapNodeSize - 1
)
// Map represents an immutable hash map implementation. The map uses a Hasher
// to generate hashes and check for equality of key values.
//
// It is implemented as an Hash Array Mapped Trie.
type Map struct {
size int // total number of key/value pairs
root mapNode // root node of trie
hasher Hasher // hasher implementation
}
// NewMap returns a new instance of Map. If hasher is nil, a default hasher
// implementation will automatically be chosen based on the first key added.
// Default hasher implementations only exist for int, string, and byte slice types.
func NewMap(hasher Hasher) *Map {
return &Map{
hasher: hasher,
}
}
// Len returns the number of elements in the map.
func (m *Map) Len() int {
return m.size
}
// clone returns a shallow copy of m.
func (m *Map) clone() *Map {
other := *m
return &other
}
// Get returns the value for a given key and a flag indicating whether the
// key exists. This flag distinguishes a nil value set on a key versus a
// non-existent key in the map.
func (m *Map) Get(key interface{}) (value interface{}, ok bool) {
if m.root == nil {
return nil, false
}
keyHash := m.hasher.Hash(key)
return m.root.get(key, 0, keyHash, m.hasher)
}
// Set returns a map with the key set to the new value. A nil value is allowed.
//
// This function will return a new map even if the updated value is the same as
// the existing value because Map does not track value equality.
func (m *Map) Set(key, value interface{}) *Map {
return m.set(key, value, false)
}
func (m *Map) set(key, value interface{}, mutable bool) *Map {
// Set a hasher on the first value if one does not already exist.
hasher := m.hasher
if hasher == nil {
switch key.(type) {
case int:
hasher = &intHasher{}
case string:
hasher = &stringHasher{}
case []byte:
hasher = &byteSliceHasher{}
default:
panic(fmt.Sprintf("immutable.Map.Set: must set hasher for %T type", key))
}
}
// Generate copy if necessary.
other := m
if !mutable {
other = m.clone()
}
other.hasher = hasher
// If the map is empty, initialize with a simple array node.
if m.root == nil {
other.size = 1
other.root = &mapArrayNode{entries: []mapEntry{{key: key, value: value}}}
return other
}
// Otherwise copy the map and delegate insertion to the root.
// Resized will return true if the key does not currently exist.
var resized bool
other.root = m.root.set(key, value, 0, hasher.Hash(key), hasher, mutable, &resized)
if resized {
other.size++
}
return other
}
// Delete returns a map with the given key removed.
// Removing a non-existent key will cause this method to return the same map.
func (m *Map) Delete(key interface{}) *Map {
return m.delete(key, false)
}
func (m *Map) delete(key interface{}, mutable bool) *Map {
// Return original map if no keys exist.
if m.root == nil {
return m
}
// If the delete did not change the node then return the original map.
var resized bool
newRoot := m.root.delete(key, 0, m.hasher.Hash(key), m.hasher, mutable, &resized)
if !resized {
return m
}
// Generate copy if necessary.
other := m
if !mutable {
other = m.clone()
}
// Return copy of map with new root and decreased size.
other.size = m.size - 1
other.root = newRoot
return other
}
// Iterator returns a new iterator for the map.
func (m *Map) Iterator() *MapIterator {
itr := &MapIterator{m: m}
itr.First()
return itr
}
// MapBuilder represents an efficient builder for creating Maps.
//
// Maps returned from the builder are safe to use even after you continue to
// use the builder. However, for efficiency, you should only retrieve your map
// after you have completed building it.
type MapBuilder struct {
m *Map // current state
mutable bool // if true, next mutation will operate in-place.
}
// NewMapBuilder returns a new instance of MapBuilder to build on a base map.
func NewMapBuilder(m *Map) *MapBuilder {
return &MapBuilder{m: m}
}
// Map returns the current copy of the map.
// The returned map is safe to use even if after the builder continues to be used.
func (b *MapBuilder) Map() *Map {
m := b.m
b.mutable = false
return m
}
// Len returns the number of elements in the underlying map.
func (b *MapBuilder) Len() int {
return b.m.Len()
}
// Get returns the value for the given key.
func (b *MapBuilder) Get(key interface{}) (value interface{}, ok bool) {
return b.m.Get(key)
}
// Set sets the value of the given key. See Map.Set() for additional details.
func (b *MapBuilder) Set(key, value interface{}) {
b.m = b.m.set(key, value, b.mutable)
b.mutable = true
}
// Delete removes the given key. See Map.Delete() for additional details.
func (b *MapBuilder) Delete(key interface{}) {
b.m = b.m.delete(key, b.mutable)
b.mutable = true
}
// mapNode represents any node in the map tree.
type mapNode interface {
get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool)
set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode
delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode
}
var _ mapNode = (*mapArrayNode)(nil)
var _ mapNode = (*mapBitmapIndexedNode)(nil)
var _ mapNode = (*mapHashArrayNode)(nil)
var _ mapNode = (*mapValueNode)(nil)
var _ mapNode = (*mapHashCollisionNode)(nil)
// mapLeafNode represents a node that stores a single key hash at the leaf of the map tree.
type mapLeafNode interface {
mapNode
keyHashValue() uint32
}
var _ mapLeafNode = (*mapValueNode)(nil)
var _ mapLeafNode = (*mapHashCollisionNode)(nil)
// mapArrayNode is a map node that stores key/value pairs in a slice.
// Entries are stored in insertion order. An array node expands into a bitmap
// indexed node once a given threshold size is crossed.
type mapArrayNode struct {
entries []mapEntry
}
// indexOf returns the entry index of the given key. Returns -1 if key not found.
func (n *mapArrayNode) indexOf(key interface{}, h Hasher) int {
for i := range n.entries {
if h.Equal(n.entries[i].key, key) {
return i
}
}
return -1
}
// get returns the value for the given key.
func (n *mapArrayNode) get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool) {
i := n.indexOf(key, h)
if i == -1 {
return nil, false
}
return n.entries[i].value, true
}
// set inserts or updates the value for a given key. If the key is inserted and
// the new size crosses the max size threshold, a bitmap indexed node is returned.
func (n *mapArrayNode) set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
idx := n.indexOf(key, h)
// Mark as resized if the key doesn't exist.
if idx == -1 {
*resized = true
}
// If we are adding and it crosses the max size threshold, expand the node.
// We do this by continually setting the entries to a value node and expanding.
if idx == -1 && len(n.entries) >= maxArrayMapSize {
var node mapNode = newMapValueNode(h.Hash(key), key, value)
for _, entry := range n.entries {
node = node.set(entry.key, entry.value, 0, h.Hash(entry.key), h, false, resized)
}
return node
}
// Update in-place if mutable.
if mutable {
if idx != -1 {
n.entries[idx] = mapEntry{key, value}
} else {
n.entries = append(n.entries, mapEntry{key, value})
}
return n
}
// Update existing entry if a match is found.
// Otherwise append to the end of the element list if it doesn't exist.
var other mapArrayNode
if idx != -1 {
other.entries = make([]mapEntry, len(n.entries))
copy(other.entries, n.entries)
other.entries[idx] = mapEntry{key, value}
} else {
other.entries = make([]mapEntry, len(n.entries)+1)
copy(other.entries, n.entries)
other.entries[len(other.entries)-1] = mapEntry{key, value}
}
return &other
}
// delete removes the given key from the node. Returns the same node if key does
// not exist. Returns a nil node when removing the last entry.
func (n *mapArrayNode) delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
idx := n.indexOf(key, h)
// Return original node if key does not exist.
if idx == -1 {
return n
}
*resized = true
// Return nil if this node will contain no nodes.
if len(n.entries) == 1 {
return nil
}
// Update in-place, if mutable.
if mutable {
copy(n.entries[idx:], n.entries[idx+1:])
n.entries[len(n.entries)-1] = mapEntry{}
n.entries = n.entries[:len(n.entries)-1]
return n
}
// Otherwise create a copy with the given entry removed.
other := &mapArrayNode{entries: make([]mapEntry, len(n.entries)-1)}
copy(other.entries[:idx], n.entries[:idx])
copy(other.entries[idx:], n.entries[idx+1:])
return other
}
// mapBitmapIndexedNode represents a map branch node with a variable number of
// node slots and indexed using a bitmap. Indexes for the node slots are
// calculated by counting the number of set bits before the target bit using popcount.
type mapBitmapIndexedNode struct {
bitmap uint32
nodes []mapNode
}
// get returns the value for the given key.
func (n *mapBitmapIndexedNode) get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool) {
bit := uint32(1) << ((keyHash >> shift) & mapNodeMask)
if (n.bitmap & bit) == 0 {
return nil, false
}
child := n.nodes[bits.OnesCount32(n.bitmap&(bit-1))]
return child.get(key, shift+mapNodeBits, keyHash, h)
}
// set inserts or updates the value for the given key. If a new key is inserted
// and the size crosses the max size threshold then a hash array node is returned.
func (n *mapBitmapIndexedNode) set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
// Extract the index for the bit segment of the key hash.
keyHashFrag := (keyHash >> shift) & mapNodeMask
// Determine the bit based on the hash index.
bit := uint32(1) << keyHashFrag
exists := (n.bitmap & bit) != 0
// Mark as resized if the key doesn't exist.
if !exists {
*resized = true
}
// Find index of node based on popcount of bits before it.
idx := bits.OnesCount32(n.bitmap & (bit - 1))
// If the node already exists, delegate set operation to it.
// If the node doesn't exist then create a simple value leaf node.
var newNode mapNode
if exists {
newNode = n.nodes[idx].set(key, value, shift+mapNodeBits, keyHash, h, mutable, resized)
} else {
newNode = newMapValueNode(keyHash, key, value)
}
// Convert to a hash-array node once we exceed the max bitmap size.
// Copy each node based on their bit position within the bitmap.
if !exists && len(n.nodes) > maxBitmapIndexedSize {
var other mapHashArrayNode
for i := uint(0); i < uint(len(other.nodes)); i++ {
if n.bitmap&(uint32(1)<<i) != 0 {
other.nodes[i] = n.nodes[other.count]
other.count++
}
}
other.nodes[keyHashFrag] = newNode
other.count++
return &other
}
// Update in-place if mutable.
if mutable {
if exists {
n.nodes[idx] = newNode
} else {
n.bitmap |= bit
n.nodes = append(n.nodes, nil)
copy(n.nodes[idx+1:], n.nodes[idx:])
n.nodes[idx] = newNode
}
return n
}
// If node exists at given slot then overwrite it with new node.
// Otherwise expand the node list and insert new node into appropriate position.
other := &mapBitmapIndexedNode{bitmap: n.bitmap | bit}
if exists {
other.nodes = make([]mapNode, len(n.nodes))
copy(other.nodes, n.nodes)
other.nodes[idx] = newNode
} else {
other.nodes = make([]mapNode, len(n.nodes)+1)
copy(other.nodes, n.nodes[:idx])
other.nodes[idx] = newNode
copy(other.nodes[idx+1:], n.nodes[idx:])
}
return other
}
// delete removes the key from the tree. If the key does not exist then the
// original node is returned. If removing the last child node then a nil is
// returned. Note that shrinking the node will not convert it to an array node.
func (n *mapBitmapIndexedNode) delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
bit := uint32(1) << ((keyHash >> shift) & mapNodeMask)
// Return original node if key does not exist.
if (n.bitmap & bit) == 0 {
return n
}
// Find index of node based on popcount of bits before it.
idx := bits.OnesCount32(n.bitmap & (bit - 1))
// Delegate delete to child node.
child := n.nodes[idx]
newChild := child.delete(key, shift+mapNodeBits, keyHash, h, mutable, resized)
// Return original node if key doesn't exist in child.
if !*resized {
return n
}
// Remove if returned child has been deleted.
if newChild == nil {
// If we won't have any children then return nil.
if len(n.nodes) == 1 {
return nil
}
// Update in-place if mutable.
if mutable {
n.bitmap ^= bit
copy(n.nodes[idx:], n.nodes[idx+1:])
n.nodes[len(n.nodes)-1] = nil
n.nodes = n.nodes[:len(n.nodes)-1]
return n
}
// Return copy with bit removed from bitmap and node removed from node list.
other := &mapBitmapIndexedNode{bitmap: n.bitmap ^ bit, nodes: make([]mapNode, len(n.nodes)-1)}
copy(other.nodes[:idx], n.nodes[:idx])
copy(other.nodes[idx:], n.nodes[idx+1:])
return other
}
// Generate copy, if necessary.
other := n
if !mutable {
other = &mapBitmapIndexedNode{bitmap: n.bitmap, nodes: make([]mapNode, len(n.nodes))}
copy(other.nodes, n.nodes)
}
// Update child.
other.nodes[idx] = newChild
return other
}
// mapHashArrayNode is a map branch node that stores nodes in a fixed length
// array. Child nodes are indexed by their index bit segment for the current depth.
type mapHashArrayNode struct {
count uint // number of set nodes
nodes [mapNodeSize]mapNode // child node slots, may contain empties
}
// clone returns a shallow copy of n.
func (n *mapHashArrayNode) clone() *mapHashArrayNode {
other := *n
return &other
}
// get returns the value for the given key.
func (n *mapHashArrayNode) get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool) {
node := n.nodes[(keyHash>>shift)&mapNodeMask]
if node == nil {
return nil, false
}
return node.get(key, shift+mapNodeBits, keyHash, h)
}
// set returns a node with the value set for the given key.
func (n *mapHashArrayNode) set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
idx := (keyHash >> shift) & mapNodeMask
node := n.nodes[idx]
// If node at index doesn't exist, create a simple value leaf node.
// Otherwise delegate set to child node.
var newNode mapNode
if node == nil {
*resized = true
newNode = newMapValueNode(keyHash, key, value)
} else {
newNode = node.set(key, value, shift+mapNodeBits, keyHash, h, mutable, resized)
}
// Generate copy, if necessary.
other := n
if !mutable {
other = n.clone()
}
// Update child node (and update size, if new).
if node == nil {
other.count++
}
other.nodes[idx] = newNode
return other
}
// delete returns a node with the given key removed. Returns the same node if
// the key does not exist. If node shrinks to within bitmap-indexed size then
// converts to a bitmap-indexed node.
func (n *mapHashArrayNode) delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
idx := (keyHash >> shift) & mapNodeMask
node := n.nodes[idx]
// Return original node if child is not found.
if node == nil {
return n
}
// Return original node if child is unchanged.
newNode := node.delete(key, shift+mapNodeBits, keyHash, h, mutable, resized)
if !*resized {
return n
}
// If we remove a node and drop below a threshold, convert back to bitmap indexed node.
if newNode == nil && n.count <= maxBitmapIndexedSize {
other := &mapBitmapIndexedNode{nodes: make([]mapNode, 0, n.count-1)}
for i, child := range n.nodes {
if child != nil && uint32(i) != idx {
other.bitmap |= 1 << uint(i)
other.nodes = append(other.nodes, child)
}
}
return other
}
// Generate copy, if necessary.
other := n
if !mutable {
other = n.clone()
}
// Return copy of node with child updated.
other.nodes[idx] = newNode
if newNode == nil {
other.count--
}
return other
}
// mapValueNode represents a leaf node with a single key/value pair.
// A value node can be converted to a hash collision leaf node if a different
// key with the same keyHash is inserted.
type mapValueNode struct {
keyHash uint32
key interface{}
value interface{}
}
// newMapValueNode returns a new instance of mapValueNode.
func newMapValueNode(keyHash uint32, key, value interface{}) *mapValueNode {
return &mapValueNode{
keyHash: keyHash,
key: key,
value: value,
}
}
// keyHashValue returns the key hash for this node.
func (n *mapValueNode) keyHashValue() uint32 {
return n.keyHash
}
// get returns the value for the given key.
func (n *mapValueNode) get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool) {
if !h.Equal(n.key, key) {
return nil, false
}
return n.value, true
}
// set returns a new node with the new value set for the key. If the key equals
// the node's key then a new value node is returned. If key is not equal to the
// node's key but has the same hash then a hash collision node is returned.
// Otherwise the nodes are merged into a branch node.
func (n *mapValueNode) set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
// If the keys match then return a new value node overwriting the value.
if h.Equal(n.key, key) {
// Update in-place if mutable.
if mutable {
n.value = value
return n
}
// Otherwise return a new copy.
return newMapValueNode(n.keyHash, key, value)
}
*resized = true
// Recursively merge nodes together if key hashes are different.
if n.keyHash != keyHash {
return mergeIntoNode(n, shift, keyHash, key, value)
}
// Merge into collision node if hash matches.
return &mapHashCollisionNode{keyHash: keyHash, entries: []mapEntry{
{key: n.key, value: n.value},
{key: key, value: value},
}}
}
// delete returns nil if the key matches the node's key. Otherwise returns the original node.
func (n *mapValueNode) delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
// Return original node if the keys do not match.
if !h.Equal(n.key, key) {
return n
}
// Otherwise remove the node if keys do match.
*resized = true
return nil
}
// mapHashCollisionNode represents a leaf node that contains two or more key/value
// pairs with the same key hash. Single pairs for a hash are stored as value nodes.
type mapHashCollisionNode struct {
keyHash uint32 // key hash for all entries
entries []mapEntry
}
// keyHashValue returns the key hash for all entries on the node.
func (n *mapHashCollisionNode) keyHashValue() uint32 {
return n.keyHash
}
// indexOf returns the index of the entry for the given key.
// Returns -1 if the key does not exist in the node.
func (n *mapHashCollisionNode) indexOf(key interface{}, h Hasher) int {
for i := range n.entries {
if h.Equal(n.entries[i].key, key) {
return i
}
}
return -1
}
// get returns the value for the given key.
func (n *mapHashCollisionNode) get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool) {
for i := range n.entries {
if h.Equal(n.entries[i].key, key) {
return n.entries[i].value, true
}
}
return nil, false
}
// set returns a copy of the node with key set to the given value.
func (n *mapHashCollisionNode) set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
// Merge node with key/value pair if this is not a hash collision.
if n.keyHash != keyHash {
*resized = true
return mergeIntoNode(n, shift, keyHash, key, value)
}
// Update in-place if mutable.
if mutable {
if idx := n.indexOf(key, h); idx == -1 {
*resized = true
n.entries = append(n.entries, mapEntry{key, value})
} else {
n.entries[idx] = mapEntry{key, value}
}
return n
}
// Append to end of node if key doesn't exist & mark resized.
// Otherwise copy nodes and overwrite at matching key index.
other := &mapHashCollisionNode{keyHash: n.keyHash}
if idx := n.indexOf(key, h); idx == -1 {
*resized = true
other.entries = make([]mapEntry, len(n.entries)+1)
copy(other.entries, n.entries)
other.entries[len(other.entries)-1] = mapEntry{key, value}
} else {
other.entries = make([]mapEntry, len(n.entries))
copy(other.entries, n.entries)
other.entries[idx] = mapEntry{key, value}
}
return other
}
// delete returns a node with the given key deleted. Returns the same node if
// the key does not exist. If removing the key would shrink the node to a single
// entry then a value node is returned.
func (n *mapHashCollisionNode) delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
idx := n.indexOf(key, h)
// Return original node if key is not found.
if idx == -1 {
return n
}
// Mark as resized if key exists.
*resized = true
// Convert to value node if we move to one entry.
if len(n.entries) == 2 {
return &mapValueNode{
keyHash: n.keyHash,
key: n.entries[idx^1].key,
value: n.entries[idx^1].value,
}
}
// Remove entry in-place if mutable.
if mutable {
copy(n.entries[idx:], n.entries[idx+1:])
n.entries[len(n.entries)-1] = mapEntry{}
n.entries = n.entries[:len(n.entries)-1]
return n
}
// Return copy without entry if immutable.
other := &mapHashCollisionNode{keyHash: n.keyHash, entries: make([]mapEntry, len(n.entries)-1)}
copy(other.entries[:idx], n.entries[:idx])
copy(other.entries[idx:], n.entries[idx+1:])
return other
}
// mergeIntoNode merges a key/value pair into an existing node.
// Caller must verify that node's keyHash is not equal to keyHash.
func mergeIntoNode(node mapLeafNode, shift uint, keyHash uint32, key, value interface{}) mapNode {
idx1 := (node.keyHashValue() >> shift) & mapNodeMask
idx2 := (keyHash >> shift) & mapNodeMask
// Recursively build branch nodes to combine the node and its key.
other := &mapBitmapIndexedNode{bitmap: (1 << idx1) | (1 << idx2)}
if idx1 == idx2 {
other.nodes = []mapNode{mergeIntoNode(node, shift+mapNodeBits, keyHash, key, value)}
} else {
if newNode := newMapValueNode(keyHash, key, value); idx1 < idx2 {
other.nodes = []mapNode{node, newNode}
} else {
other.nodes = []mapNode{newNode, node}
}
}
return other
}
// mapEntry represents a single key/value pair.
type mapEntry struct {
key interface{}
value interface{}
}
// MapIterator represents an iterator over a map's key/value pairs. Although
// map keys are not sorted, the iterator's order is deterministic.
type MapIterator struct {
m *Map // source map
stack [32]mapIteratorElem // search stack
depth int // stack depth
}
// Done returns true if no more elements remain in the iterator.
func (itr *MapIterator) Done() bool {
return itr.depth == -1
}
// First resets the iterator to the first key/value pair.
func (itr *MapIterator) First() {
// Exit immediately if the map is empty.
if itr.m.root == nil {
itr.depth = -1
return
}
// Initialize the stack to the left most element.
itr.stack[0] = mapIteratorElem{node: itr.m.root}
itr.depth = 0
itr.first()
}
// Next returns the next key/value pair. Returns a nil key when no elements remain.
func (itr *MapIterator) Next() (key, value interface{}) {
// Return nil key if iteration is done.
if itr.Done() {
return nil, nil
}
// Retrieve current index & value. Current node is always a leaf.
elem := &itr.stack[itr.depth]
switch node := elem.node.(type) {
case *mapArrayNode:
entry := &node.entries[elem.index]
key, value = entry.key, entry.value
case *mapValueNode:
key, value = node.key, node.value
case *mapHashCollisionNode:
entry := &node.entries[elem.index]
key, value = entry.key, entry.value
}
// Move up stack until we find a node that has remaining position ahead
// and move that element forward by one.
itr.next()
return key, value
}
// next moves to the next available key.
func (itr *MapIterator) next() {
for ; itr.depth >= 0; itr.depth-- {
elem := &itr.stack[itr.depth]
switch node := elem.node.(type) {
case *mapArrayNode:
if elem.index < len(node.entries)-1 {
elem.index++
return
}
case *mapBitmapIndexedNode:
if elem.index < len(node.nodes)-1 {
elem.index++
itr.stack[itr.depth+1].node = node.nodes[elem.index]
itr.depth++
itr.first()
return
}
case *mapHashArrayNode:
for i := elem.index + 1; i < len(node.nodes); i++ {
if node.nodes[i] != nil {
elem.index = i
itr.stack[itr.depth+1].node = node.nodes[elem.index]
itr.depth++
itr.first()
return
}
}
case *mapValueNode:
continue // always the last value, traverse up
case *mapHashCollisionNode:
if elem.index < len(node.entries)-1 {
elem.index++
return
}
}
}
}
// first positions the stack left most index.
// Elements and indexes at and below the current depth are assumed to be correct.
func (itr *MapIterator) first() {
for ; ; itr.depth++ {
elem := &itr.stack[itr.depth]
switch node := elem.node.(type) {
case *mapBitmapIndexedNode:
elem.index = 0
itr.stack[itr.depth+1].node = node.nodes[0]
case *mapHashArrayNode:
for i := 0; i < len(node.nodes); i++ {
if node.nodes[i] != nil { // find first node
elem.index = i
itr.stack[itr.depth+1].node = node.nodes[i]
break
}
}
default: // *mapArrayNode, mapLeafNode
elem.index = 0
return
}
}
}
// mapIteratorElem represents a node/index pair in the MapIterator stack.
type mapIteratorElem struct {
node mapNode
index int
}
// Sorted map child node limit size.
const (
sortedMapNodeSize = 32
)
// SortedMap represents a map of key/value pairs sorted by key. The sort order
// is determined by the Comparer used by the map.
//
// This map is implemented as a B+tree.
type SortedMap struct {
size int // total number of key/value pairs
root sortedMapNode // root of b+tree
comparer Comparer
}
// NewSortedMap returns a new instance of SortedMap. If comparer is nil then
// a default comparer is set after the first key is inserted. Default comparers
// exist for int, string, and byte slice keys.
func NewSortedMap(comparer Comparer) *SortedMap {
return &SortedMap{
comparer: comparer,
}
}
// Len returns the number of elements in the sorted map.
func (m *SortedMap) Len() int {
return m.size
}
// Get returns the value for a given key and a flag indicating if the key is set.
// The flag can be used to distinguish between a nil-set key versus an unset key.
func (m *SortedMap) Get(key interface{}) (interface{}, bool) {
if m.root == nil {
return nil, false
}
return m.root.get(key, m.comparer)
}
// Set returns a copy of the map with the key set to the given value.
func (m *SortedMap) Set(key, value interface{}) *SortedMap {
return m.set(key, value, false)
}
func (m *SortedMap) set(key, value interface{}, mutable bool) *SortedMap {
// Set a comparer on the first value if one does not already exist.
comparer := m.comparer
if comparer == nil {
switch key.(type) {
case int:
comparer = &intComparer{}
case string:
comparer = &stringComparer{}
case []byte:
comparer = &byteSliceComparer{}
default:
panic(fmt.Sprintf("immutable.SortedMap.Set: must set comparer for %T type", key))
}
}
// Create copy, if necessary.
other := m
if !mutable {
other = m.clone()
}
other.comparer = comparer
// If no values are set then initialize with a leaf node.
if m.root == nil {
other.size = 1
other.root = &sortedMapLeafNode{entries: []mapEntry{{key: key, value: value}}}
return other
}
// Otherwise delegate to root node.
// If a split occurs then grow the tree from the root.
var resized bool
newRoot, splitNode := m.root.set(key, value, comparer, mutable, &resized)
if splitNode != nil {
newRoot = newSortedMapBranchNode(newRoot, splitNode)
}
// Update root and size (if resized).
other.size = m.size
other.root = newRoot
if resized {
other.size++
}
return other
}
// Delete returns a copy of the map with the key removed.
// Returns the original map if key does not exist.
func (m *SortedMap) Delete(key interface{}) *SortedMap {
return m.delete(key, false)
}
func (m *SortedMap) delete(key interface{}, mutable bool) *SortedMap {
// Return original map if no keys exist.
if m.root == nil {
return m
}
// If the delete did not change the node then return the original map.
var resized bool
newRoot := m.root.delete(key, m.comparer, mutable, &resized)
if !resized {
return m
}
// Create copy, if necessary.
other := m
if !mutable {
other = m.clone()
}
// Update root and size.
other.size = m.size - 1
other.root = newRoot
return other
}
// clone returns a shallow copy of m.
func (m *SortedMap) clone() *SortedMap {
other := *m
return &other
}
// Iterator returns a new iterator for this map positioned at the first key.
func (m *SortedMap) Iterator() *SortedMapIterator {
itr := &SortedMapIterator{m: m}
itr.First()
return itr
}
// SortedMapBuilder represents an efficient builder for creating sorted maps.
//
// Maps returned from the builder are safe to use even after you continue to
// use the builder. However, for efficiency, you should only retrieve your map
// after you have completed building it.
type SortedMapBuilder struct {
m *SortedMap // current state
mutable bool // if true, next mutation will operate in-place.
}
// NewSortedMapBuilder returns a new instance of SortedMapBuilder to build on a base map.
func NewSortedMapBuilder(m *SortedMap) *SortedMapBuilder {
return &SortedMapBuilder{m: m}
}
// SortedMap returns the current copy of the map.
// The returned map is safe to use even if after the builder continues to be used.
func (b *SortedMapBuilder) Map() *SortedMap {
m := b.m
b.mutable = false
return m
}
// Len returns the number of elements in the underlying map.
func (b *SortedMapBuilder) Len() int {
return b.m.Len()
}
// Get returns the value for the given key.
func (b *SortedMapBuilder) Get(key interface{}) (value interface{}, ok bool) {
return b.m.Get(key)
}
// Set sets the value of the given key. See SortedMap.Set() for additional details.
func (b *SortedMapBuilder) Set(key, value interface{}) {
b.m = b.m.set(key, value, b.mutable)
b.mutable = true
}
// Delete removes the given key. See SortedMap.Delete() for additional details.
func (b *SortedMapBuilder) Delete(key interface{}) {
b.m = b.m.delete(key, b.mutable)
b.mutable = true
}
// sortedMapNode represents a branch or leaf node in the sorted map.
type sortedMapNode interface {
minKey() interface{}
indexOf(key interface{}, c Comparer) int
get(key interface{}, c Comparer) (value interface{}, ok bool)
set(key, value interface{}, c Comparer, mutable bool, resized *bool) (sortedMapNode, sortedMapNode)
delete(key interface{}, c Comparer, mutable bool, resized *bool) sortedMapNode
}
var _ sortedMapNode = (*sortedMapBranchNode)(nil)
var _ sortedMapNode = (*sortedMapLeafNode)(nil)
// sortedMapBranchNode represents a branch in the sorted map.
type sortedMapBranchNode struct {
elems []sortedMapBranchElem
}
// newSortedMapBranchNode returns a new branch node with the given child nodes.
func newSortedMapBranchNode(children ...sortedMapNode) *sortedMapBranchNode {
// Fetch min keys for every child.
elems := make([]sortedMapBranchElem, len(children))
for i, child := range children {
elems[i] = sortedMapBranchElem{
key: child.minKey(),
node: child,
}
}
return &sortedMapBranchNode{elems: elems}
}
// minKey returns the lowest key stored in this node's tree.
func (n *sortedMapBranchNode) minKey() interface{} {
return n.elems[0].node.minKey()
}
// indexOf returns the index of the key within the child nodes.
func (n *sortedMapBranchNode) indexOf(key interface{}, c Comparer) int {
if idx := sort.Search(len(n.elems), func(i int) bool { return c.Compare(n.elems[i].key, key) == 1 }); idx > 0 {
return idx - 1
}
return 0
}
// get returns the value for the given key.
func (n *sortedMapBranchNode) get(key interface{}, c Comparer) (value interface{}, ok bool) {
idx := n.indexOf(key, c)
return n.elems[idx].node.get(key, c)
}
// set returns a copy of the node with the key set to the given value.
func (n *sortedMapBranchNode) set(key, value interface{}, c Comparer, mutable bool, resized *bool) (sortedMapNode, sortedMapNode) {
idx := n.indexOf(key, c)
// Delegate insert to child node.
newNode, splitNode := n.elems[idx].node.set(key, value, c, mutable, resized)
// Update in-place, if mutable.
if mutable {
n.elems[idx] = sortedMapBranchElem{key: newNode.minKey(), node: newNode}
if splitNode != nil {
n.elems = append(n.elems, sortedMapBranchElem{})
copy(n.elems[idx+1:], n.elems[idx:])
n.elems[idx+1] = sortedMapBranchElem{key: splitNode.minKey(), node: splitNode}
}
// If the child splits and we have no more room then we split too.
if len(n.elems) > sortedMapNodeSize {
splitIdx := len(n.elems) / 2
newNode := &sortedMapBranchNode{elems: n.elems[:splitIdx:splitIdx]}
splitNode := &sortedMapBranchNode{elems: n.elems[splitIdx:]}
return newNode, splitNode
}
return n, nil
}
// If no split occurs, copy branch and update keys.
// If the child splits, insert new key/child into copy of branch.
var other sortedMapBranchNode
if splitNode == nil {
other.elems = make([]sortedMapBranchElem, len(n.elems))
copy(other.elems, n.elems)
other.elems[idx] = sortedMapBranchElem{
key: newNode.minKey(),
node: newNode,
}
} else {
other.elems = make([]sortedMapBranchElem, len(n.elems)+1)
copy(other.elems[:idx], n.elems[:idx])
copy(other.elems[idx+1:], n.elems[idx:])
other.elems[idx] = sortedMapBranchElem{
key: newNode.minKey(),
node: newNode,
}
other.elems[idx+1] = sortedMapBranchElem{
key: splitNode.minKey(),
node: splitNode,
}
}
// If the child splits and we have no more room then we split too.
if len(other.elems) > sortedMapNodeSize {
splitIdx := len(other.elems) / 2
newNode := &sortedMapBranchNode{elems: other.elems[:splitIdx:splitIdx]}
splitNode := &sortedMapBranchNode{elems: other.elems[splitIdx:]}
return newNode, splitNode
}
// Otherwise return the new branch node with the updated entry.
return &other, nil
}
// delete returns a node with the key removed. Returns the same node if the key
// does not exist. Returns nil if all child nodes are removed.
func (n *sortedMapBranchNode) delete(key interface{}, c Comparer, mutable bool, resized *bool) sortedMapNode {
idx := n.indexOf(key, c)
// Return original node if child has not changed.
newNode := n.elems[idx].node.delete(key, c, mutable, resized)
if !*resized {
return n
}
// Remove child if it is now nil.
if newNode == nil {
// If this node will become empty then simply return nil.
if len(n.elems) == 1 {
return nil
}
// If mutable, update in-place.
if mutable {
copy(n.elems[idx:], n.elems[idx+1:])
n.elems[len(n.elems)-1] = sortedMapBranchElem{}
n.elems = n.elems[:len(n.elems)-1]
return n
}
// Return a copy without the given node.
other := &sortedMapBranchNode{elems: make([]sortedMapBranchElem, len(n.elems)-1)}
copy(other.elems[:idx], n.elems[:idx])
copy(other.elems[idx:], n.elems[idx+1:])
return other
}
// If mutable, update in-place.
if mutable {
n.elems[idx] = sortedMapBranchElem{key: newNode.minKey(), node: newNode}
return n
}
// Return a copy with the updated node.
other := &sortedMapBranchNode{elems: make([]sortedMapBranchElem, len(n.elems))}
copy(other.elems, n.elems)
other.elems[idx] = sortedMapBranchElem{
key: newNode.minKey(),
node: newNode,
}
return other
}
type sortedMapBranchElem struct {
key interface{}
node sortedMapNode
}
// sortedMapLeafNode represents a leaf node in the sorted map.
type sortedMapLeafNode struct {
entries []mapEntry
}
// minKey returns the first key stored in this node.
func (n *sortedMapLeafNode) minKey() interface{} {
return n.entries[0].key
}
// indexOf returns the index of the given key.
func (n *sortedMapLeafNode) indexOf(key interface{}, c Comparer) int {
return sort.Search(len(n.entries), func(i int) bool {
return c.Compare(n.entries[i].key, key) != -1 // GTE
})
}
// get returns the value of the given key.
func (n *sortedMapLeafNode) get(key interface{}, c Comparer) (value interface{}, ok bool) {
idx := n.indexOf(key, c)
// If the index is beyond the entry count or the key is not equal then return 'not found'.
if idx == len(n.entries) || c.Compare(n.entries[idx].key, key) != 0 {
return nil, false
}
// If the key matches then return its value.
return n.entries[idx].value, true
}
// set returns a copy of node with the key set to the given value. If the update
// causes the node to grow beyond the maximum size then it is split in two.
func (n *sortedMapLeafNode) set(key, value interface{}, c Comparer, mutable bool, resized *bool) (sortedMapNode, sortedMapNode) {
// Find the insertion index for the key.
idx := n.indexOf(key, c)
exists := idx < len(n.entries) && c.Compare(n.entries[idx].key, key) == 0
// Update in-place, if mutable.
if mutable {
if !exists {
*resized = true
n.entries = append(n.entries, mapEntry{})
copy(n.entries[idx+1:], n.entries[idx:])
}
n.entries[idx] = mapEntry{key: key, value: value}
// If the key doesn't exist and we exceed our max allowed values then split.
if len(n.entries) > sortedMapNodeSize {
splitIdx := len(n.entries) / 2
newNode := &sortedMapLeafNode{entries: n.entries[:splitIdx:splitIdx]}
splitNode := &sortedMapLeafNode{entries: n.entries[splitIdx:]}
return newNode, splitNode
}
return n, nil
}
// If the key matches then simply return a copy with the entry overridden.
// If there is no match then insert new entry and mark as resized.
var newEntries []mapEntry
if exists {
newEntries = make([]mapEntry, len(n.entries))
copy(newEntries, n.entries)
newEntries[idx] = mapEntry{key: key, value: value}
} else {
*resized = true
newEntries = make([]mapEntry, len(n.entries)+1)
copy(newEntries[:idx], n.entries[:idx])
newEntries[idx] = mapEntry{key: key, value: value}
copy(newEntries[idx+1:], n.entries[idx:])
}
// If the key doesn't exist and we exceed our max allowed values then split.
if len(newEntries) > sortedMapNodeSize {
splitIdx := len(newEntries) / 2
newNode := &sortedMapLeafNode{entries: newEntries[:splitIdx:splitIdx]}
splitNode := &sortedMapLeafNode{entries: newEntries[splitIdx:]}
return newNode, splitNode
}
// Otherwise return the new leaf node with the updated entry.
return &sortedMapLeafNode{entries: newEntries}, nil
}
// delete returns a copy of node with key removed. Returns the original node if
// the key does not exist. Returns nil if the removed key is the last remaining key.
func (n *sortedMapLeafNode) delete(key interface{}, c Comparer, mutable bool, resized *bool) sortedMapNode {
idx := n.indexOf(key, c)
// Return original node if key is not found.
if idx >= len(n.entries) || c.Compare(n.entries[idx].key, key) != 0 {
return n
}
*resized = true
// If this is the last entry then return nil.
if len(n.entries) == 1 {
return nil
}
// Update in-place, if mutable.
if mutable {
copy(n.entries[idx:], n.entries[idx+1:])
n.entries[len(n.entries)-1] = mapEntry{}
n.entries = n.entries[:len(n.entries)-1]
return n
}
// Return copy of node with entry removed.
other := &sortedMapLeafNode{entries: make([]mapEntry, len(n.entries)-1)}
copy(other.entries[:idx], n.entries[:idx])
copy(other.entries[idx:], n.entries[idx+1:])
return other
}
// SortedMapIterator represents an iterator over a sorted map.
// Iteration can occur in natural or reverse order based on use of Next() or Prev().
type SortedMapIterator struct {
m *SortedMap // source map
stack [32]sortedMapIteratorElem // search stack
depth int // stack depth
}
// Done returns true if no more key/value pairs remain in the iterator.
func (itr *SortedMapIterator) Done() bool {
return itr.depth == -1
}
// First moves the iterator to the first key/value pair.
func (itr *SortedMapIterator) First() {
if itr.m.root == nil {
itr.depth = -1
return
}
itr.stack[0] = sortedMapIteratorElem{node: itr.m.root}
itr.depth = 0
itr.first()
}
// Last moves the iterator to the last key/value pair.
func (itr *SortedMapIterator) Last() {
if itr.m.root == nil {
itr.depth = -1
return
}
itr.stack[0] = sortedMapIteratorElem{node: itr.m.root}
itr.depth = 0
itr.last()
}
// Seek moves the iterator position to the given key in the map.
// If the key does not exist then the next key is used. If no more keys exist
// then the iteartor is marked as done.
func (itr *SortedMapIterator) Seek(key interface{}) {
if itr.m.root == nil {
itr.depth = -1
return
}
itr.stack[0] = sortedMapIteratorElem{node: itr.m.root}
itr.depth = 0
itr.seek(key)
}
// Next returns the current key/value pair and moves the iterator forward.
// Returns a nil key if the there are no more elements to return.
func (itr *SortedMapIterator) Next() (key, value interface{}) {
// Return nil key if iteration is complete.
if itr.Done() {
return nil, nil
}
// Retrieve current key/value pair.
leafElem := &itr.stack[itr.depth]
leafNode := leafElem.node.(*sortedMapLeafNode)
leafEntry := &leafNode.entries[leafElem.index]
key, value = leafEntry.key, leafEntry.value
// Move to the next available key/value pair.
itr.next()
// Only occurs when iterator is done.
return key, value
}
// next moves to the next key. If no keys are after then depth is set to -1.
func (itr *SortedMapIterator) next() {
for ; itr.depth >= 0; itr.depth-- {
elem := &itr.stack[itr.depth]
switch node := elem.node.(type) {
case *sortedMapLeafNode:
if elem.index < len(node.entries)-1 {
elem.index++
return
}
case *sortedMapBranchNode:
if elem.index < len(node.elems)-1 {
elem.index++
itr.stack[itr.depth+1].node = node.elems[elem.index].node
itr.depth++
itr.first()
return
}
}
}
}
// Prev returns the current key/value pair and moves the iterator backward.
// Returns a nil key if the there are no more elements to return.
func (itr *SortedMapIterator) Prev() (key, value interface{}) {
// Return nil key if iteration is complete.
if itr.Done() {
return nil, nil
}
// Retrieve current key/value pair.
leafElem := &itr.stack[itr.depth]
leafNode := leafElem.node.(*sortedMapLeafNode)
leafEntry := &leafNode.entries[leafElem.index]
key, value = leafEntry.key, leafEntry.value
itr.prev()
return key, value
}
// prev moves to the previous key. If no keys are before then depth is set to -1.
func (itr *SortedMapIterator) prev() {
for ; itr.depth >= 0; itr.depth-- {
elem := &itr.stack[itr.depth]
switch node := elem.node.(type) {
case *sortedMapLeafNode:
if elem.index > 0 {
elem.index--
return
}
case *sortedMapBranchNode:
if elem.index > 0 {
elem.index--
itr.stack[itr.depth+1].node = node.elems[elem.index].node
itr.depth++
itr.last()
return
}
}
}
}
// first positions the stack to the leftmost key from the current depth.
// Elements and indexes below the current depth are assumed to be correct.
func (itr *SortedMapIterator) first() {
for {
elem := &itr.stack[itr.depth]
elem.index = 0
switch node := elem.node.(type) {
case *sortedMapBranchNode:
itr.stack[itr.depth+1] = sortedMapIteratorElem{node: node.elems[elem.index].node}
itr.depth++
case *sortedMapLeafNode:
return
}
}
}
// last positions the stack to the rightmost key from the current depth.
// Elements and indexes below the current depth are assumed to be correct.
func (itr *SortedMapIterator) last() {
for {
elem := &itr.stack[itr.depth]
switch node := elem.node.(type) {
case *sortedMapBranchNode:
elem.index = len(node.elems) - 1
itr.stack[itr.depth+1] = sortedMapIteratorElem{node: node.elems[elem.index].node}
itr.depth++
case *sortedMapLeafNode:
elem.index = len(node.entries) - 1
return
}
}
}
// seek positions the stack to the given key from the current depth.
// Elements and indexes below the current depth are assumed to be correct.
func (itr *SortedMapIterator) seek(key interface{}) {
for {
elem := &itr.stack[itr.depth]
elem.index = elem.node.indexOf(key, itr.m.comparer)
switch node := elem.node.(type) {
case *sortedMapBranchNode:
itr.stack[itr.depth+1] = sortedMapIteratorElem{node: node.elems[elem.index].node}
itr.depth++
case *sortedMapLeafNode:
if elem.index == len(node.entries) {
itr.next()
}
return
}
}
}
// sortedMapIteratorElem represents node/index pair in the SortedMapIterator stack.
type sortedMapIteratorElem struct {
node sortedMapNode
index int
}
// Hasher hashes keys and checks them for equality.
type Hasher interface {
// Computes a 32-bit hash for key.
Hash(key interface{}) uint32
// Returns true if a and b are equal.
Equal(a, b interface{}) bool
}
// intHasher implements Hasher for int keys.
type intHasher struct{}
// Hash returns a hash for key.
func (h *intHasher) Hash(key interface{}) uint32 {
return hashUint64(uint64(key.(int)))
}
// Equal returns true if a is equal to b. Otherwise returns false.
// Panics if a and b are not ints.
func (h *intHasher) Equal(a, b interface{}) bool {
return a.(int) == b.(int)
}
// stringHasher implements Hasher for string keys.
type stringHasher struct{}
// Hash returns a hash for value.
func (h *stringHasher) Hash(value interface{}) uint32 {
var hash uint32
for i, value := 0, value.(string); i < len(value); i++ {
hash = 31*hash + uint32(value[i])
}
return hash
}
// Equal returns true if a is equal to b. Otherwise returns false.
// Panics if a and b are not strings.
func (h *stringHasher) Equal(a, b interface{}) bool {
return a.(string) == b.(string)
}
// byteSliceHasher implements Hasher for string keys.
type byteSliceHasher struct{}
// Hash returns a hash for value.
func (h *byteSliceHasher) Hash(value interface{}) uint32 {
var hash uint32
for i, value := 0, value.([]byte); i < len(value); i++ {
hash = 31*hash + uint32(value[i])
}
return hash
}
// Equal returns true if a is equal to b. Otherwise returns false.
// Panics if a and b are not byte slices.
func (h *byteSliceHasher) Equal(a, b interface{}) bool {
return bytes.Equal(a.([]byte), b.([]byte))
}
// hashUint64 returns a 32-bit hash for a 64-bit value.
func hashUint64(value uint64) uint32 {
hash := value
for value > 0xffffffff {
value /= 0xffffffff
hash ^= value
}
return uint32(hash)
}
// Comparer allows the comparison of two keys for the purpose of sorting.
type Comparer interface {
// Returns -1 if a is less than b, returns 1 if a is greater than b,
// and returns 0 if a is equal to b.
Compare(a, b interface{}) int
}
// intComparer compares two integers. Implements Comparer.
type intComparer struct{}
// Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
// returns 0 if a is equal to b. Panic if a or b is not an int.
func (c *intComparer) Compare(a, b interface{}) int {
if i, j := a.(int), b.(int); i < j {
return -1
} else if i > j {
return 1
}
return 0
}
// stringComparer compares two strings. Implements Comparer.
type stringComparer struct{}
// Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
// returns 0 if a is equal to b. Panic if a or b is not a string.
func (c *stringComparer) Compare(a, b interface{}) int {
return strings.Compare(a.(string), b.(string))
}
// byteSliceComparer compares two byte slices. Implements Comparer.
type byteSliceComparer struct{}
// Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
// returns 0 if a is equal to b. Panic if a or b is not a byte slice.
func (c *byteSliceComparer) Compare(a, b interface{}) int {
return bytes.Compare(a.([]byte), b.([]byte))
}
|