ProBuf.js 335.1 KB
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 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914
/*
 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
 Copyright 2009 The Closure Library Authors. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS-IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/**
 * @license Long.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
 * Released under the Apache License, Version 2.0
 * see: https://github.com/dcodeIO/Long.js for details
 */
(function (global, factory) {

  /* AMD */
  if (typeof define === 'function' && define["amd"])
    define([], factory);
  /* CommonJS */
  else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
    module["exports"] = factory();
  /* Global */
  else
    (global["dcodeIO"] = global["dcodeIO"] || {})["Long"] = factory();

})(this, function () {
  "use strict";

  /**
   * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
   *  See the from* functions below for more convenient ways of constructing Longs.
   * @exports Long
   * @class A Long class for representing a 64 bit two's-complement integer value.
   * @param {number} low The low (signed) 32 bits of the long
   * @param {number} high The high (signed) 32 bits of the long
   * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
   * @constructor
   */
  var Long = function (low, high, unsigned) {

    /**
     * The low 32 bits as a signed value.
     * @type {number}
     * @expose
     */
    this.low = low | 0;

    /**
     * The high 32 bits as a signed value.
     * @type {number}
     * @expose
     */
    this.high = high | 0;

    /**
     * Whether unsigned or not.
     * @type {boolean}
     * @expose
     */
    this.unsigned = !!unsigned;
  };

  // The internal representation of a long is the two given signed, 32-bit values.
  // We use 32-bit pieces because these are the size of integers on which
  // Javascript performs bit-operations.  For operations like addition and
  // multiplication, we split each number into 16 bit pieces, which can easily be
  // multiplied within Javascript's floating-point representation without overflow
  // or change in sign.
  //
  // In the algorithms below, we frequently reduce the negative case to the
  // positive case by negating the input(s) and then post-processing the result.
  // Note that we must ALWAYS check specially whether those values are MIN_VALUE
  // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
  // a positive number, it overflows back into a negative).  Not handling this
  // case would often result in infinite recursion.
  //
  // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
  // methods on which they depend.

  /**
   * An indicator used to reliably determine if an object is a Long or not.
   * @type {boolean}
   * @const
   * @expose
   * @private
   */
  Long.__isLong__;

  Object.defineProperty(Long.prototype, "__isLong__", {
    value: true,
    enumerable: false,
    configurable: false
  });

  /**
   * Tests if the specified object is a Long.
   * @param {*} obj Object
   * @returns {boolean}
   * @expose
   */
  Long.isLong = function (obj) {
    return (obj && obj["__isLong__"]) === true;
  };

  /**
   * A cache of the Long representations of small integer values.
   * @type {!Object}
   * @inner
   */
  var INT_CACHE = {};

  /**
   * A cache of the Long representations of small unsigned integer values.
   * @type {!Object}
   * @inner
   */
  var UINT_CACHE = {};

  /**
   * Returns a Long representing the given 32 bit integer value.
   * @param {number} value The 32 bit integer in question
   * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
   * @returns {!Long} The corresponding Long value
   * @expose
   */
  Long.fromInt = function (value, unsigned) {
    var obj, cachedObj;
    if (!unsigned) {
      value = value | 0;
      if (-128 <= value && value < 128) {
        cachedObj = INT_CACHE[value];
        if (cachedObj)
          return cachedObj;
      }
      obj = new Long(value, value < 0 ? -1 : 0, false);
      if (-128 <= value && value < 128)
        INT_CACHE[value] = obj;
      return obj;
    } else {
      value = value >>> 0;
      if (0 <= value && value < 256) {
        cachedObj = UINT_CACHE[value];
        if (cachedObj)
          return cachedObj;
      }
      obj = new Long(value, (value | 0) < 0 ? -1 : 0, true);
      if (0 <= value && value < 256)
        UINT_CACHE[value] = obj;
      return obj;
    }
  };

  /**
   * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
   * @param {number} value The number in question
   * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
   * @returns {!Long} The corresponding Long value
   * @expose
   */
  Long.fromNumber = function (value, unsigned) {
    unsigned = !!unsigned;
    if (isNaN(value) || !isFinite(value))
      return Long.ZERO;
    if (!unsigned && value <= -TWO_PWR_63_DBL)
      return Long.MIN_VALUE;
    if (!unsigned && value + 1 >= TWO_PWR_63_DBL)
      return Long.MAX_VALUE;
    if (unsigned && value >= TWO_PWR_64_DBL)
      return Long.MAX_UNSIGNED_VALUE;
    if (value < 0)
      return Long.fromNumber(-value, unsigned).negate();
    return new Long((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
  };

  /**
   * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
   *  assumed to use 32 bits.
   * @param {number} lowBits The low 32 bits
   * @param {number} highBits The high 32 bits
   * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
   * @returns {!Long} The corresponding Long value
   * @expose
   */
  Long.fromBits = function (lowBits, highBits, unsigned) {
    return new Long(lowBits, highBits, unsigned);
  };

  /**
   * Returns a Long representation of the given string, written using the specified radix.
   * @param {string} str The textual representation of the Long
   * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed
   * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
   * @returns {!Long} The corresponding Long value
   * @expose
   */
  Long.fromString = function (str, unsigned, radix) {
    if (str.length === 0)
      throw Error('number format error: empty string');
    if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
      return Long.ZERO;
    if (typeof unsigned === 'number') // For goog.math.long compatibility
      radix = unsigned,
      unsigned = false;
    radix = radix || 10;
    if (radix < 2 || 36 < radix)
      throw Error('radix out of range: ' + radix);

    var p;
    if ((p = str.indexOf('-')) > 0)
      throw Error('number format error: interior "-" character: ' + str);
    else if (p === 0)
      return Long.fromString(str.substring(1), unsigned, radix).negate();

    // Do several (8) digits each time through the loop, so as to
    // minimize the calls to the very expensive emulated div.
    var radixToPower = Long.fromNumber(Math.pow(radix, 8));

    var result = Long.ZERO;
    for (var i = 0; i < str.length; i += 8) {
      var size = Math.min(8, str.length - i);
      var value = parseInt(str.substring(i, i + size), radix);
      if (size < 8) {
        var power = Long.fromNumber(Math.pow(radix, size));
        result = result.multiply(power).add(Long.fromNumber(value));
      } else {
        result = result.multiply(radixToPower);
        result = result.add(Long.fromNumber(value));
      }
    }
    result.unsigned = unsigned;
    return result;
  };

  /**
   * Converts the specified value to a Long.
   * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
   * @returns {!Long}
   * @expose
   */
  Long.fromValue = function (val) {
    if (val /* is compatible */ instanceof Long)
      return val;
    if (typeof val === 'number')
      return Long.fromNumber(val);
    if (typeof val === 'string')
      return Long.fromString(val);
    // Throws for non-objects, converts non-instanceof Long:
    return new Long(val.low, val.high, val.unsigned);
  };

  // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
  // no runtime penalty for these.

  /**
   * @type {number}
   * @const
   * @inner
   */
  var TWO_PWR_16_DBL = 1 << 16;

  /**
   * @type {number}
   * @const
   * @inner
   */
  var TWO_PWR_24_DBL = 1 << 24;

  /**
   * @type {number}
   * @const
   * @inner
   */
  var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;

  /**
   * @type {number}
   * @const
   * @inner
   */
  var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;

  /**
   * @type {number}
   * @const
   * @inner
   */
  var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;

  /**
   * @type {!Long}
   * @const
   * @inner
   */
  var TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);

  /**
   * Signed zero.
   * @type {!Long}
   * @expose
   */
  Long.ZERO = Long.fromInt(0);

  /**
   * Unsigned zero.
   * @type {!Long}
   * @expose
   */
  Long.UZERO = Long.fromInt(0, true);

  /**
   * Signed one.
   * @type {!Long}
   * @expose
   */
  Long.ONE = Long.fromInt(1);

  /**
   * Unsigned one.
   * @type {!Long}
   * @expose
   */
  Long.UONE = Long.fromInt(1, true);

  /**
   * Signed negative one.
   * @type {!Long}
   * @expose
   */
  Long.NEG_ONE = Long.fromInt(-1);

  /**
   * Maximum signed value.
   * @type {!Long}
   * @expose
   */
  Long.MAX_VALUE = Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0, false);

  /**
   * Maximum unsigned value.
   * @type {!Long}
   * @expose
   */
  Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xFFFFFFFF | 0, 0xFFFFFFFF | 0, true);

  /**
   * Minimum signed value.
   * @type {!Long}
   * @expose
   */
  Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);

  /**
   * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
   * @returns {number}
   * @expose
   */
  Long.prototype.toInt = function () {
    return this.unsigned ? this.low >>> 0 : this.low;
  };

  /**
   * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
   * @returns {number}
   * @expose
   */
  Long.prototype.toNumber = function () {
    if (this.unsigned) {
      return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
    }
    return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
  };

  /**
   * Converts the Long to a string written in the specified radix.
   * @param {number=} radix Radix (2-36), defaults to 10
   * @returns {string}
   * @override
   * @throws {RangeError} If `radix` is out of range
   * @expose
   */
  Long.prototype.toString = function (radix) {
    radix = radix || 10;
    if (radix < 2 || 36 < radix)
      throw RangeError('radix out of range: ' + radix);
    if (this.isZero())
      return '0';
    var rem;
    if (this.isNegative()) { // Unsigned Longs are never negative
      if (this.equals(Long.MIN_VALUE)) {
        // We need to change the Long value before it can be negated, so we remove
        // the bottom-most digit in this base and then recurse to do the rest.
        var radixLong = Long.fromNumber(radix);
        var div = this.div(radixLong);
        rem = div.multiply(radixLong).subtract(this);
        return div.toString(radix) + rem.toInt().toString(radix);
      } else
        return '-' + this.negate().toString(radix);
    }

    // Do several (6) digits each time through the loop, so as to
    // minimize the calls to the very expensive emulated div.
    var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
    rem = this;
    var result = '';
    while (true) {
      var remDiv = rem.div(radixToPower),
        intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0,
        digits = intval.toString(radix);
      rem = remDiv;
      if (rem.isZero())
        return digits + result;
      else {
        while (digits.length < 6)
          digits = '0' + digits;
        result = '' + digits + result;
      }
    }
  };

  /**
   * Gets the high 32 bits as a signed integer.
   * @returns {number} Signed high bits
   * @expose
   */
  Long.prototype.getHighBits = function () {
    return this.high;
  };

  /**
   * Gets the high 32 bits as an unsigned integer.
   * @returns {number} Unsigned high bits
   * @expose
   */
  Long.prototype.getHighBitsUnsigned = function () {
    return this.high >>> 0;
  };

  /**
   * Gets the low 32 bits as a signed integer.
   * @returns {number} Signed low bits
   * @expose
   */
  Long.prototype.getLowBits = function () {
    return this.low;
  };

  /**
   * Gets the low 32 bits as an unsigned integer.
   * @returns {number} Unsigned low bits
   * @expose
   */
  Long.prototype.getLowBitsUnsigned = function () {
    return this.low >>> 0;
  };

  /**
   * Gets the number of bits needed to represent the absolute value of this Long.
   * @returns {number}
   * @expose
   */
  Long.prototype.getNumBitsAbs = function () {
    if (this.isNegative()) // Unsigned Longs are never negative
      return this.equals(Long.MIN_VALUE) ? 64 : this.negate().getNumBitsAbs();
    var val = this.high != 0 ? this.high : this.low;
    for (var bit = 31; bit > 0; bit--)
      if ((val & (1 << bit)) != 0)
        break;
    return this.high != 0 ? bit + 33 : bit + 1;
  };

  /**
   * Tests if this Long's value equals zero.
   * @returns {boolean}
   * @expose
   */
  Long.prototype.isZero = function () {
    return this.high === 0 && this.low === 0;
  };

  /**
   * Tests if this Long's value is negative.
   * @returns {boolean}
   * @expose
   */
  Long.prototype.isNegative = function () {
    return !this.unsigned && this.high < 0;
  };

  /**
   * Tests if this Long's value is positive.
   * @returns {boolean}
   * @expose
   */
  Long.prototype.isPositive = function () {
    return this.unsigned || this.high >= 0;
  };

  /**
   * Tests if this Long's value is odd.
   * @returns {boolean}
   * @expose
   */
  Long.prototype.isOdd = function () {
    return (this.low & 1) === 1;
  };

  /**
   * Tests if this Long's value is even.
   * @returns {boolean}
   * @expose
   */
  Long.prototype.isEven = function () {
    return (this.low & 1) === 0;
  };

  /**
   * Tests if this Long's value equals the specified's.
   * @param {!Long|number|string} other Other value
   * @returns {boolean}
   * @expose
   */
  Long.prototype.equals = function (other) {
    if (!Long.isLong(other))
      other = Long.fromValue(other);
    if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
      return false;
    return this.high === other.high && this.low === other.low;
  };

  /**
   * Tests if this Long's value differs from the specified's.
   * @param {!Long|number|string} other Other value
   * @returns {boolean}
   * @expose
   */
  Long.prototype.notEquals = function (other) {
    return !this.equals( /* validates */ other);
  };

  /**
   * Tests if this Long's value is less than the specified's.
   * @param {!Long|number|string} other Other value
   * @returns {boolean}
   * @expose
   */
  Long.prototype.lessThan = function (other) {
    return this.compare( /* validates */ other) < 0;
  };

  /**
   * Tests if this Long's value is less than or equal the specified's.
   * @param {!Long|number|string} other Other value
   * @returns {boolean}
   * @expose
   */
  Long.prototype.lessThanOrEqual = function (other) {
    return this.compare( /* validates */ other) <= 0;
  };

  /**
   * Tests if this Long's value is greater than the specified's.
   * @param {!Long|number|string} other Other value
   * @returns {boolean}
   * @expose
   */
  Long.prototype.greaterThan = function (other) {
    return this.compare( /* validates */ other) > 0;
  };

  /**
   * Tests if this Long's value is greater than or equal the specified's.
   * @param {!Long|number|string} other Other value
   * @returns {boolean}
   * @expose
   */
  Long.prototype.greaterThanOrEqual = function (other) {
    return this.compare( /* validates */ other) >= 0;
  };

  /**
   * Compares this Long's value with the specified's.
   * @param {!Long|number|string} other Other value
   * @returns {number} 0 if they are the same, 1 if the this is greater and -1
   *  if the given one is greater
   * @expose
   */
  Long.prototype.compare = function (other) {
    if (!Long.isLong(other))
      other = Long.fromValue(other);
    if (this.equals(other))
      return 0;
    var thisNeg = this.isNegative(),
      otherNeg = other.isNegative();
    if (thisNeg && !otherNeg)
      return -1;
    if (!thisNeg && otherNeg)
      return 1;
    // At this point the sign bits are the same
    if (!this.unsigned)
      return this.subtract(other).isNegative() ? -1 : 1;
    // Both are positive if at least one is unsigned
    return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
  };

  /**
   * Negates this Long's value.
   * @returns {!Long} Negated Long
   * @expose
   */
  Long.prototype.negate = function () {
    if (!this.unsigned && this.equals(Long.MIN_VALUE))
      return Long.MIN_VALUE;
    return this.not().add(Long.ONE);
  };

  /**
   * Returns the sum of this and the specified Long.
   * @param {!Long|number|string} addend Addend
   * @returns {!Long} Sum
   * @expose
   */
  Long.prototype.add = function (addend) {
    if (!Long.isLong(addend))
      addend = Long.fromValue(addend);

    // Divide each number into 4 chunks of 16 bits, and then sum the chunks.

    var a48 = this.high >>> 16;
    var a32 = this.high & 0xFFFF;
    var a16 = this.low >>> 16;
    var a00 = this.low & 0xFFFF;

    var b48 = addend.high >>> 16;
    var b32 = addend.high & 0xFFFF;
    var b16 = addend.low >>> 16;
    var b00 = addend.low & 0xFFFF;

    var c48 = 0,
      c32 = 0,
      c16 = 0,
      c00 = 0;
    c00 += a00 + b00;
    c16 += c00 >>> 16;
    c00 &= 0xFFFF;
    c16 += a16 + b16;
    c32 += c16 >>> 16;
    c16 &= 0xFFFF;
    c32 += a32 + b32;
    c48 += c32 >>> 16;
    c32 &= 0xFFFF;
    c48 += a48 + b48;
    c48 &= 0xFFFF;
    return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  };

  /**
   * Returns the difference of this and the specified Long.
   * @param {!Long|number|string} subtrahend Subtrahend
   * @returns {!Long} Difference
   * @expose
   */
  Long.prototype.subtract = function (subtrahend) {
    if (!Long.isLong(subtrahend))
      subtrahend = Long.fromValue(subtrahend);
    return this.add(subtrahend.negate());
  };

  /**
   * Returns the product of this and the specified Long.
   * @param {!Long|number|string} multiplier Multiplier
   * @returns {!Long} Product
   * @expose
   */
  Long.prototype.multiply = function (multiplier) {
    if (this.isZero())
      return Long.ZERO;
    if (!Long.isLong(multiplier))
      multiplier = Long.fromValue(multiplier);
    if (multiplier.isZero())
      return Long.ZERO;
    if (this.equals(Long.MIN_VALUE))
      return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
    if (multiplier.equals(Long.MIN_VALUE))
      return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;

    if (this.isNegative()) {
      if (multiplier.isNegative())
        return this.negate().multiply(multiplier.negate());
      else
        return this.negate().multiply(multiplier).negate();
    } else if (multiplier.isNegative())
      return this.multiply(multiplier.negate()).negate();

    // If both longs are small, use float multiplication
    if (this.lessThan(TWO_PWR_24) && multiplier.lessThan(TWO_PWR_24))
      return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);

    // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
    // We can skip products that would overflow.

    var a48 = this.high >>> 16;
    var a32 = this.high & 0xFFFF;
    var a16 = this.low >>> 16;
    var a00 = this.low & 0xFFFF;

    var b48 = multiplier.high >>> 16;
    var b32 = multiplier.high & 0xFFFF;
    var b16 = multiplier.low >>> 16;
    var b00 = multiplier.low & 0xFFFF;

    var c48 = 0,
      c32 = 0,
      c16 = 0,
      c00 = 0;
    c00 += a00 * b00;
    c16 += c00 >>> 16;
    c00 &= 0xFFFF;
    c16 += a16 * b00;
    c32 += c16 >>> 16;
    c16 &= 0xFFFF;
    c16 += a00 * b16;
    c32 += c16 >>> 16;
    c16 &= 0xFFFF;
    c32 += a32 * b00;
    c48 += c32 >>> 16;
    c32 &= 0xFFFF;
    c32 += a16 * b16;
    c48 += c32 >>> 16;
    c32 &= 0xFFFF;
    c32 += a00 * b32;
    c48 += c32 >>> 16;
    c32 &= 0xFFFF;
    c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
    c48 &= 0xFFFF;
    return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  };

  /**
   * Returns this Long divided by the specified.
   * @param {!Long|number|string} divisor Divisor
   * @returns {!Long} Quotient
   * @expose
   */
  Long.prototype.div = function (divisor) {
    if (!Long.isLong(divisor))
      divisor = Long.fromValue(divisor);
    if (divisor.isZero())
      throw (new Error('division by zero'));
    if (this.isZero())
      return this.unsigned ? Long.UZERO : Long.ZERO;
    var approx, rem, res;
    if (this.equals(Long.MIN_VALUE)) {
      if (divisor.equals(Long.ONE) || divisor.equals(Long.NEG_ONE))
        return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
      else if (divisor.equals(Long.MIN_VALUE))
        return Long.ONE;
      else {
        // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
        var halfThis = this.shiftRight(1);
        approx = halfThis.div(divisor).shiftLeft(1);
        if (approx.equals(Long.ZERO)) {
          return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
        } else {
          rem = this.subtract(divisor.multiply(approx));
          res = approx.add(rem.div(divisor));
          return res;
        }
      }
    } else if (divisor.equals(Long.MIN_VALUE))
      return this.unsigned ? Long.UZERO : Long.ZERO;
    if (this.isNegative()) {
      if (divisor.isNegative())
        return this.negate().div(divisor.negate());
      return this.negate().div(divisor).negate();
    } else if (divisor.isNegative())
      return this.div(divisor.negate()).negate();

    // Repeat the following until the remainder is less than other:  find a
    // floating-point that approximates remainder / other *from below*, add this
    // into the result, and subtract it from the remainder.  It is critical that
    // the approximate value is less than or equal to the real value so that the
    // remainder never becomes negative.
    res = Long.ZERO;
    rem = this;
    while (rem.greaterThanOrEqual(divisor)) {
      // Approximate the result of division. This may be a little greater or
      // smaller than the actual value.
      approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));

      // We will tweak the approximate result by changing it in the 48-th digit or
      // the smallest non-fractional digit, whichever is larger.
      var log2 = Math.ceil(Math.log(approx) / Math.LN2),
        delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48),

        // Decrease the approximation until it is smaller than the remainder.  Note
        // that if it is too large, the product overflows and is negative.
        approxRes = Long.fromNumber(approx),
        approxRem = approxRes.multiply(divisor);
      while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
        approx -= delta;
        approxRes = Long.fromNumber(approx, this.unsigned);
        approxRem = approxRes.multiply(divisor);
      }

      // We know the answer can't be zero... and actually, zero would cause
      // infinite recursion since we would make no progress.
      if (approxRes.isZero())
        approxRes = Long.ONE;

      res = res.add(approxRes);
      rem = rem.subtract(approxRem);
    }
    return res;
  };

  /**
   * Returns this Long modulo the specified.
   * @param {!Long|number|string} divisor Divisor
   * @returns {!Long} Remainder
   * @expose
   */
  Long.prototype.modulo = function (divisor) {
    if (!Long.isLong(divisor))
      divisor = Long.fromValue(divisor);
    return this.subtract(this.div(divisor).multiply(divisor));
  };

  /**
   * Returns the bitwise NOT of this Long.
   * @returns {!Long}
   * @expose
   */
  Long.prototype.not = function () {
    return Long.fromBits(~this.low, ~this.high, this.unsigned);
  };

  /**
   * Returns the bitwise AND of this Long and the specified.
   * @param {!Long|number|string} other Other Long
   * @returns {!Long}
   * @expose
   */
  Long.prototype.and = function (other) {
    if (!Long.isLong(other))
      other = Long.fromValue(other);
    return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
  };

  /**
   * Returns the bitwise OR of this Long and the specified.
   * @param {!Long|number|string} other Other Long
   * @returns {!Long}
   * @expose
   */
  Long.prototype.or = function (other) {
    if (!Long.isLong(other))
      other = Long.fromValue(other);
    return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
  };

  /**
   * Returns the bitwise XOR of this Long and the given one.
   * @param {!Long|number|string} other Other Long
   * @returns {!Long}
   * @expose
   */
  Long.prototype.xor = function (other) {
    if (!Long.isLong(other))
      other = Long.fromValue(other);
    return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
  };

  /**
   * Returns this Long with bits shifted to the left by the given amount.
   * @param {number|!Long} numBits Number of bits
   * @returns {!Long} Shifted Long
   * @expose
   */
  Long.prototype.shiftLeft = function (numBits) {
    if (Long.isLong(numBits))
      numBits = numBits.toInt();
    if ((numBits &= 63) === 0)
      return this;
    else if (numBits < 32)
      return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
    else
      return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
  };

  /**
   * Returns this Long with bits arithmetically shifted to the right by the given amount.
   * @param {number|!Long} numBits Number of bits
   * @returns {!Long} Shifted Long
   * @expose
   */
  Long.prototype.shiftRight = function (numBits) {
    if (Long.isLong(numBits))
      numBits = numBits.toInt();
    if ((numBits &= 63) === 0)
      return this;
    else if (numBits < 32)
      return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
    else
      return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
  };

  /**
   * Returns this Long with bits logically shifted to the right by the given amount.
   * @param {number|!Long} numBits Number of bits
   * @returns {!Long} Shifted Long
   * @expose
   */
  Long.prototype.shiftRightUnsigned = function (numBits) {
    if (Long.isLong(numBits))
      numBits = numBits.toInt();
    numBits &= 63;
    if (numBits === 0)
      return this;
    else {
      var high = this.high;
      if (numBits < 32) {
        var low = this.low;
        return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
      } else if (numBits === 32)
        return Long.fromBits(high, 0, this.unsigned);
      else
        return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
    }
  };

  /**
   * Converts this Long to signed.
   * @returns {!Long} Signed long
   * @expose
   */
  Long.prototype.toSigned = function () {
    if (!this.unsigned)
      return this;
    return new Long(this.low, this.high, false);
  };

  /**
   * Converts this Long to unsigned.
   * @returns {!Long} Unsigned long
   * @expose
   */
  Long.prototype.toUnsigned = function () {
    if (this.unsigned)
      return this;
    return new Long(this.low, this.high, true);
  };

  return Long;
});
/*
 Copyright 2013-2014 Daniel Wirtz <dcode@dcode.io>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/**
 * @license ByteBuffer.js (c) 2015 Daniel Wirtz <dcode@dcode.io>
 * [BUILD] ByteBufferAB - Backing buffer: ArrayBuffer, Accessor: Uint8Array
 * Released under the Apache License, Version 2.0
 * see: https://github.com/dcodeIO/ByteBuffer.js for details
 */
(function (global, factory) {

  /* AMD */
  if (typeof define === 'function' && define["amd"])
    define(["Long"], factory);
  /* CommonJS */
  else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
    module['exports'] = (function () {
      var Long;
      try { Long = require("long"); } catch (e) {}
      return factory(Long);
    })();
  /* Global */
  else
    (global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]);

})(this, function (Long) {
  "use strict";

  /**
   * Constructs a new ByteBuffer.
   * @class The swiss army knife for binary data in JavaScript.
   * @exports ByteBuffer
   * @constructor
   * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
   * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
   *  {@link ByteBuffer.DEFAULT_ENDIAN}.
   * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
   *  {@link ByteBuffer.DEFAULT_NOASSERT}.
   * @expose
   */
  var ByteBuffer = function (capacity, littleEndian, noAssert) {
    if (typeof capacity === 'undefined')
      capacity = ByteBuffer.DEFAULT_CAPACITY;
    if (typeof littleEndian === 'undefined')
      littleEndian = ByteBuffer.DEFAULT_ENDIAN;
    if (typeof noAssert === 'undefined')
      noAssert = ByteBuffer.DEFAULT_NOASSERT;
    if (!noAssert) {
      capacity = capacity | 0;
      if (capacity < 0)
        throw RangeError("Illegal capacity");
      littleEndian = !!littleEndian;
      noAssert = !!noAssert;
    }

    /**
     * Backing ArrayBuffer.
     * @type {!ArrayBuffer}
     * @expose
     */
    this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity);

    /**
     * Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`.
     * @type {?Uint8Array}
     * @expose
     */
    this.view = capacity === 0 ? null : new Uint8Array(this.buffer);

    /**
     * Absolute read/write offset.
     * @type {number}
     * @expose
     * @see ByteBuffer#flip
     * @see ByteBuffer#clear
     */
    this.offset = 0;

    /**
     * Marked offset.
     * @type {number}
     * @expose
     * @see ByteBuffer#mark
     * @see ByteBuffer#reset
     */
    this.markedOffset = -1;

    /**
     * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
     * @type {number}
     * @expose
     * @see ByteBuffer#flip
     * @see ByteBuffer#clear
     */
    this.limit = capacity;

    /**
     * Whether to use little endian byte order, defaults to `false` for big endian.
     * @type {boolean}
     * @expose
     */
    this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : false;

    /**
     * Whether to skip assertions of offsets and values, defaults to `false`.
     * @type {boolean}
     * @expose
     */
    this.noAssert = !!noAssert;
  };

  /**
   * ByteBuffer version.
   * @type {string}
   * @const
   * @expose
   */
  ByteBuffer.VERSION = "4.1.0";

  /**
   * Little endian constant that can be used instead of its boolean value. Evaluates to `true`.
   * @type {boolean}
   * @const
   * @expose
   */
  ByteBuffer.LITTLE_ENDIAN = true;

  /**
   * Big endian constant that can be used instead of its boolean value. Evaluates to `false`.
   * @type {boolean}
   * @const
   * @expose
   */
  ByteBuffer.BIG_ENDIAN = false;

  /**
   * Default initial capacity of `16`.
   * @type {number}
   * @expose
   */
  ByteBuffer.DEFAULT_CAPACITY = 16;

  /**
   * Default endianess of `false` for big endian.
   * @type {boolean}
   * @expose
   */
  ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN;

  /**
   * Default no assertions flag of `false`.
   * @type {boolean}
   * @expose
   */
  ByteBuffer.DEFAULT_NOASSERT = false;

  /**
   * A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded
   *  and int64 support is not available.
   * @type {?Long}
   * @const
   * @see https://github.com/dcodeIO/Long.js
   * @expose
   */
  ByteBuffer.Long = Long || null;

  /**
   * @alias ByteBuffer.prototype
   * @inner
   */
  var ByteBufferPrototype = ByteBuffer.prototype;

  /**
   * An indicator used to reliably determine if an object is a ByteBuffer or not.
   * @type {boolean}
   * @const
   * @expose
   * @private
   */
  ByteBufferPrototype.__isByteBuffer__;

  Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", {
    value: true,
    enumerable: false,
    configurable: false
  });

  // helpers

  /**
   * @type {!ArrayBuffer}
   * @inner
   */
  var EMPTY_BUFFER = new ArrayBuffer(0);

  /**
   * String.fromCharCode reference for compile-time renaming.
   * @type {function(...number):string}
   * @inner
   */
  var stringFromCharCode = String.fromCharCode;

  /**
   * Creates a source function for a string.
   * @param {string} s String to read from
   * @returns {function():number|null} Source function returning the next char code respectively `null` if there are
   *  no more characters left.
   * @throws {TypeError} If the argument is invalid
   * @inner
   */
  function stringSource(s) {
    var i = 0;
    return function () {
      return i < s.length ? s.charCodeAt(i++) : null;
    };
  }

  /**
   * Creates a destination function for a string.
   * @returns {function(number=):undefined|string} Destination function successively called with the next char code.
   *  Returns the final string when called without arguments.
   * @inner
   */
  function stringDestination() {
    var cs = [],
      ps = [];
    return function () {
      if (arguments.length === 0)
        return ps.join('') + stringFromCharCode.apply(String, cs);
      if (cs.length + arguments.length > 1024)
        ps.push(stringFromCharCode.apply(String, cs)),
        cs.length = 0;
      Array.prototype.push.apply(cs, arguments);
    };
  }

  /**
   * Gets the accessor type.
   * @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes)
   * @expose
   */
  ByteBuffer.accessor = function () {
    return Uint8Array;
  };
  /**
   * Allocates a new ByteBuffer backed by a buffer of the specified capacity.
   * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
   * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
   *  {@link ByteBuffer.DEFAULT_ENDIAN}.
   * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
   *  {@link ByteBuffer.DEFAULT_NOASSERT}.
   * @returns {!ByteBuffer}
   * @expose
   */
  ByteBuffer.allocate = function (capacity, littleEndian, noAssert) {
    return new ByteBuffer(capacity, littleEndian, noAssert);
  };

  /**
   * Concatenates multiple ByteBuffers into one.
   * @param {!Array.<!ByteBuffer|!ArrayBuffer|!Uint8Array|string>} buffers Buffers to concatenate
   * @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary",
   *  defaults to "utf8")
   * @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults
   *  to {@link ByteBuffer.DEFAULT_ENDIAN}.
   * @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to
   *  {@link ByteBuffer.DEFAULT_NOASSERT}.
   * @returns {!ByteBuffer} Concatenated ByteBuffer
   * @expose
   */
  ByteBuffer.concat = function (buffers, encoding, littleEndian, noAssert) {
    if (typeof encoding === 'boolean' || typeof encoding !== 'string') {
      noAssert = littleEndian;
      littleEndian = encoding;
      encoding = undefined;
    }
    var capacity = 0;
    for (var i = 0, k = buffers.length, length; i < k; ++i) {
      if (!ByteBuffer.isByteBuffer(buffers[i]))
        buffers[i] = ByteBuffer.wrap(buffers[i], encoding);
      length = buffers[i].limit - buffers[i].offset;
      if (length > 0) capacity += length;
    }
    if (capacity === 0)
      return new ByteBuffer(0, littleEndian, noAssert);
    var bb = new ByteBuffer(capacity, littleEndian, noAssert),
      bi;
    i = 0;
    while (i < k) {
      bi = buffers[i++];
      length = bi.limit - bi.offset;
      if (length <= 0) continue;
      bb.view.set(bi.view.subarray(bi.offset, bi.limit), bb.offset);
      bb.offset += length;
    }
    bb.limit = bb.offset;
    bb.offset = 0;
    return bb;
  };

  /**
   * Tests if the specified type is a ByteBuffer.
   * @param {*} bb ByteBuffer to test
   * @returns {boolean} `true` if it is a ByteBuffer, otherwise `false`
   * @expose
   */
  ByteBuffer.isByteBuffer = function (bb) {
    return (bb && bb["__isByteBuffer__"]) === true;
  };
  /**
   * Gets the backing buffer type.
   * @returns {Function} `Buffer` under node.js, `ArrayBuffer` in the browser (classes)
   * @expose
   */
  ByteBuffer.type = function () {
    return ArrayBuffer;
  };
  /**
   * Wraps a buffer or a string. Sets the allocated ByteBuffer's {@link ByteBuffer#offset} to `0` and its
   *  {@link ByteBuffer#limit} to the length of the wrapped data.
   * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string|!Array.<number>} buffer Anything that can be wrapped
   * @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to
   *  "utf8")
   * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
   *  {@link ByteBuffer.DEFAULT_ENDIAN}.
   * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
   *  {@link ByteBuffer.DEFAULT_NOASSERT}.
   * @returns {!ByteBuffer} A ByteBuffer wrapping `buffer`
   * @expose
   */
  ByteBuffer.wrap = function (buffer, encoding, littleEndian, noAssert) {
    if (typeof encoding !== 'string') {
      noAssert = littleEndian;
      littleEndian = encoding;
      encoding = undefined;
    }
    if (typeof buffer === 'string') {
      if (typeof encoding === 'undefined')
        encoding = "utf8";
      switch (encoding) {
      case "base64":
        return ByteBuffer.fromBase64(buffer, littleEndian);
      case "hex":
        return ByteBuffer.fromHex(buffer, littleEndian);
      case "binary":
        return ByteBuffer.fromBinary(buffer, littleEndian);
      case "utf8":
        return ByteBuffer.fromUTF8(buffer, littleEndian);
      case "debug":
        return ByteBuffer.fromDebug(buffer, littleEndian);
      default:
        throw Error("Unsupported encoding: " + encoding);
      }
    }
    if (buffer === null || typeof buffer !== 'object')
      throw TypeError("Illegal buffer");
    var bb;
    if (ByteBuffer.isByteBuffer(buffer)) {
      bb = ByteBufferPrototype.clone.call(buffer);
      bb.markedOffset = -1;
      return bb;
    }
    if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array
      bb = new ByteBuffer(0, littleEndian, noAssert);
      if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER
        bb.buffer = buffer.buffer;
        bb.offset = buffer.byteOffset;
        bb.limit = buffer.byteOffset + buffer.byteLength;
        bb.view = new Uint8Array(buffer.buffer);
      }
    } else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer
      bb = new ByteBuffer(0, littleEndian, noAssert);
      if (buffer.byteLength > 0) {
        bb.buffer = buffer;
        bb.offset = 0;
        bb.limit = buffer.byteLength;
        bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null;
      }
    } else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets
      bb = new ByteBuffer(buffer.length, littleEndian, noAssert);
      bb.limit = buffer.length;
      for (var i = 0; i < buffer.length; ++i)
        bb.view[i] = buffer[i];
    } else
      throw TypeError("Illegal buffer"); // Otherwise fail
    return bb;
  };

  /**
   * Reads the specified number of bytes.
   * @param {number} length Number of bytes to read
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
   * @returns {!ByteBuffer}
   * @expose
   */
  ByteBufferPrototype.readBytes = function (length, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + length > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + length + ") <= " + this.buffer.byteLength);
    }
    var slice = this.slice(offset, offset + length);
    if (relative) this.offset += length;
    return slice;
  };

  /**
   * Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}.
   * @function
   * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets
   *  will be modified according to the performed read operation.
   * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  written if omitted.
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.writeBytes = ByteBufferPrototype.append;

  // types/ints/int8

  /**
   * Writes an 8bit signed integer.
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.writeInt8 = function (value, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof value !== 'number' || value % 1 !== 0)
        throw TypeError("Illegal value: " + value + " (not an integer)");
      value |= 0;
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    offset += 1;
    var capacity0 = this.buffer.byteLength;
    if (offset > capacity0)
      this.resize((capacity0 *= 2) > offset ? capacity0 : offset);
    offset -= 1;
    this.view[offset] = value;
    if (relative) this.offset += 1;
    return this;
  };

  /**
   * Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}.
   * @function
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8;

  /**
   * Reads an 8bit signed integer.
   * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
   * @returns {number} Value read
   * @expose
   */
  ByteBufferPrototype.readInt8 = function (offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 1 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 1 + ") <= " + this.buffer.byteLength);
    }
    var value = this.view[offset];
    if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed
    if (relative) this.offset += 1;
    return value;
  };

  /**
   * Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}.
   * @function
   * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
   * @returns {number} Value read
   * @expose
   */
  ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8;

  /**
   * Writes an 8bit unsigned integer.
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.writeUint8 = function (value, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof value !== 'number' || value % 1 !== 0)
        throw TypeError("Illegal value: " + value + " (not an integer)");
      value >>>= 0;
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    offset += 1;
    var capacity1 = this.buffer.byteLength;
    if (offset > capacity1)
      this.resize((capacity1 *= 2) > offset ? capacity1 : offset);
    offset -= 1;
    this.view[offset] = value;
    if (relative) this.offset += 1;
    return this;
  };

  /**
   * Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}.
   * @function
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8;

  /**
   * Reads an 8bit unsigned integer.
   * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
   * @returns {number} Value read
   * @expose
   */
  ByteBufferPrototype.readUint8 = function (offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 1 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 1 + ") <= " + this.buffer.byteLength);
    }
    var value = this.view[offset];
    if (relative) this.offset += 1;
    return value;
  };

  /**
   * Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}.
   * @function
   * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
   * @returns {number} Value read
   * @expose
   */
  ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8;

  // types/ints/int16

  /**
   * Writes a 16bit signed integer.
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
   * @throws {TypeError} If `offset` or `value` is not a valid number
   * @throws {RangeError} If `offset` is out of bounds
   * @expose
   */
  ByteBufferPrototype.writeInt16 = function (value, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof value !== 'number' || value % 1 !== 0)
        throw TypeError("Illegal value: " + value + " (not an integer)");
      value |= 0;
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    offset += 2;
    var capacity2 = this.buffer.byteLength;
    if (offset > capacity2)
      this.resize((capacity2 *= 2) > offset ? capacity2 : offset);
    offset -= 2;
    if (this.littleEndian) {
      this.view[offset + 1] = (value & 0xFF00) >>> 8;
      this.view[offset] = value & 0x00FF;
    } else {
      this.view[offset] = (value & 0xFF00) >>> 8;
      this.view[offset + 1] = value & 0x00FF;
    }
    if (relative) this.offset += 2;
    return this;
  };

  /**
   * Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}.
   * @function
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
   * @throws {TypeError} If `offset` or `value` is not a valid number
   * @throws {RangeError} If `offset` is out of bounds
   * @expose
   */
  ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16;

  /**
   * Reads a 16bit signed integer.
   * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
   * @returns {number} Value read
   * @throws {TypeError} If `offset` is not a valid number
   * @throws {RangeError} If `offset` is out of bounds
   * @expose
   */
  ByteBufferPrototype.readInt16 = function (offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 2 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 2 + ") <= " + this.buffer.byteLength);
    }
    var value = 0;
    if (this.littleEndian) {
      value = this.view[offset];
      value |= this.view[offset + 1] << 8;
    } else {
      value = this.view[offset] << 8;
      value |= this.view[offset + 1];
    }
    if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed
    if (relative) this.offset += 2;
    return value;
  };

  /**
   * Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}.
   * @function
   * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
   * @returns {number} Value read
   * @throws {TypeError} If `offset` is not a valid number
   * @throws {RangeError} If `offset` is out of bounds
   * @expose
   */
  ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16;

  /**
   * Writes a 16bit unsigned integer.
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
   * @throws {TypeError} If `offset` or `value` is not a valid number
   * @throws {RangeError} If `offset` is out of bounds
   * @expose
   */
  ByteBufferPrototype.writeUint16 = function (value, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof value !== 'number' || value % 1 !== 0)
        throw TypeError("Illegal value: " + value + " (not an integer)");
      value >>>= 0;
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    offset += 2;
    var capacity3 = this.buffer.byteLength;
    if (offset > capacity3)
      this.resize((capacity3 *= 2) > offset ? capacity3 : offset);
    offset -= 2;
    if (this.littleEndian) {
      this.view[offset + 1] = (value & 0xFF00) >>> 8;
      this.view[offset] = value & 0x00FF;
    } else {
      this.view[offset] = (value & 0xFF00) >>> 8;
      this.view[offset + 1] = value & 0x00FF;
    }
    if (relative) this.offset += 2;
    return this;
  };

  /**
   * Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}.
   * @function
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
   * @throws {TypeError} If `offset` or `value` is not a valid number
   * @throws {RangeError} If `offset` is out of bounds
   * @expose
   */
  ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16;

  /**
   * Reads a 16bit unsigned integer.
   * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
   * @returns {number} Value read
   * @throws {TypeError} If `offset` is not a valid number
   * @throws {RangeError} If `offset` is out of bounds
   * @expose
   */
  ByteBufferPrototype.readUint16 = function (offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 2 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 2 + ") <= " + this.buffer.byteLength);
    }
    var value = 0;
    if (this.littleEndian) {
      value = this.view[offset];
      value |= this.view[offset + 1] << 8;
    } else {
      value = this.view[offset] << 8;
      value |= this.view[offset + 1];
    }
    if (relative) this.offset += 2;
    return value;
  };

  /**
   * Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}.
   * @function
   * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
   * @returns {number} Value read
   * @throws {TypeError} If `offset` is not a valid number
   * @throws {RangeError} If `offset` is out of bounds
   * @expose
   */
  ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16;

  // types/ints/int32

  /**
   * Writes a 32bit signed integer.
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
   * @expose
   */
  ByteBufferPrototype.writeInt32 = function (value, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof value !== 'number' || value % 1 !== 0)
        throw TypeError("Illegal value: " + value + " (not an integer)");
      value |= 0;
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    offset += 4;
    var capacity4 = this.buffer.byteLength;
    if (offset > capacity4)
      this.resize((capacity4 *= 2) > offset ? capacity4 : offset);
    offset -= 4;
    if (this.littleEndian) {
      this.view[offset + 3] = (value >>> 24) & 0xFF;
      this.view[offset + 2] = (value >>> 16) & 0xFF;
      this.view[offset + 1] = (value >>> 8) & 0xFF;
      this.view[offset] = value & 0xFF;
    } else {
      this.view[offset] = (value >>> 24) & 0xFF;
      this.view[offset + 1] = (value >>> 16) & 0xFF;
      this.view[offset + 2] = (value >>> 8) & 0xFF;
      this.view[offset + 3] = value & 0xFF;
    }
    if (relative) this.offset += 4;
    return this;
  };

  /**
   * Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}.
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
   * @expose
   */
  ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32;

  /**
   * Reads a 32bit signed integer.
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
   * @returns {number} Value read
   * @expose
   */
  ByteBufferPrototype.readInt32 = function (offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 4 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 4 + ") <= " + this.buffer.byteLength);
    }
    var value = 0;
    if (this.littleEndian) {
      value = this.view[offset + 2] << 16;
      value |= this.view[offset + 1] << 8;
      value |= this.view[offset];
      value += this.view[offset + 3] << 24 >>> 0;
    } else {
      value = this.view[offset + 1] << 16;
      value |= this.view[offset + 2] << 8;
      value |= this.view[offset + 3];
      value += this.view[offset] << 24 >>> 0;
    }
    value |= 0; // Cast to signed
    if (relative) this.offset += 4;
    return value;
  };

  /**
   * Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}.
   * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted.
   * @returns {number} Value read
   * @expose
   */
  ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32;

  /**
   * Writes a 32bit unsigned integer.
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
   * @expose
   */
  ByteBufferPrototype.writeUint32 = function (value, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof value !== 'number' || value % 1 !== 0)
        throw TypeError("Illegal value: " + value + " (not an integer)");
      value >>>= 0;
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    offset += 4;
    var capacity5 = this.buffer.byteLength;
    if (offset > capacity5)
      this.resize((capacity5 *= 2) > offset ? capacity5 : offset);
    offset -= 4;
    if (this.littleEndian) {
      this.view[offset + 3] = (value >>> 24) & 0xFF;
      this.view[offset + 2] = (value >>> 16) & 0xFF;
      this.view[offset + 1] = (value >>> 8) & 0xFF;
      this.view[offset] = value & 0xFF;
    } else {
      this.view[offset] = (value >>> 24) & 0xFF;
      this.view[offset + 1] = (value >>> 16) & 0xFF;
      this.view[offset + 2] = (value >>> 8) & 0xFF;
      this.view[offset + 3] = value & 0xFF;
    }
    if (relative) this.offset += 4;
    return this;
  };

  /**
   * Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}.
   * @function
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
   * @expose
   */
  ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32;

  /**
   * Reads a 32bit unsigned integer.
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
   * @returns {number} Value read
   * @expose
   */
  ByteBufferPrototype.readUint32 = function (offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 4 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 4 + ") <= " + this.buffer.byteLength);
    }
    var value = 0;
    if (this.littleEndian) {
      value = this.view[offset + 2] << 16;
      value |= this.view[offset + 1] << 8;
      value |= this.view[offset];
      value += this.view[offset + 3] << 24 >>> 0;
    } else {
      value = this.view[offset + 1] << 16;
      value |= this.view[offset + 2] << 8;
      value |= this.view[offset + 3];
      value += this.view[offset] << 24 >>> 0;
    }
    if (relative) this.offset += 4;
    return value;
  };

  /**
   * Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}.
   * @function
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
   * @returns {number} Value read
   * @expose
   */
  ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32;

  // types/ints/int64

  if (Long) {

    /**
     * Writes a 64bit signed integer.
     * @param {number|!Long} value Value to write
     * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
     * @returns {!ByteBuffer} this
     * @expose
     */
    ByteBufferPrototype.writeInt64 = function (value, offset) {
      var relative = typeof offset === 'undefined';
      if (relative) offset = this.offset;
      if (!this.noAssert) {
        if (typeof value === 'number')
          value = Long.fromNumber(value);
        else if (typeof value === 'string')
          value = Long.fromString(value);
        else if (!(value && value instanceof Long))
          throw TypeError("Illegal value: " + value + " (not an integer or Long)");
        if (typeof offset !== 'number' || offset % 1 !== 0)
          throw TypeError("Illegal offset: " + offset + " (not an integer)");
        offset >>>= 0;
        if (offset < 0 || offset + 0 > this.buffer.byteLength)
          throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
      }
      if (typeof value === 'number')
        value = Long.fromNumber(value);
      else if (typeof value === 'string')
        value = Long.fromString(value);
      offset += 8;
      var capacity6 = this.buffer.byteLength;
      if (offset > capacity6)
        this.resize((capacity6 *= 2) > offset ? capacity6 : offset);
      offset -= 8;
      var lo = value.low,
        hi = value.high;
      if (this.littleEndian) {
        this.view[offset + 3] = (lo >>> 24) & 0xFF;
        this.view[offset + 2] = (lo >>> 16) & 0xFF;
        this.view[offset + 1] = (lo >>> 8) & 0xFF;
        this.view[offset] = lo & 0xFF;
        offset += 4;
        this.view[offset + 3] = (hi >>> 24) & 0xFF;
        this.view[offset + 2] = (hi >>> 16) & 0xFF;
        this.view[offset + 1] = (hi >>> 8) & 0xFF;
        this.view[offset] = hi & 0xFF;
      } else {
        this.view[offset] = (hi >>> 24) & 0xFF;
        this.view[offset + 1] = (hi >>> 16) & 0xFF;
        this.view[offset + 2] = (hi >>> 8) & 0xFF;
        this.view[offset + 3] = hi & 0xFF;
        offset += 4;
        this.view[offset] = (lo >>> 24) & 0xFF;
        this.view[offset + 1] = (lo >>> 16) & 0xFF;
        this.view[offset + 2] = (lo >>> 8) & 0xFF;
        this.view[offset + 3] = lo & 0xFF;
      }
      if (relative) this.offset += 8;
      return this;
    };

    /**
     * Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}.
     * @param {number|!Long} value Value to write
     * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
     * @returns {!ByteBuffer} this
     * @expose
     */
    ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64;

    /**
     * Reads a 64bit signed integer.
     * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
     * @returns {!Long}
     * @expose
     */
    ByteBufferPrototype.readInt64 = function (offset) {
      var relative = typeof offset === 'undefined';
      if (relative) offset = this.offset;
      if (!this.noAssert) {
        if (typeof offset !== 'number' || offset % 1 !== 0)
          throw TypeError("Illegal offset: " + offset + " (not an integer)");
        offset >>>= 0;
        if (offset < 0 || offset + 8 > this.buffer.byteLength)
          throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 8 + ") <= " + this.buffer.byteLength);
      }
      var lo = 0,
        hi = 0;
      if (this.littleEndian) {
        lo = this.view[offset + 2] << 16;
        lo |= this.view[offset + 1] << 8;
        lo |= this.view[offset];
        lo += this.view[offset + 3] << 24 >>> 0;
        offset += 4;
        hi = this.view[offset + 2] << 16;
        hi |= this.view[offset + 1] << 8;
        hi |= this.view[offset];
        hi += this.view[offset + 3] << 24 >>> 0;
      } else {
        hi = this.view[offset + 1] << 16;
        hi |= this.view[offset + 2] << 8;
        hi |= this.view[offset + 3];
        hi += this.view[offset] << 24 >>> 0;
        offset += 4;
        lo = this.view[offset + 1] << 16;
        lo |= this.view[offset + 2] << 8;
        lo |= this.view[offset + 3];
        lo += this.view[offset] << 24 >>> 0;
      }
      var value = new Long(lo, hi, false);
      if (relative) this.offset += 8;
      return value;
    };

    /**
     * Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}.
     * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
     * @returns {!Long}
     * @expose
     */
    ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64;

    /**
     * Writes a 64bit unsigned integer.
     * @param {number|!Long} value Value to write
     * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
     * @returns {!ByteBuffer} this
     * @expose
     */
    ByteBufferPrototype.writeUint64 = function (value, offset) {
      var relative = typeof offset === 'undefined';
      if (relative) offset = this.offset;
      if (!this.noAssert) {
        if (typeof value === 'number')
          value = Long.fromNumber(value);
        else if (typeof value === 'string')
          value = Long.fromString(value);
        else if (!(value && value instanceof Long))
          throw TypeError("Illegal value: " + value + " (not an integer or Long)");
        if (typeof offset !== 'number' || offset % 1 !== 0)
          throw TypeError("Illegal offset: " + offset + " (not an integer)");
        offset >>>= 0;
        if (offset < 0 || offset + 0 > this.buffer.byteLength)
          throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
      }
      if (typeof value === 'number')
        value = Long.fromNumber(value);
      else if (typeof value === 'string')
        value = Long.fromString(value);
      offset += 8;
      var capacity7 = this.buffer.byteLength;
      if (offset > capacity7)
        this.resize((capacity7 *= 2) > offset ? capacity7 : offset);
      offset -= 8;
      var lo = value.low,
        hi = value.high;
      if (this.littleEndian) {
        this.view[offset + 3] = (lo >>> 24) & 0xFF;
        this.view[offset + 2] = (lo >>> 16) & 0xFF;
        this.view[offset + 1] = (lo >>> 8) & 0xFF;
        this.view[offset] = lo & 0xFF;
        offset += 4;
        this.view[offset + 3] = (hi >>> 24) & 0xFF;
        this.view[offset + 2] = (hi >>> 16) & 0xFF;
        this.view[offset + 1] = (hi >>> 8) & 0xFF;
        this.view[offset] = hi & 0xFF;
      } else {
        this.view[offset] = (hi >>> 24) & 0xFF;
        this.view[offset + 1] = (hi >>> 16) & 0xFF;
        this.view[offset + 2] = (hi >>> 8) & 0xFF;
        this.view[offset + 3] = hi & 0xFF;
        offset += 4;
        this.view[offset] = (lo >>> 24) & 0xFF;
        this.view[offset + 1] = (lo >>> 16) & 0xFF;
        this.view[offset + 2] = (lo >>> 8) & 0xFF;
        this.view[offset + 3] = lo & 0xFF;
      }
      if (relative) this.offset += 8;
      return this;
    };

    /**
     * Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}.
     * @function
     * @param {number|!Long} value Value to write
     * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
     * @returns {!ByteBuffer} this
     * @expose
     */
    ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64;

    /**
     * Reads a 64bit unsigned integer.
     * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
     * @returns {!Long}
     * @expose
     */
    ByteBufferPrototype.readUint64 = function (offset) {
      var relative = typeof offset === 'undefined';
      if (relative) offset = this.offset;
      if (!this.noAssert) {
        if (typeof offset !== 'number' || offset % 1 !== 0)
          throw TypeError("Illegal offset: " + offset + " (not an integer)");
        offset >>>= 0;
        if (offset < 0 || offset + 8 > this.buffer.byteLength)
          throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 8 + ") <= " + this.buffer.byteLength);
      }
      var lo = 0,
        hi = 0;
      if (this.littleEndian) {
        lo = this.view[offset + 2] << 16;
        lo |= this.view[offset + 1] << 8;
        lo |= this.view[offset];
        lo += this.view[offset + 3] << 24 >>> 0;
        offset += 4;
        hi = this.view[offset + 2] << 16;
        hi |= this.view[offset + 1] << 8;
        hi |= this.view[offset];
        hi += this.view[offset + 3] << 24 >>> 0;
      } else {
        hi = this.view[offset + 1] << 16;
        hi |= this.view[offset + 2] << 8;
        hi |= this.view[offset + 3];
        hi += this.view[offset] << 24 >>> 0;
        offset += 4;
        lo = this.view[offset + 1] << 16;
        lo |= this.view[offset + 2] << 8;
        lo |= this.view[offset + 3];
        lo += this.view[offset] << 24 >>> 0;
      }
      var value = new Long(lo, hi, true);
      if (relative) this.offset += 8;
      return value;
    };

    /**
     * Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}.
     * @function
     * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
     * @returns {!Long}
     * @expose
     */
    ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64;

  } // Long

  // types/floats/float32

  /*
   ieee754 - https://github.com/feross/ieee754

   The MIT License (MIT)

   Copyright (c) Feross Aboukhadijeh

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
  */

  /**
   * Reads an IEEE754 float from a byte array.
   * @param {!Array} buffer
   * @param {number} offset
   * @param {boolean} isLE
   * @param {number} mLen
   * @param {number} nBytes
   * @returns {number}
   * @inner
   */
  function ieee754_read(buffer, offset, isLE, mLen, nBytes) {
    var e, m,
      eLen = nBytes * 8 - mLen - 1,
      eMax = (1 << eLen) - 1,
      eBias = eMax >> 1,
      nBits = -7,
      i = isLE ? (nBytes - 1) : 0,
      d = isLE ? -1 : 1,
      s = buffer[offset + i];

    i += d;

    e = s & ((1 << (-nBits)) - 1);
    s >>= (-nBits);
    nBits += eLen;
    for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}

    m = e & ((1 << (-nBits)) - 1);
    e >>= (-nBits);
    nBits += mLen;
    for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}

    if (e === 0) {
      e = 1 - eBias;
    } else if (e === eMax) {
      return m ? NaN : ((s ? -1 : 1) * Infinity);
    } else {
      m = m + Math.pow(2, mLen);
      e = e - eBias;
    }
    return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  }

  /**
   * Writes an IEEE754 float to a byte array.
   * @param {!Array} buffer
   * @param {number} value
   * @param {number} offset
   * @param {boolean} isLE
   * @param {number} mLen
   * @param {number} nBytes
   * @inner
   */
  function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) {
    var e, m, c,
      eLen = nBytes * 8 - mLen - 1,
      eMax = (1 << eLen) - 1,
      eBias = eMax >> 1,
      rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
      i = isLE ? 0 : (nBytes - 1),
      d = isLE ? 1 : -1,
      s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;

    value = Math.abs(value);

    if (isNaN(value) || value === Infinity) {
      m = isNaN(value) ? 1 : 0;
      e = eMax;
    } else {
      e = Math.floor(Math.log(value) / Math.LN2);
      if (value * (c = Math.pow(2, -e)) < 1) {
        e--;
        c *= 2;
      }
      if (e + eBias >= 1) {
        value += rt / c;
      } else {
        value += rt * Math.pow(2, 1 - eBias);
      }
      if (value * c >= 2) {
        e++;
        c /= 2;
      }

      if (e + eBias >= eMax) {
        m = 0;
        e = eMax;
      } else if (e + eBias >= 1) {
        m = (value * c - 1) * Math.pow(2, mLen);
        e = e + eBias;
      } else {
        m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
        e = 0;
      }
    }

    for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

    e = (e << mLen) | m;
    eLen += mLen;
    for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

    buffer[offset + i - d] |= s * 128;
  }

  /**
   * Writes a 32bit float.
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.writeFloat32 = function (value, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof value !== 'number')
        throw TypeError("Illegal value: " + value + " (not a number)");
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    offset += 4;
    var capacity8 = this.buffer.byteLength;
    if (offset > capacity8)
      this.resize((capacity8 *= 2) > offset ? capacity8 : offset);
    offset -= 4;
    ieee754_write(this.view, value, offset, this.littleEndian, 23, 4);
    if (relative) this.offset += 4;
    return this;
  };

  /**
   * Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}.
   * @function
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32;

  /**
   * Reads a 32bit float.
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
   * @returns {number}
   * @expose
   */
  ByteBufferPrototype.readFloat32 = function (offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 4 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 4 + ") <= " + this.buffer.byteLength);
    }
    var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4);
    if (relative) this.offset += 4;
    return value;
  };

  /**
   * Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}.
   * @function
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
   * @returns {number}
   * @expose
   */
  ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32;

  // types/floats/float64

  /**
   * Writes a 64bit float.
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.writeFloat64 = function (value, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof value !== 'number')
        throw TypeError("Illegal value: " + value + " (not a number)");
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    offset += 8;
    var capacity9 = this.buffer.byteLength;
    if (offset > capacity9)
      this.resize((capacity9 *= 2) > offset ? capacity9 : offset);
    offset -= 8;
    ieee754_write(this.view, value, offset, this.littleEndian, 52, 8);
    if (relative) this.offset += 8;
    return this;
  };

  /**
   * Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}.
   * @function
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64;

  /**
   * Reads a 64bit float.
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
   * @returns {number}
   * @expose
   */
  ByteBufferPrototype.readFloat64 = function (offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 8 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 8 + ") <= " + this.buffer.byteLength);
    }
    var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8);
    if (relative) this.offset += 8;
    return value;
  };

  /**
   * Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}.
   * @function
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
   * @returns {number}
   * @expose
   */
  ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64;

  // types/varints/varint32

  /**
   * Maximum number of bytes required to store a 32bit base 128 variable-length integer.
   * @type {number}
   * @const
   * @expose
   */
  ByteBuffer.MAX_VARINT32_BYTES = 5;

  /**
   * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer.
   * @param {number} value Value to encode
   * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES}
   * @expose
   */
  ByteBuffer.calculateVarint32 = function (value) {
    // ref: src/google/protobuf/io/coded_stream.cc
    value = value >>> 0;
    if (value < 1 << 7) return 1;
    else if (value < 1 << 14) return 2;
    else if (value < 1 << 21) return 3;
    else if (value < 1 << 28) return 4;
    else return 5;
  };

  /**
   * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding.
   * @param {number} n Signed 32bit integer
   * @returns {number} Unsigned zigzag encoded 32bit integer
   * @expose
   */
  ByteBuffer.zigZagEncode32 = function (n) {
    return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h
  };

  /**
   * Decodes a zigzag encoded signed 32bit integer.
   * @param {number} n Unsigned zigzag encoded 32bit integer
   * @returns {number} Signed 32bit integer
   * @expose
   */
  ByteBuffer.zigZagDecode32 = function (n) {
    return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h
  };

  /**
   * Writes a 32bit base 128 variable-length integer.
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  written if omitted.
   * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
   * @expose
   */
  ByteBufferPrototype.writeVarint32 = function (value, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof value !== 'number' || value % 1 !== 0)
        throw TypeError("Illegal value: " + value + " (not an integer)");
      value |= 0;
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    var size = ByteBuffer.calculateVarint32(value),
      b;
    offset += size;
    var capacity10 = this.buffer.byteLength;
    if (offset > capacity10)
      this.resize((capacity10 *= 2) > offset ? capacity10 : offset);
    offset -= size;
    value >>>= 0;
    while (value >= 0x80) {
      b = (value & 0x7f) | 0x80;
      this.view[offset++] = b;
      value >>>= 7;
    }
    this.view[offset++] = value;
    if (relative) {
      this.offset = offset;
      return this;
    }
    return size;
  };

  /**
   * Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer.
   * @param {number} value Value to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  written if omitted.
   * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
   * @expose
   */
  ByteBufferPrototype.writeVarint32ZigZag = function (value, offset) {
    return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset);
  };

  /**
   * Reads a 32bit base 128 variable-length integer.
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  written if omitted.
   * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
   *  and the actual number of bytes read.
   * @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available
   *  to fully decode the varint.
   * @expose
   */
  ByteBufferPrototype.readVarint32 = function (offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 1 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 1 + ") <= " + this.buffer.byteLength);
    }
    var c = 0,
      value = 0 >>> 0,
      b;
    do {
      if (!this.noAssert && offset > this.limit) {
        var err = Error("Truncated");
        err['truncated'] = true;
        throw err;
      }
      b = this.view[offset++];
      if (c < 5)
        value |= (b & 0x7f) << (7 * c);
      ++c;
    } while ((b & 0x80) !== 0);
    value |= 0;
    if (relative) {
      this.offset = offset;
      return value;
    }
    return {
      "value": value,
      "length": c
    };
  };

  /**
   * Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer.
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  written if omitted.
   * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
   *  and the actual number of bytes read.
   * @throws {Error} If it's not a valid varint
   * @expose
   */
  ByteBufferPrototype.readVarint32ZigZag = function (offset) {
    var val = this.readVarint32(offset);
    if (typeof val === 'object')
      val["value"] = ByteBuffer.zigZagDecode32(val["value"]);
    else
      val = ByteBuffer.zigZagDecode32(val);
    return val;
  };

  // types/varints/varint64

  if (Long) {

    /**
     * Maximum number of bytes required to store a 64bit base 128 variable-length integer.
     * @type {number}
     * @const
     * @expose
     */
    ByteBuffer.MAX_VARINT64_BYTES = 10;

    /**
     * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer.
     * @param {number|!Long} value Value to encode
     * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES}
     * @expose
     */
    ByteBuffer.calculateVarint64 = function (value) {
      if (typeof value === 'number')
        value = Long.fromNumber(value);
      else if (typeof value === 'string')
        value = Long.fromString(value);
      // ref: src/google/protobuf/io/coded_stream.cc
      var part0 = value.toInt() >>> 0,
        part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
        part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
      if (part2 == 0) {
        if (part1 == 0) {
          if (part0 < 1 << 14)
            return part0 < 1 << 7 ? 1 : 2;
          else
            return part0 < 1 << 21 ? 3 : 4;
        } else {
          if (part1 < 1 << 14)
            return part1 < 1 << 7 ? 5 : 6;
          else
            return part1 < 1 << 21 ? 7 : 8;
        }
      } else
        return part2 < 1 << 7 ? 9 : 10;
    };

    /**
     * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding.
     * @param {number|!Long} value Signed long
     * @returns {!Long} Unsigned zigzag encoded long
     * @expose
     */
    ByteBuffer.zigZagEncode64 = function (value) {
      if (typeof value === 'number')
        value = Long.fromNumber(value, false);
      else if (typeof value === 'string')
        value = Long.fromString(value, false);
      else if (value.unsigned !== false) value = value.toSigned();
      // ref: src/google/protobuf/wire_format_lite.h
      return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned();
    };

    /**
     * Decodes a zigzag encoded signed 64bit integer.
     * @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number
     * @returns {!Long} Signed long
     * @expose
     */
    ByteBuffer.zigZagDecode64 = function (value) {
      if (typeof value === 'number')
        value = Long.fromNumber(value, false);
      else if (typeof value === 'string')
        value = Long.fromString(value, false);
      else if (value.unsigned !== false) value = value.toSigned();
      // ref: src/google/protobuf/wire_format_lite.h
      return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned();
    };

    /**
     * Writes a 64bit base 128 variable-length integer.
     * @param {number|Long} value Value to write
     * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
     *  written if omitted.
     * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
     * @expose
     */
    ByteBufferPrototype.writeVarint64 = function (value, offset) {
      var relative = typeof offset === 'undefined';
      if (relative) offset = this.offset;
      if (!this.noAssert) {
        if (typeof value === 'number')
          value = Long.fromNumber(value);
        else if (typeof value === 'string')
          value = Long.fromString(value);
        else if (!(value && value instanceof Long))
          throw TypeError("Illegal value: " + value + " (not an integer or Long)");
        if (typeof offset !== 'number' || offset % 1 !== 0)
          throw TypeError("Illegal offset: " + offset + " (not an integer)");
        offset >>>= 0;
        if (offset < 0 || offset + 0 > this.buffer.byteLength)
          throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
      }
      if (typeof value === 'number')
        value = Long.fromNumber(value, false);
      else if (typeof value === 'string')
        value = Long.fromString(value, false);
      else if (value.unsigned !== false) value = value.toSigned();
      var size = ByteBuffer.calculateVarint64(value),
        part0 = value.toInt() >>> 0,
        part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
        part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
      offset += size;
      var capacity11 = this.buffer.byteLength;
      if (offset > capacity11)
        this.resize((capacity11 *= 2) > offset ? capacity11 : offset);
      offset -= size;
      switch (size) {
      case 10:
        this.view[offset + 9] = (part2 >>> 7) & 0x01;
      case 9:
        this.view[offset + 8] = size !== 9 ? (part2) | 0x80 : (part2) & 0x7F;
      case 8:
        this.view[offset + 7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
      case 7:
        this.view[offset + 6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
      case 6:
        this.view[offset + 5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
      case 5:
        this.view[offset + 4] = size !== 5 ? (part1) | 0x80 : (part1) & 0x7F;
      case 4:
        this.view[offset + 3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
      case 3:
        this.view[offset + 2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
      case 2:
        this.view[offset + 1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
      case 1:
        this.view[offset] = size !== 1 ? (part0) | 0x80 : (part0) & 0x7F;
      }
      if (relative) {
        this.offset += size;
        return this;
      } else {
        return size;
      }
    };

    /**
     * Writes a zig-zag encoded 64bit base 128 variable-length integer.
     * @param {number|Long} value Value to write
     * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
     *  written if omitted.
     * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
     * @expose
     */
    ByteBufferPrototype.writeVarint64ZigZag = function (value, offset) {
      return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset);
    };

    /**
     * Reads a 64bit base 128 variable-length integer. Requires Long.js.
     * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
     *  read if omitted.
     * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
     *  the actual number of bytes read.
     * @throws {Error} If it's not a valid varint
     * @expose
     */
    ByteBufferPrototype.readVarint64 = function (offset) {
      var relative = typeof offset === 'undefined';
      if (relative) offset = this.offset;
      if (!this.noAssert) {
        if (typeof offset !== 'number' || offset % 1 !== 0)
          throw TypeError("Illegal offset: " + offset + " (not an integer)");
        offset >>>= 0;
        if (offset < 0 || offset + 1 > this.buffer.byteLength)
          throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 1 + ") <= " + this.buffer.byteLength);
      }
      // ref: src/google/protobuf/io/coded_stream.cc
      var start = offset,
        part0 = 0,
        part1 = 0,
        part2 = 0,
        b = 0;
      b = this.view[offset++];
      part0 = (b & 0x7F);
      if (b & 0x80) {
        b = this.view[offset++];
        part0 |= (b & 0x7F) << 7;
        if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
          b = this.view[offset++];
          part0 |= (b & 0x7F) << 14;
          if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
            b = this.view[offset++];
            part0 |= (b & 0x7F) << 21;
            if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
              b = this.view[offset++];
              part1 = (b & 0x7F);
              if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
                b = this.view[offset++];
                part1 |= (b & 0x7F) << 7;
                if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
                  b = this.view[offset++];
                  part1 |= (b & 0x7F) << 14;
                  if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
                    b = this.view[offset++];
                    part1 |= (b & 0x7F) << 21;
                    if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
                      b = this.view[offset++];
                      part2 = (b & 0x7F);
                      if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
                        b = this.view[offset++];
                        part2 |= (b & 0x7F) << 7;
                        if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
                          throw Error("Buffer overrun");
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
      var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false);
      if (relative) {
        this.offset = offset;
        return value;
      } else {
        return {
          'value': value,
          'length': offset - start
        };
      }
    };

    /**
     * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js.
     * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
     *  read if omitted.
     * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
     *  the actual number of bytes read.
     * @throws {Error} If it's not a valid varint
     * @expose
     */
    ByteBufferPrototype.readVarint64ZigZag = function (offset) {
      var val = this.readVarint64(offset);
      if (val && val['value'] instanceof Long)
        val["value"] = ByteBuffer.zigZagDecode64(val["value"]);
      else
        val = ByteBuffer.zigZagDecode64(val);
      return val;
    };

  } // Long

  // types/strings/cstring

  /**
   * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL
   *  characters itself.
   * @param {string} str String to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  contained in `str` + 1 if omitted.
   * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written
   * @expose
   */
  ByteBufferPrototype.writeCString = function (str, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    var i,
      k = str.length;
    if (!this.noAssert) {
      if (typeof str !== 'string')
        throw TypeError("Illegal str: Not a string");
      for (i = 0; i < k; ++i) {
        if (str.charCodeAt(i) === 0)
          throw RangeError("Illegal str: Contains NULL-characters");
      }
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    // UTF8 strings do not contain zero bytes in between except for the zero character, so:
    k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
    offset += k + 1;
    var capacity12 = this.buffer.byteLength;
    if (offset > capacity12)
      this.resize((capacity12 *= 2) > offset ? capacity12 : offset);
    offset -= k + 1;
    utfx.encodeUTF16toUTF8(stringSource(str), function (b) {
      this.view[offset++] = b;
    }.bind(this));
    this.view[offset++] = 0;
    if (relative) {
      this.offset = offset;
      return this;
    }
    return k;
  };

  /**
   * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters
   *  itself.
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  read if omitted.
   * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
   *  read and the actual number of bytes read.
   * @expose
   */
  ByteBufferPrototype.readCString = function (offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 1 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 1 + ") <= " + this.buffer.byteLength);
    }
    var start = offset,
      temp;
    // UTF8 strings do not contain zero bytes in between except for the zero character itself, so:
    var sd, b = -1;
    utfx.decodeUTF8toUTF16(function () {
      if (b === 0) return null;
      if (offset >= this.limit)
        throw RangeError("Illegal range: Truncated data, " + offset + " < " + this.limit);
      b = this.view[offset++];
      return b === 0 ? null : b;
    }.bind(this), sd = stringDestination(), true);
    if (relative) {
      this.offset = offset;
      return sd();
    } else {
      return {
        "string": sd(),
        "length": offset - start
      };
    }
  };

  // types/strings/istring

  /**
   * Writes a length as uint32 prefixed UTF8 encoded string.
   * @param {string} str String to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  written if omitted.
   * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
   * @expose
   * @see ByteBuffer#writeVarint32
   */
  ByteBufferPrototype.writeIString = function (str, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof str !== 'string')
        throw TypeError("Illegal str: Not a string");
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    var start = offset,
      k;
    k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
    offset += 4 + k;
    var capacity13 = this.buffer.byteLength;
    if (offset > capacity13)
      this.resize((capacity13 *= 2) > offset ? capacity13 : offset);
    offset -= 4 + k;
    if (this.littleEndian) {
      this.view[offset + 3] = (k >>> 24) & 0xFF;
      this.view[offset + 2] = (k >>> 16) & 0xFF;
      this.view[offset + 1] = (k >>> 8) & 0xFF;
      this.view[offset] = k & 0xFF;
    } else {
      this.view[offset] = (k >>> 24) & 0xFF;
      this.view[offset + 1] = (k >>> 16) & 0xFF;
      this.view[offset + 2] = (k >>> 8) & 0xFF;
      this.view[offset + 3] = k & 0xFF;
    }
    offset += 4;
    utfx.encodeUTF16toUTF8(stringSource(str), function (b) {
      this.view[offset++] = b;
    }.bind(this));
    if (offset !== start + 4 + k)
      throw RangeError("Illegal range: Truncated data, " + offset + " == " + (offset + 4 + k));
    if (relative) {
      this.offset = offset;
      return this;
    }
    return offset - start;
  };

  /**
   * Reads a length as uint32 prefixed UTF8 encoded string.
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  read if omitted.
   * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
   *  read and the actual number of bytes read.
   * @expose
   * @see ByteBuffer#readVarint32
   */
  ByteBufferPrototype.readIString = function (offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 4 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 4 + ") <= " + this.buffer.byteLength);
    }
    var temp = 0,
      start = offset,
      str;
    if (this.littleEndian) {
      temp = this.view[offset + 2] << 16;
      temp |= this.view[offset + 1] << 8;
      temp |= this.view[offset];
      temp += this.view[offset + 3] << 24 >>> 0;
    } else {
      temp = this.view[offset + 1] << 16;
      temp |= this.view[offset + 2] << 8;
      temp |= this.view[offset + 3];
      temp += this.view[offset] << 24 >>> 0;
    }
    offset += 4;
    var k = offset + temp,
      sd;
    utfx.decodeUTF8toUTF16(function () {
      return offset < k ? this.view[offset++] : null;
    }.bind(this), sd = stringDestination(), this.noAssert);
    str = sd();
    if (relative) {
      this.offset = offset;
      return str;
    } else {
      return {
        'string': str,
        'length': offset - start
      };
    }
  };

  // types/strings/utf8string

  /**
   * Metrics representing number of UTF8 characters. Evaluates to `c`.
   * @type {string}
   * @const
   * @expose
   */
  ByteBuffer.METRICS_CHARS = 'c';

  /**
   * Metrics representing number of bytes. Evaluates to `b`.
   * @type {string}
   * @const
   * @expose
   */
  ByteBuffer.METRICS_BYTES = 'b';

  /**
   * Writes an UTF8 encoded string.
   * @param {string} str String to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
   * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
   * @expose
   */
  ByteBufferPrototype.writeUTF8String = function (str, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    var k;
    var start = offset;
    k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
    offset += k;
    var capacity14 = this.buffer.byteLength;
    if (offset > capacity14)
      this.resize((capacity14 *= 2) > offset ? capacity14 : offset);
    offset -= k;
    utfx.encodeUTF16toUTF8(stringSource(str), function (b) {
      this.view[offset++] = b;
    }.bind(this));
    if (relative) {
      this.offset = offset;
      return this;
    }
    return offset - start;
  };

  /**
   * Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}.
   * @function
   * @param {string} str String to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
   * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
   * @expose
   */
  ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String;

  /**
   * Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's
   *  `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
   * @param {string} str String to calculate
   * @returns {number} Number of UTF8 characters
   * @expose
   */
  ByteBuffer.calculateUTF8Chars = function (str) {
    return utfx.calculateUTF16asUTF8(stringSource(str))[0];
  };

  /**
   * Calculates the number of UTF8 bytes of a string.
   * @param {string} str String to calculate
   * @returns {number} Number of UTF8 bytes
   * @expose
   */
  ByteBuffer.calculateUTF8Bytes = function (str) {
    return utfx.calculateUTF16asUTF8(stringSource(str))[1];
  };

  /**
   * Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}.
   * @function
   * @param {string} str String to calculate
   * @returns {number} Number of UTF8 bytes
   * @expose
   */
  ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes;

  /**
   * Reads an UTF8 encoded string.
   * @param {number} length Number of characters or bytes to read.
   * @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to
   *  {@link ByteBuffer.METRICS_CHARS}.
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  read if omitted.
   * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
   *  read and the actual number of bytes read.
   * @expose
   */
  ByteBufferPrototype.readUTF8String = function (length, metrics, offset) {
    if (typeof metrics === 'number') {
      offset = metrics;
      metrics = undefined;
    }
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS;
    if (!this.noAssert) {
      if (typeof length !== 'number' || length % 1 !== 0)
        throw TypeError("Illegal length: " + length + " (not an integer)");
      length |= 0;
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    var i = 0,
      start = offset,
      sd;
    if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser
      sd = stringDestination();
      utfx.decodeUTF8(function () {
        return i < length && offset < this.limit ? this.view[offset++] : null;
      }.bind(this), function (cp) {
        ++i;
        utfx.UTF8toUTF16(cp, sd);
      });
      if (i !== length)
        throw RangeError("Illegal range: Truncated data, " + i + " == " + length);
      if (relative) {
        this.offset = offset;
        return sd();
      } else {
        return {
          "string": sd(),
          "length": offset - start
        };
      }
    } else if (metrics === ByteBuffer.METRICS_BYTES) {
      if (!this.noAssert) {
        if (typeof offset !== 'number' || offset % 1 !== 0)
          throw TypeError("Illegal offset: " + offset + " (not an integer)");
        offset >>>= 0;
        if (offset < 0 || offset + length > this.buffer.byteLength)
          throw RangeError("Illegal offset: 0 <= " + offset + " (+" + length + ") <= " + this.buffer.byteLength);
      }
      var k = offset + length;
      utfx.decodeUTF8toUTF16(function () {
        return offset < k ? this.view[offset++] : null;
      }.bind(this), sd = stringDestination(), this.noAssert);
      if (offset !== k)
        throw RangeError("Illegal range: Truncated data, " + offset + " == " + k);
      if (relative) {
        this.offset = offset;
        return sd();
      } else {
        return {
          'string': sd(),
          'length': offset - start
        };
      }
    } else
      throw TypeError("Unsupported metrics: " + metrics);
  };

  /**
   * Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}.
   * @function
   * @param {number} length Number of characters or bytes to read
   * @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to
   *  {@link ByteBuffer.METRICS_CHARS}.
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  read if omitted.
   * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
   *  read and the actual number of bytes read.
   * @expose
   */
  ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String;

  // types/strings/vstring

  /**
   * Writes a length as varint32 prefixed UTF8 encoded string.
   * @param {string} str String to write
   * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  written if omitted.
   * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
   * @expose
   * @see ByteBuffer#writeVarint32
   */
  ByteBufferPrototype.writeVString = function (str, offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof str !== 'string')
        throw TypeError("Illegal str: Not a string");
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    var start = offset,
      k, l;
    k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
    l = ByteBuffer.calculateVarint32(k);
    offset += l + k;
    var capacity15 = this.buffer.byteLength;
    if (offset > capacity15)
      this.resize((capacity15 *= 2) > offset ? capacity15 : offset);
    offset -= l + k;
    offset += this.writeVarint32(k, offset);
    utfx.encodeUTF16toUTF8(stringSource(str), function (b) {
      this.view[offset++] = b;
    }.bind(this));
    if (offset !== start + k + l)
      throw RangeError("Illegal range: Truncated data, " + offset + " == " + (offset + k + l));
    if (relative) {
      this.offset = offset;
      return this;
    }
    return offset - start;
  };

  /**
   * Reads a length as varint32 prefixed UTF8 encoded string.
   * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  read if omitted.
   * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
   *  read and the actual number of bytes read.
   * @expose
   * @see ByteBuffer#readVarint32
   */
  ByteBufferPrototype.readVString = function (offset) {
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 1 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 1 + ") <= " + this.buffer.byteLength);
    }
    var temp = this.readVarint32(offset),
      start = offset,
      str;
    offset += temp['length'];
    temp = temp['value'];
    var k = offset + temp,
      sd = stringDestination();
    utfx.decodeUTF8toUTF16(function () {
      return offset < k ? this.view[offset++] : null;
    }.bind(this), sd, this.noAssert);
    str = sd();
    if (relative) {
      this.offset = offset;
      return str;
    } else {
      return {
        'string': str,
        'length': offset - start
      };
    }
  };

  /**
   * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended
   *  data's length.
   * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets
   *  will be modified according to the performed read operation.
   * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
   * @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  written if omitted.
   * @returns {!ByteBuffer} this
   * @expose
   * @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|`
   * @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|`
   */
  ByteBufferPrototype.append = function (source, encoding, offset) {
    if (typeof encoding === 'number' || typeof encoding !== 'string') {
      offset = encoding;
      encoding = undefined;
    }
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    if (!(source instanceof ByteBuffer))
      source = ByteBuffer.wrap(source, encoding);
    var length = source.limit - source.offset;
    if (length <= 0) return this; // Nothing to append
    offset += length;
    var capacity16 = this.buffer.byteLength;
    if (offset > capacity16)
      this.resize((capacity16 *= 2) > offset ? capacity16 : offset);
    offset -= length;
    this.view.set(source.view.subarray(source.offset, source.limit), offset);
    source.offset += length;
    if (relative) this.offset += length;
    return this;
  };

  /**
   * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the
      specified offset up to the length of this ByteBuffer's data.
   * @param {!ByteBuffer} target Target ByteBuffer
   * @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  read if omitted.
   * @returns {!ByteBuffer} this
   * @expose
   * @see ByteBuffer#append
   */
  ByteBufferPrototype.appendTo = function (target, offset) {
    target.append(this, offset);
    return this;
  };

  /**
   * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to
   *  disable them if your code already makes sure that everything is valid.
   * @param {boolean} assert `true` to enable assertions, otherwise `false`
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.assert = function (assert) {
    this.noAssert = !assert;
    return this;
  };

  /**
   * Gets the capacity of this ByteBuffer's backing buffer.
   * @returns {number} Capacity of the backing buffer
   * @expose
   */
  ByteBufferPrototype.capacity = function () {
    return this.buffer.byteLength;
  };
  /**
   * Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the
   *  backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}.
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.clear = function () {
    this.offset = 0;
    this.limit = this.buffer.byteLength;
    this.markedOffset = -1;
    return this;
  };

  /**
   * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset},
   *  {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}.
   * @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false`
   * @returns {!ByteBuffer} Cloned instance
   * @expose
   */
  ByteBufferPrototype.clone = function (copy) {
    var bb = new ByteBuffer(0, this.littleEndian, this.noAssert);
    if (copy) {
      bb.buffer = new ArrayBuffer(this.buffer.byteLength);
      bb.view = new Uint8Array(bb.buffer);
    } else {
      bb.buffer = this.buffer;
      bb.view = this.view;
    }
    bb.offset = this.offset;
    bb.markedOffset = this.markedOffset;
    bb.limit = this.limit;
    return bb;
  };

  /**
   * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes
   *  between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and
   *  adapt {@link ByteBuffer#markedOffset} to the same relative position if set.
   * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
   * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.compact = function (begin, end) {
    if (typeof begin === 'undefined') begin = this.offset;
    if (typeof end === 'undefined') end = this.limit;
    if (!this.noAssert) {
      if (typeof begin !== 'number' || begin % 1 !== 0)
        throw TypeError("Illegal begin: Not an integer");
      begin >>>= 0;
      if (typeof end !== 'number' || end % 1 !== 0)
        throw TypeError("Illegal end: Not an integer");
      end >>>= 0;
      if (begin < 0 || begin > end || end > this.buffer.byteLength)
        throw RangeError("Illegal range: 0 <= " + begin + " <= " + end + " <= " + this.buffer.byteLength);
    }
    if (begin === 0 && end === this.buffer.byteLength)
      return this; // Already compacted
    var len = end - begin;
    if (len === 0) {
      this.buffer = EMPTY_BUFFER;
      this.view = null;
      if (this.markedOffset >= 0) this.markedOffset -= begin;
      this.offset = 0;
      this.limit = 0;
      return this;
    }
    var buffer = new ArrayBuffer(len);
    var view = new Uint8Array(buffer);
    view.set(this.view.subarray(begin, end));
    this.buffer = buffer;
    this.view = view;
    if (this.markedOffset >= 0) this.markedOffset -= begin;
    this.offset = 0;
    this.limit = len;
    return this;
  };

  /**
   * Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and
   *  {@link ByteBuffer#limit}.
   * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
   * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
   * @returns {!ByteBuffer} Copy
   * @expose
   */
  ByteBufferPrototype.copy = function (begin, end) {
    if (typeof begin === 'undefined') begin = this.offset;
    if (typeof end === 'undefined') end = this.limit;
    if (!this.noAssert) {
      if (typeof begin !== 'number' || begin % 1 !== 0)
        throw TypeError("Illegal begin: Not an integer");
      begin >>>= 0;
      if (typeof end !== 'number' || end % 1 !== 0)
        throw TypeError("Illegal end: Not an integer");
      end >>>= 0;
      if (begin < 0 || begin > end || end > this.buffer.byteLength)
        throw RangeError("Illegal range: 0 <= " + begin + " <= " + end + " <= " + this.buffer.byteLength);
    }
    if (begin === end)
      return new ByteBuffer(0, this.littleEndian, this.noAssert);
    var capacity = end - begin,
      bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert);
    bb.offset = 0;
    bb.limit = capacity;
    if (bb.markedOffset >= 0) bb.markedOffset -= begin;
    this.copyTo(bb, 0, begin, end);
    return bb;
  };

  /**
   * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and
   *  {@link ByteBuffer#limit}.
   * @param {!ByteBuffer} target Target ByteBuffer
   * @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset}
   *  by the number of bytes copied if omitted.
   * @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the
   *  number of bytes copied if omitted.
   * @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit}
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.copyTo = function (target, targetOffset, sourceOffset, sourceLimit) {
    var relative,
      targetRelative;
    if (!this.noAssert) {
      if (!ByteBuffer.isByteBuffer(target))
        throw TypeError("Illegal target: Not a ByteBuffer");
    }
    targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0;
    sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0;
    sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0;

    if (targetOffset < 0 || targetOffset > target.buffer.byteLength)
      throw RangeError("Illegal target range: 0 <= " + targetOffset + " <= " + target.buffer.byteLength);
    if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength)
      throw RangeError("Illegal source range: 0 <= " + sourceOffset + " <= " + this.buffer.byteLength);

    var len = sourceLimit - sourceOffset;
    if (len === 0)
      return target; // Nothing to copy

    target.ensureCapacity(targetOffset + len);

    target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset);

    if (relative) this.offset += len;
    if (targetRelative) target.offset += len;

    return this;
  };

  /**
   * Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the
   *  current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity,
   *  the required capacity will be used instead.
   * @param {number} capacity Required capacity
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.ensureCapacity = function (capacity) {
    var current = this.buffer.byteLength;
    if (current < capacity)
      return this.resize((current *= 2) > capacity ? current : capacity);
    return this;
  };

  /**
   * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between
   *  {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
   * @param {number|string} value Byte value to fill with. If given as a string, the first character is used.
   * @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes
   *  written if omitted. defaults to {@link ByteBuffer#offset}.
   * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
   * @returns {!ByteBuffer} this
   * @expose
   * @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes
   */
  ByteBufferPrototype.fill = function (value, begin, end) {
    var relative = typeof begin === 'undefined';
    if (relative) begin = this.offset;
    if (typeof value === 'string' && value.length > 0)
      value = value.charCodeAt(0);
    if (typeof begin === 'undefined') begin = this.offset;
    if (typeof end === 'undefined') end = this.limit;
    if (!this.noAssert) {
      if (typeof value !== 'number' || value % 1 !== 0)
        throw TypeError("Illegal value: " + value + " (not an integer)");
      value |= 0;
      if (typeof begin !== 'number' || begin % 1 !== 0)
        throw TypeError("Illegal begin: Not an integer");
      begin >>>= 0;
      if (typeof end !== 'number' || end % 1 !== 0)
        throw TypeError("Illegal end: Not an integer");
      end >>>= 0;
      if (begin < 0 || begin > end || end > this.buffer.byteLength)
        throw RangeError("Illegal range: 0 <= " + begin + " <= " + end + " <= " + this.buffer.byteLength);
    }
    if (begin >= end)
      return this; // Nothing to fill
    while (begin < end) this.view[begin++] = value;
    if (relative) this.offset = begin;
    return this;
  };

  /**
   * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and
   *  `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete.
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.flip = function () {
    this.limit = this.offset;
    this.offset = 0;
    return this;
  };
  /**
   * Marks an offset on this ByteBuffer to be used later.
   * @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}.
   * @returns {!ByteBuffer} this
   * @throws {TypeError} If `offset` is not a valid number
   * @throws {RangeError} If `offset` is out of bounds
   * @see ByteBuffer#reset
   * @expose
   */
  ByteBufferPrototype.mark = function (offset) {
    offset = typeof offset === 'undefined' ? this.offset : offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    this.markedOffset = offset;
    return this;
  };
  /**
   * Sets the byte order.
   * @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.order = function (littleEndian) {
    if (!this.noAssert) {
      if (typeof littleEndian !== 'boolean')
        throw TypeError("Illegal littleEndian: Not a boolean");
    }
    this.littleEndian = !!littleEndian;
    return this;
  };

  /**
   * Switches (to) little endian byte order.
   * @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.LE = function (littleEndian) {
    this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true;
    return this;
  };

  /**
   * Switches (to) big endian byte order.
   * @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.BE = function (bigEndian) {
    this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false;
    return this;
  };
  /**
   * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the
   *  prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
   *  will be resized and its contents moved accordingly.
   * @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be
   *  modified according to the performed read operation.
   * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
   * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
   *  prepended if omitted.
   * @returns {!ByteBuffer} this
   * @expose
   * @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|`
   * @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|`
   */
  ByteBufferPrototype.prepend = function (source, encoding, offset) {
    if (typeof encoding === 'number' || typeof encoding !== 'string') {
      offset = encoding;
      encoding = undefined;
    }
    var relative = typeof offset === 'undefined';
    if (relative) offset = this.offset;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: " + offset + " (not an integer)");
      offset >>>= 0;
      if (offset < 0 || offset + 0 > this.buffer.byteLength)
        throw RangeError("Illegal offset: 0 <= " + offset + " (+" + 0 + ") <= " + this.buffer.byteLength);
    }
    if (!(source instanceof ByteBuffer))
      source = ByteBuffer.wrap(source, encoding);
    var len = source.limit - source.offset;
    if (len <= 0) return this; // Nothing to prepend
    var diff = len - offset;
    if (diff > 0) { // Not enough space before offset, so resize + move
      var buffer = new ArrayBuffer(this.buffer.byteLength + diff);
      var view = new Uint8Array(buffer);
      view.set(this.view.subarray(offset, this.buffer.byteLength), len);
      this.buffer = buffer;
      this.view = view;
      this.offset += diff;
      if (this.markedOffset >= 0) this.markedOffset += diff;
      this.limit += diff;
      offset += diff;
    } else {
      var arrayView = new Uint8Array(this.buffer);
    }
    this.view.set(source.view.subarray(source.offset, source.limit), offset - len);

    source.offset = source.limit;
    if (relative)
      this.offset -= len;
    return this;
  };

  /**
   * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the
   *  prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
   *  will be resized and its contents moved accordingly.
   * @param {!ByteBuffer} target Target ByteBuffer
   * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
   *  prepended if omitted.
   * @returns {!ByteBuffer} this
   * @expose
   * @see ByteBuffer#prepend
   */
  ByteBufferPrototype.prependTo = function (target, offset) {
    target.prepend(this, offset);
    return this;
  };
  /**
   * Prints debug information about this ByteBuffer's contents.
   * @param {function(string)=} out Output function to call, defaults to console.log
   * @expose
   */
  ByteBufferPrototype.printDebug = function (out) {
    if (typeof out !== 'function') out = console.log.bind(console);
    out(
      this.toString() + "\n" +
      "-------------------------------------------------------------------\n" +
      this.toDebug( /* columns */ true)
    );
  };

  /**
   * Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and
   *  {@link ByteBuffer#limit}, so this returns `limit - offset`.
   * @returns {number} Remaining readable bytes. May be negative if `offset > limit`.
   * @expose
   */
  ByteBufferPrototype.remaining = function () {
    return this.limit - this.offset;
  };
  /**
   * Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark}
   *  before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been
   *  marked, sets `offset = 0`.
   * @returns {!ByteBuffer} this
   * @see ByteBuffer#mark
   * @expose
   */
  ByteBufferPrototype.reset = function () {
    if (this.markedOffset >= 0) {
      this.offset = this.markedOffset;
      this.markedOffset = -1;
    } else {
      this.offset = 0;
    }
    return this;
  };
  /**
   * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that
   *  large or larger.
   * @param {number} capacity Capacity required
   * @returns {!ByteBuffer} this
   * @throws {TypeError} If `capacity` is not a number
   * @throws {RangeError} If `capacity < 0`
   * @expose
   */
  ByteBufferPrototype.resize = function (capacity) {
    if (!this.noAssert) {
      if (typeof capacity !== 'number' || capacity % 1 !== 0)
        throw TypeError("Illegal capacity: " + capacity + " (not an integer)");
      capacity |= 0;
      if (capacity < 0)
        throw RangeError("Illegal capacity: 0 <= " + capacity);
    }
    if (this.buffer.byteLength < capacity) {
      var buffer = new ArrayBuffer(capacity);
      var view = new Uint8Array(buffer);
      view.set(this.view);
      this.buffer = buffer;
      this.view = view;
    }
    return this;
  };
  /**
   * Reverses this ByteBuffer's contents.
   * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
   * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.reverse = function (begin, end) {
    if (typeof begin === 'undefined') begin = this.offset;
    if (typeof end === 'undefined') end = this.limit;
    if (!this.noAssert) {
      if (typeof begin !== 'number' || begin % 1 !== 0)
        throw TypeError("Illegal begin: Not an integer");
      begin >>>= 0;
      if (typeof end !== 'number' || end % 1 !== 0)
        throw TypeError("Illegal end: Not an integer");
      end >>>= 0;
      if (begin < 0 || begin > end || end > this.buffer.byteLength)
        throw RangeError("Illegal range: 0 <= " + begin + " <= " + end + " <= " + this.buffer.byteLength);
    }
    if (begin === end)
      return this; // Nothing to reverse
    Array.prototype.reverse.call(this.view.subarray(begin, end));
    return this;
  };
  /**
   * Skips the next `length` bytes. This will just advance
   * @param {number} length Number of bytes to skip. May also be negative to move the offset back.
   * @returns {!ByteBuffer} this
   * @expose
   */
  ByteBufferPrototype.skip = function (length) {
    if (!this.noAssert) {
      if (typeof length !== 'number' || length % 1 !== 0)
        throw TypeError("Illegal length: " + length + " (not an integer)");
      length |= 0;
    }
    var offset = this.offset + length;
    if (!this.noAssert) {
      if (offset < 0 || offset > this.buffer.byteLength)
        throw RangeError("Illegal length: 0 <= " + this.offset + " + " + length + " <= " + this.buffer.byteLength);
    }
    this.offset = offset;
    return this;
  };

  /**
   * Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`.
   * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
   * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
   * @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer}
   * @expose
   */
  ByteBufferPrototype.slice = function (begin, end) {
    if (typeof begin === 'undefined') begin = this.offset;
    if (typeof end === 'undefined') end = this.limit;
    if (!this.noAssert) {
      if (typeof begin !== 'number' || begin % 1 !== 0)
        throw TypeError("Illegal begin: Not an integer");
      begin >>>= 0;
      if (typeof end !== 'number' || end % 1 !== 0)
        throw TypeError("Illegal end: Not an integer");
      end >>>= 0;
      if (begin < 0 || begin > end || end > this.buffer.byteLength)
        throw RangeError("Illegal range: 0 <= " + begin + " <= " + end + " <= " + this.buffer.byteLength);
    }
    var bb = this.clone();
    bb.offset = begin;
    bb.limit = end;
    return bb;
  };
  /**
   * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between
   *  {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
   * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if
   *  possible. Defaults to `false`
   * @returns {!ArrayBuffer} Contents as an ArrayBuffer
   * @expose
   */
  ByteBufferPrototype.toBuffer = function (forceCopy) {
    var offset = this.offset,
      limit = this.limit;
    if (!this.noAssert) {
      if (typeof offset !== 'number' || offset % 1 !== 0)
        throw TypeError("Illegal offset: Not an integer");
      offset >>>= 0;
      if (typeof limit !== 'number' || limit % 1 !== 0)
        throw TypeError("Illegal limit: Not an integer");
      limit >>>= 0;
      if (offset < 0 || offset > limit || limit > this.buffer.byteLength)
        throw RangeError("Illegal range: 0 <= " + offset + " <= " + limit + " <= " + this.buffer.byteLength);
    }
    // NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is
    // possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So:
    if (!forceCopy && offset === 0 && limit === this.buffer.byteLength)
      return this.buffer;
    if (offset === limit)
      return EMPTY_BUFFER;
    var buffer = new ArrayBuffer(limit - offset);
    new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0);
    return buffer;
  };

  /**
   * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
   *  {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}.
   * @function
   * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory.
   *  Defaults to `false`
   * @returns {!ArrayBuffer} Contents as an ArrayBuffer
   * @expose
   */
  ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer;

  /**
   * Converts the ByteBuffer's contents to a string.
   * @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows
   *  direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with
   *  highlighted offsets.
   * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}
   * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
   * @returns {string} String representation
   * @throws {Error} If `encoding` is invalid
   * @expose
   */
  ByteBufferPrototype.toString = function (encoding, begin, end) {
    if (typeof encoding === 'undefined')
      return "ByteBufferAB(offset=" + this.offset + ",markedOffset=" + this.markedOffset + ",limit=" + this.limit + ",capacity=" + this.capacity() + ")";
    if (typeof encoding === 'number')
      encoding = "utf8",
      begin = encoding,
      end = begin;
    switch (encoding) {
    case "utf8":
      return this.toUTF8(begin, end);
    case "base64":
      return this.toBase64(begin, end);
    case "hex":
      return this.toHex(begin, end);
    case "binary":
      return this.toBinary(begin, end);
    case "debug":
      return this.toDebug();
    case "columns":
      return this.toColumns();
    default:
      throw Error("Unsupported encoding: " + encoding);
    }
  };

  // lxiv-embeddable

  /**
   * lxiv-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
   * Released under the Apache License, Version 2.0
   * see: https://github.com/dcodeIO/lxiv for details
   */
  var lxiv = function () {
    "use strict";

    /**
     * lxiv namespace.
     * @type {!Object.<string,*>}
     * @exports lxiv
     */
    var lxiv = {};

    /**
     * Character codes for output.
     * @type {!Array.<number>}
     * @inner
     */
    var aout = [
      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, 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, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47
    ];

    /**
     * Character codes for input.
     * @type {!Array.<number>}
     * @inner
     */
    var ain = [];
    for (var i = 0, k = aout.length; i < k; ++i)
      ain[aout[i]] = i;

    /**
     * Encodes bytes to base64 char codes.
     * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if
     *  there are no more bytes left.
     * @param {!function(number)} dst Characters destination as a function successively called with each encoded char
     *  code.
     */
    lxiv.encode = function (src, dst) {
      var b, t;
      while ((b = src()) !== null) {
        dst(aout[(b >> 2) & 0x3f]);
        t = (b & 0x3) << 4;
        if ((b = src()) !== null) {
          t |= (b >> 4) & 0xf;
          dst(aout[(t | ((b >> 4) & 0xf)) & 0x3f]);
          t = (b & 0xf) << 2;
          if ((b = src()) !== null)
            dst(aout[(t | ((b >> 6) & 0x3)) & 0x3f]),
            dst(aout[b & 0x3f]);
          else
            dst(aout[t & 0x3f]),
            dst(61);
        } else
          dst(aout[t & 0x3f]),
          dst(61),
          dst(61);
      }
    };

    /**
     * Decodes base64 char codes to bytes.
     * @param {!function():number|null} src Characters source as a function returning the next char code respectively
     *  `null` if there are no more characters left.
     * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
     * @throws {Error} If a character code is invalid
     */
    lxiv.decode = function (src, dst) {
      var c, t1, t2;

      function fail(c) {
        throw Error("Illegal character code: " + c);
      }
      while ((c = src()) !== null) {
        t1 = ain[c];
        if (typeof t1 === 'undefined') fail(c);
        if ((c = src()) !== null) {
          t2 = ain[c];
          if (typeof t2 === 'undefined') fail(c);
          dst((t1 << 2) >>> 0 | (t2 & 0x30) >> 4);
          if ((c = src()) !== null) {
            t1 = ain[c];
            if (typeof t1 === 'undefined')
              if (c === 61) break;
              else fail(c);
            dst(((t2 & 0xf) << 4) >>> 0 | (t1 & 0x3c) >> 2);
            if ((c = src()) !== null) {
              t2 = ain[c];
              if (typeof t2 === 'undefined')
                if (c === 61) break;
                else fail(c);
              dst(((t1 & 0x3) << 6) >>> 0 | t2);
            }
          }
        }
      }
    };

    /**
     * Tests if a string is valid base64.
     * @param {string} str String to test
     * @returns {boolean} `true` if valid, otherwise `false`
     */
    lxiv.test = function (str) {
      return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str);
    };

    return lxiv;
  }();

  // encodings/base64

  /**
   * Encodes this ByteBuffer's contents to a base64 encoded string.
   * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}.
   * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}.
   * @returns {string} Base64 encoded string
   * @throws {RangeError} If `begin` or `end` is out of bounds
   * @expose
   */
  ByteBufferPrototype.toBase64 = function (begin, end) {
    if (typeof begin === 'undefined')
      begin = this.offset;
    if (typeof end === 'undefined')
      end = this.limit;
    begin = begin | 0;
    end = end | 0;
    if (begin < 0 || end > this.capacity || begin > end)
      throw RangeError("begin, end");
    var sd;
    lxiv.encode(function () {
      return begin < end ? this.view[begin++] : null;
    }.bind(this), sd = stringDestination());
    return sd();
  };

  /**
   * Decodes a base64 encoded string to a ByteBuffer.
   * @param {string} str String to decode
   * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
   *  {@link ByteBuffer.DEFAULT_ENDIAN}.
   * @returns {!ByteBuffer} ByteBuffer
   * @expose
   */
  ByteBuffer.fromBase64 = function (str, littleEndian) {
    if (typeof str !== 'string')
      throw TypeError("str");
    var bb = new ByteBuffer(str.length / 4 * 3, littleEndian),
      i = 0;
    lxiv.decode(stringSource(str), function (b) {
      bb.view[i++] = b;
    });
    bb.limit = i;
    return bb;
  };

  /**
   * Encodes a binary string to base64 like `window.btoa` does.
   * @param {string} str Binary string
   * @returns {string} Base64 encoded string
   * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa
   * @expose
   */
  ByteBuffer.btoa = function (str) {
    return ByteBuffer.fromBinary(str).toBase64();
  };

  /**
   * Decodes a base64 encoded string to binary like `window.atob` does.
   * @param {string} b64 Base64 encoded string
   * @returns {string} Binary string
   * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob
   * @expose
   */
  ByteBuffer.atob = function (b64) {
    return ByteBuffer.fromBase64(b64).toBinary();
  };

  // encodings/binary

  /**
   * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
   * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
   * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
   * @returns {string} Binary encoded string
   * @throws {RangeError} If `offset > limit`
   * @expose
   */
  ByteBufferPrototype.toBinary = function (begin, end) {
    if (typeof begin === 'undefined')
      begin = this.offset;
    if (typeof end === 'undefined')
      end = this.limit;
    begin |= 0;
    end |= 0;
    if (begin < 0 || end > this.capacity() || begin > end)
      throw RangeError("begin, end");
    if (begin === end)
      return "";
    var chars = [],
      parts = [];
    while (begin < end) {
      chars.push(this.view[begin++]);
      if (chars.length >= 1024)
        parts.push(String.fromCharCode.apply(String, chars)),
        chars = [];
    }
    return parts.join('') + String.fromCharCode.apply(String, chars);
  };

  /**
   * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
   * @param {string} str String to decode
   * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
   *  {@link ByteBuffer.DEFAULT_ENDIAN}.
   * @returns {!ByteBuffer} ByteBuffer
   * @expose
   */
  ByteBuffer.fromBinary = function (str, littleEndian) {
    if (typeof str !== 'string')
      throw TypeError("str");
    var i = 0,
      k = str.length,
      charCode,
      bb = new ByteBuffer(k, littleEndian);
    while (i < k) {
      charCode = str.charCodeAt(i);
      if (charCode > 0xff)
        throw RangeError("illegal char code: " + charCode);
      bb.view[i++] = charCode;
    }
    bb.limit = k;
    return bb;
  };

  // encodings/debug

  /**
   * Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
   * * `<` : offset,
   * * `'` : markedOffset,
   * * `>` : limit,
   * * `|` : offset and limit,
   * * `[` : offset and markedOffset,
   * * `]` : markedOffset and limit,
   * * `!` : offset, markedOffset and limit
   * @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false`
   * @returns {string|!Array.<string>} Debug string or array of lines if `asArray = true`
   * @expose
   * @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3`
   * @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4`
   * @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1`
   * @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1`
   */
  ByteBufferPrototype.toDebug = function (columns) {
    var i = -1,
      k = this.buffer.byteLength,
      b,
      hex = "",
      asc = "",
      out = "";
    while (i < k) {
      if (i !== -1) {
        b = this.view[i];
        if (b < 0x10) hex += "0" + b.toString(16).toUpperCase();
        else hex += b.toString(16).toUpperCase();
        if (columns)
          asc += b > 32 && b < 127 ? String.fromCharCode(b) : '.';
      }
      ++i;
      if (columns) {
        if (i > 0 && i % 16 === 0 && i !== k) {
          while (hex.length < 3 * 16 + 3) hex += " ";
          out += hex + asc + "\n";
          hex = asc = "";
        }
      }
      if (i === this.offset && i === this.limit)
        hex += i === this.markedOffset ? "!" : "|";
      else if (i === this.offset)
        hex += i === this.markedOffset ? "[" : "<";
      else if (i === this.limit)
        hex += i === this.markedOffset ? "]" : ">";
      else
        hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : "");
    }
    if (columns && hex !== " ") {
      while (hex.length < 3 * 16 + 3)
        hex += " ";
      out += hex + asc + "\n";
    }
    return columns ? out : hex;
  };

  /**
   * Decodes a hex encoded string with marked offsets to a ByteBuffer.
   * @param {string} str Debug string to decode (not be generated with `columns = true`)
   * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
   *  {@link ByteBuffer.DEFAULT_ENDIAN}.
   * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
   *  {@link ByteBuffer.DEFAULT_NOASSERT}.
   * @returns {!ByteBuffer} ByteBuffer
   * @expose
   * @see ByteBuffer#toDebug
   */
  ByteBuffer.fromDebug = function (str, littleEndian, noAssert) {
    var k = str.length,
      bb = new ByteBuffer(((k + 1) / 3) | 0, littleEndian, noAssert);
    var i = 0,
      j = 0,
      ch, b,
      rs = false, // Require symbol next
      ho = false,
      hm = false,
      hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)?
      fail = false;
    while (i < k) {
      switch (ch = str.charAt(i++)) {
      case '!':
        if (!noAssert) {
          if (ho || hm || hl) {
            fail = true;
            break;
          }
          ho = hm = hl = true;
        }
        bb.offset = bb.markedOffset = bb.limit = j;
        rs = false;
        break;
      case '|':
        if (!noAssert) {
          if (ho || hl) {
            fail = true;
            break;
          }
          ho = hl = true;
        }
        bb.offset = bb.limit = j;
        rs = false;
        break;
      case '[':
        if (!noAssert) {
          if (ho || hm) {
            fail = true;
            break;
          }
          ho = hm = true;
        }
        bb.offset = bb.markedOffset = j;
        rs = false;
        break;
      case '<':
        if (!noAssert) {
          if (ho) {
            fail = true;
            break;
          }
          ho = true;
        }
        bb.offset = j;
        rs = false;
        break;
      case ']':
        if (!noAssert) {
          if (hl || hm) {
            fail = true;
            break;
          }
          hl = hm = true;
        }
        bb.limit = bb.markedOffset = j;
        rs = false;
        break;
      case '>':
        if (!noAssert) {
          if (hl) {
            fail = true;
            break;
          }
          hl = true;
        }
        bb.limit = j;
        rs = false;
        break;
      case "'":
        if (!noAssert) {
          if (hm) {
            fail = true;
            break;
          }
          hm = true;
        }
        bb.markedOffset = j;
        rs = false;
        break;
      case ' ':
        rs = false;
        break;
      default:
        if (!noAssert) {
          if (rs) {
            fail = true;
            break;
          }
        }
        b = parseInt(ch + str.charAt(i++), 16);
        if (!noAssert) {
          if (isNaN(b) || b < 0 || b > 255)
            throw TypeError("Illegal str: Not a debug encoded string");
        }
        bb.view[j++] = b;
        rs = true;
      }
      if (fail)
        throw TypeError("Illegal str: Invalid symbol at " + i);
    }
    if (!noAssert) {
      if (!ho || !hl)
        throw TypeError("Illegal str: Missing offset or limit");
      if (j < bb.buffer.byteLength)
        throw TypeError("Illegal str: Not a debug encoded string (is it hex?) " + j + " < " + k);
    }
    return bb;
  };

  // encodings/hex

  /**
   * Encodes this ByteBuffer's contents to a hex encoded string.
   * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
   * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
   * @returns {string} Hex encoded string
   * @expose
   */
  ByteBufferPrototype.toHex = function (begin, end) {
    begin = typeof begin === 'undefined' ? this.offset : begin;
    end = typeof end === 'undefined' ? this.limit : end;
    if (!this.noAssert) {
      if (typeof begin !== 'number' || begin % 1 !== 0)
        throw TypeError("Illegal begin: Not an integer");
      begin >>>= 0;
      if (typeof end !== 'number' || end % 1 !== 0)
        throw TypeError("Illegal end: Not an integer");
      end >>>= 0;
      if (begin < 0 || begin > end || end > this.buffer.byteLength)
        throw RangeError("Illegal range: 0 <= " + begin + " <= " + end + " <= " + this.buffer.byteLength);
    }
    var out = new Array(end - begin),
      b;
    while (begin < end) {
      b = this.view[begin++];
      if (b < 0x10)
        out.push("0", b.toString(16));
      else out.push(b.toString(16));
    }
    return out.join('');
  };

  /**
   * Decodes a hex encoded string to a ByteBuffer.
   * @param {string} str String to decode
   * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
   *  {@link ByteBuffer.DEFAULT_ENDIAN}.
   * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
   *  {@link ByteBuffer.DEFAULT_NOASSERT}.
   * @returns {!ByteBuffer} ByteBuffer
   * @expose
   */
  ByteBuffer.fromHex = function (str, littleEndian, noAssert) {
    if (!noAssert) {
      if (typeof str !== 'string')
        throw TypeError("Illegal str: Not a string");
      if (str.length % 2 !== 0)
        throw TypeError("Illegal str: Length not a multiple of 2");
    }
    var k = str.length,
      bb = new ByteBuffer((k / 2) | 0, littleEndian),
      b;
    for (var i = 0, j = 0; i < k; i += 2) {
      b = parseInt(str.substring(i, i + 2), 16);
      if (!noAssert)
        if (!isFinite(b) || b < 0 || b > 255)
          throw TypeError("Illegal str: Contains non-hex characters");
      bb.view[j++] = b;
    }
    bb.limit = j;
    return bb;
  };

  // utfx-embeddable

  /**
   * utfx-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
   * Released under the Apache License, Version 2.0
   * see: https://github.com/dcodeIO/utfx for details
   */
  var utfx = function () {
    "use strict";

    /**
     * utfx namespace.
     * @inner
     * @type {!Object.<string,*>}
     */
    var utfx = {};

    /**
     * Maximum valid code point.
     * @type {number}
     * @const
     */
    utfx.MAX_CODEPOINT = 0x10FFFF;

    /**
     * Encodes UTF8 code points to UTF8 bytes.
     * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
     *  respectively `null` if there are no more code points left or a single numeric code point.
     * @param {!function(number)} dst Bytes destination as a function successively called with the next byte
     */
    utfx.encodeUTF8 = function (src, dst) {
      var cp = null;
      if (typeof src === 'number')
        cp = src,
        src = function () {
          return null;
        };
      while (cp !== null || (cp = src()) !== null) {
        if (cp < 0x80)
          dst(cp & 0x7F);
        else if (cp < 0x800)
          dst(((cp >> 6) & 0x1F) | 0xC0),
          dst((cp & 0x3F) | 0x80);
        else if (cp < 0x10000)
          dst(((cp >> 12) & 0x0F) | 0xE0),
          dst(((cp >> 6) & 0x3F) | 0x80),
          dst((cp & 0x3F) | 0x80);
        else
          dst(((cp >> 18) & 0x07) | 0xF0),
          dst(((cp >> 12) & 0x3F) | 0x80),
          dst(((cp >> 6) & 0x3F) | 0x80),
          dst((cp & 0x3F) | 0x80);
        cp = null;
      }
    };

    /**
     * Decodes UTF8 bytes to UTF8 code points.
     * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
     *  are no more bytes left.
     * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point.
     * @throws {RangeError} If a starting byte is invalid in UTF8
     * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the
     *  remaining bytes.
     */
    utfx.decodeUTF8 = function (src, dst) {
      var a, b, c, d, fail = function (b) {
        b = b.slice(0, b.indexOf(null));
        var err = Error(b.toString());
        err.name = "TruncatedError";
        err['bytes'] = b;
        throw err;
      };
      while ((a = src()) !== null) {
        if ((a & 0x80) === 0)
          dst(a);
        else if ((a & 0xE0) === 0xC0)
          ((b = src()) === null) && fail([a, b]),
          dst(((a & 0x1F) << 6) | (b & 0x3F));
        else if ((a & 0xF0) === 0xE0)
          ((b = src()) === null || (c = src()) === null) && fail([a, b, c]),
          dst(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F));
        else if ((a & 0xF8) === 0xF0)
          ((b = src()) === null || (c = src()) === null || (d = src()) === null) && fail([a, b, c, d]),
          dst(((a & 0x07) << 18) | ((b & 0x3F) << 12) | ((c & 0x3F) << 6) | (d & 0x3F));
        else throw RangeError("Illegal starting byte: " + a);
      }
    };

    /**
     * Converts UTF16 characters to UTF8 code points.
     * @param {!function():number|null} src Characters source as a function returning the next char code respectively
     *  `null` if there are no more characters left.
     * @param {!function(number)} dst Code points destination as a function successively called with each converted code
     *  point.
     */
    utfx.UTF16toUTF8 = function (src, dst) {
      var c1, c2 = null;
      while (true) {
        if ((c1 = c2 !== null ? c2 : src()) === null)
          break;
        if (c1 >= 0xD800 && c1 <= 0xDFFF) {
          if ((c2 = src()) !== null) {
            if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
              dst((c1 - 0xD800) * 0x400 + c2 - 0xDC00 + 0x10000);
              c2 = null;
              continue;
            }
          }
        }
        dst(c1);
      }
      if (c2 !== null) dst(c2);
    };

    /**
     * Converts UTF8 code points to UTF16 characters.
     * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
     *  respectively `null` if there are no more code points left or a single numeric code point.
     * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
     * @throws {RangeError} If a code point is out of range
     */
    utfx.UTF8toUTF16 = function (src, dst) {
      var cp = null;
      if (typeof src === 'number')
        cp = src, src = function () {
          return null;
        };
      while (cp !== null || (cp = src()) !== null) {
        if (cp <= 0xFFFF)
          dst(cp);
        else
          cp -= 0x10000,
          dst((cp >> 10) + 0xD800),
          dst((cp % 0x400) + 0xDC00);
        cp = null;
      }
    };

    /**
     * Converts and encodes UTF16 characters to UTF8 bytes.
     * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null`
     *  if there are no more characters left.
     * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
     */
    utfx.encodeUTF16toUTF8 = function (src, dst) {
      utfx.UTF16toUTF8(src, function (cp) {
        utfx.encodeUTF8(cp, dst);
      });
    };

    /**
     * Decodes and converts UTF8 bytes to UTF16 characters.
     * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
     *  are no more bytes left.
     * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
     * @throws {RangeError} If a starting byte is invalid in UTF8
     * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes.
     */
    utfx.decodeUTF8toUTF16 = function (src, dst) {
      utfx.decodeUTF8(src, function (cp) {
        utfx.UTF8toUTF16(cp, dst);
      });
    };

    /**
     * Calculates the byte length of an UTF8 code point.
     * @param {number} cp UTF8 code point
     * @returns {number} Byte length
     */
    utfx.calculateCodePoint = function (cp) {
      return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
    };

    /**
     * Calculates the number of UTF8 bytes required to store UTF8 code points.
     * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively
     *  `null` if there are no more code points left.
     * @returns {number} The number of UTF8 bytes required
     */
    utfx.calculateUTF8 = function (src) {
      var cp, l = 0;
      while ((cp = src()) !== null)
        l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
      return l;
    };

    /**
     * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes.
     * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively
     *  `null` if there are no more characters left.
     * @returns {!Array.<number>} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1.
     */
    utfx.calculateUTF16asUTF8 = function (src) {
      var n = 0,
        l = 0;
      utfx.UTF16toUTF8(src, function (cp) {
        ++n;
        l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
      });
      return [n, l];
    };

    return utfx;
  }();

  // encodings/utf8

  /**
   * Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded
   *  string.
   * @returns {string} Hex encoded string
   * @throws {RangeError} If `offset > limit`
   * @expose
   */
  ByteBufferPrototype.toUTF8 = function (begin, end) {
    if (typeof begin === 'undefined') begin = this.offset;
    if (typeof end === 'undefined') end = this.limit;
    if (!this.noAssert) {
      if (typeof begin !== 'number' || begin % 1 !== 0)
        throw TypeError("Illegal begin: Not an integer");
      begin >>>= 0;
      if (typeof end !== 'number' || end % 1 !== 0)
        throw TypeError("Illegal end: Not an integer");
      end >>>= 0;
      if (begin < 0 || begin > end || end > this.buffer.byteLength)
        throw RangeError("Illegal range: 0 <= " + begin + " <= " + end + " <= " + this.buffer.byteLength);
    }
    var sd;
    try {
      utfx.decodeUTF8toUTF16(function () {
        return begin < end ? this.view[begin++] : null;
      }.bind(this), sd = stringDestination());
    } catch (e) {
      if (begin !== end)
        throw RangeError("Illegal range: Truncated data, " + begin + " != " + end);
    }
    return sd();
  };

  /**
   * Decodes an UTF8 encoded string to a ByteBuffer.
   * @param {string} str String to decode
   * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
   *  {@link ByteBuffer.DEFAULT_ENDIAN}.
   * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
   *  {@link ByteBuffer.DEFAULT_NOASSERT}.
   * @returns {!ByteBuffer} ByteBuffer
   * @expose
   */
  ByteBuffer.fromUTF8 = function (str, littleEndian, noAssert) {
    if (!noAssert)
      if (typeof str !== 'string')
        throw TypeError("Illegal str: Not a string");
    var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert),
      i = 0;
    utfx.encodeUTF16toUTF8(stringSource(str), function (b) {
      bb.view[i++] = b;
    });
    bb.limit = i;
    return bb;
  };

  return ByteBuffer;
});
/*
 Copyright 2013 Daniel Wirtz <dcode@dcode.io>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/**
 * @license ProtoBuf.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
 * Released under the Apache License, Version 2.0
 * see: https://github.com/dcodeIO/ProtoBuf.js for details
 */
(function (global, factory) {

  /* AMD */
  if (typeof define === 'function' && define["amd"])
    define(["ByteBuffer"], factory);
  /* CommonJS */
  else if (typeof require === "function" && typeof module === "object" && module && module["exports"])
    module["exports"] = factory(require("./ByteBuffer"), require);
  /* Global */
  else
    (global["dcodeIO"] = global["dcodeIO"] || {})["ProtoBuf"] = factory(global["dcodeIO"]["ByteBuffer"]);

})(this, function (ByteBuffer, nodeRequire) {
  "use strict";

  /**
   * The ProtoBuf namespace.
   * @exports ProtoBuf
   * @namespace
   * @expose
   */
  var ProtoBuf = {};

  /**
   * @type {!function(new: ByteBuffer, ...[*])}
   * @expose
   */
  ProtoBuf.ByteBuffer = ByteBuffer;

  /**
   * @type {?function(new: Long, ...[*])}
   * @expose
   */
  ProtoBuf.Long = ByteBuffer.Long || null;

  /**
   * ProtoBuf.js version.
   * @type {string}
   * @const
   * @expose
   */
  ProtoBuf.VERSION = "4.1.1";

  /**
   * Wire types.
   * @type {Object.<string,number>}
   * @const
   * @expose
   */
  ProtoBuf.WIRE_TYPES = {};

  /**
   * Varint wire type.
   * @type {number}
   * @expose
   */
  ProtoBuf.WIRE_TYPES.VARINT = 0;

  /**
   * Fixed 64 bits wire type.
   * @type {number}
   * @const
   * @expose
   */
  ProtoBuf.WIRE_TYPES.BITS64 = 1;

  /**
   * Length delimited wire type.
   * @type {number}
   * @const
   * @expose
   */
  ProtoBuf.WIRE_TYPES.LDELIM = 2;

  /**
   * Start group wire type.
   * @type {number}
   * @const
   * @expose
   */
  ProtoBuf.WIRE_TYPES.STARTGROUP = 3;

  /**
   * End group wire type.
   * @type {number}
   * @const
   * @expose
   */
  ProtoBuf.WIRE_TYPES.ENDGROUP = 4;

  /**
   * Fixed 32 bits wire type.
   * @type {number}
   * @const
   * @expose
   */
  ProtoBuf.WIRE_TYPES.BITS32 = 5;

  /**
   * Packable wire types.
   * @type {!Array.<number>}
   * @const
   * @expose
   */
  ProtoBuf.PACKABLE_WIRE_TYPES = [
    ProtoBuf.WIRE_TYPES.VARINT,
    ProtoBuf.WIRE_TYPES.BITS64,
    ProtoBuf.WIRE_TYPES.BITS32
  ];

  /**
   * Types.
   * @dict
   * @type {!Object.<string,{name: string, wireType: number, defaultValue: *}>}
   * @const
   * @expose
   */
  ProtoBuf.TYPES = {
    // According to the protobuf spec.
    "int32": {
      name: "int32",
      wireType: ProtoBuf.WIRE_TYPES.VARINT,
      defaultValue: 0
    },
    "uint32": {
      name: "uint32",
      wireType: ProtoBuf.WIRE_TYPES.VARINT,
      defaultValue: 0
    },
    "sint32": {
      name: "sint32",
      wireType: ProtoBuf.WIRE_TYPES.VARINT,
      defaultValue: 0
    },
    "int64": {
      name: "int64",
      wireType: ProtoBuf.WIRE_TYPES.VARINT,
      defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
    },
    "uint64": {
      name: "uint64",
      wireType: ProtoBuf.WIRE_TYPES.VARINT,
      defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
    },
    "sint64": {
      name: "sint64",
      wireType: ProtoBuf.WIRE_TYPES.VARINT,
      defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
    },
    "bool": {
      name: "bool",
      wireType: ProtoBuf.WIRE_TYPES.VARINT,
      defaultValue: false
    },
    "double": {
      name: "double",
      wireType: ProtoBuf.WIRE_TYPES.BITS64,
      defaultValue: 0
    },
    "string": {
      name: "string",
      wireType: ProtoBuf.WIRE_TYPES.LDELIM,
      defaultValue: ""
    },
    "bytes": {
      name: "bytes",
      wireType: ProtoBuf.WIRE_TYPES.LDELIM,
      defaultValue: null // overridden in the code, must be a unique instance
    },
    "fixed32": {
      name: "fixed32",
      wireType: ProtoBuf.WIRE_TYPES.BITS32,
      defaultValue: 0
    },
    "sfixed32": {
      name: "sfixed32",
      wireType: ProtoBuf.WIRE_TYPES.BITS32,
      defaultValue: 0
    },
    "fixed64": {
      name: "fixed64",
      wireType: ProtoBuf.WIRE_TYPES.BITS64,
      defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
    },
    "sfixed64": {
      name: "sfixed64",
      wireType: ProtoBuf.WIRE_TYPES.BITS64,
      defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
    },
    "float": {
      name: "float",
      wireType: ProtoBuf.WIRE_TYPES.BITS32,
      defaultValue: 0
    },
    "enum": {
      name: "enum",
      wireType: ProtoBuf.WIRE_TYPES.VARINT,
      defaultValue: 0
    },
    "message": {
      name: "message",
      wireType: ProtoBuf.WIRE_TYPES.LDELIM,
      defaultValue: null
    },
    "group": {
      name: "group",
      wireType: ProtoBuf.WIRE_TYPES.STARTGROUP,
      defaultValue: null
    }
  };

  /**
   * Valid map key types.
   * @type {!Array.<!Object.<string,{name: string, wireType: number, defaultValue: *}>>}
   * @const
   * @expose
   */
  ProtoBuf.MAP_KEY_TYPES = [
    ProtoBuf.TYPES["int32"],
    ProtoBuf.TYPES["sint32"],
    ProtoBuf.TYPES["sfixed32"],
    ProtoBuf.TYPES["uint32"],
    ProtoBuf.TYPES["fixed32"],
    ProtoBuf.TYPES["int64"],
    ProtoBuf.TYPES["sint64"],
    ProtoBuf.TYPES["sfixed64"],
    ProtoBuf.TYPES["uint64"],
    ProtoBuf.TYPES["fixed64"],
    ProtoBuf.TYPES["bool"],
    ProtoBuf.TYPES["string"],
    ProtoBuf.TYPES["bytes"]
  ];

  /**
   * Minimum field id.
   * @type {number}
   * @const
   * @expose
   */
  ProtoBuf.ID_MIN = 1;

  /**
   * Maximum field id.
   * @type {number}
   * @const
   * @expose
   */
  ProtoBuf.ID_MAX = 0x1FFFFFFF;

  /**
   * If set to `true`, field names will be converted from underscore notation to camel case. Defaults to `false`.
   *  Must be set prior to parsing.
   * @type {boolean}
   * @expose
   */
  ProtoBuf.convertFieldsToCamelCase = false;

  /**
   * By default, messages are populated with (setX, set_x) accessors for each field. This can be disabled by
   *  setting this to `false` prior to building messages.
   * @type {boolean}
   * @expose
   */
  ProtoBuf.populateAccessors = true;

  /**
   * By default, messages are populated with default values if a field is not present on the wire. To disable
   *  this behavior, set this setting to `false`.
   * @type {boolean}
   * @expose
   */
  ProtoBuf.populateDefaults = true;

  /**
   * @alias ProtoBuf.Util
   * @expose
   */
  ProtoBuf.Util = (function () {
    "use strict";

    /**
     * ProtoBuf utilities.
     * @exports ProtoBuf.Util
     * @namespace
     */
    var Util = {};

    /**
     * Flag if running in node or not.
     * @type {boolean}
     * @const
     * @expose
     */
    Util.IS_NODE = !!(
      typeof process === 'object' && process + '' === '[object process]' && !process['browser']
    );

    /**
     * Constructs a XMLHttpRequest object.
     * @return {XMLHttpRequest}
     * @throws {Error} If XMLHttpRequest is not supported
     * @expose
     */
    Util.XHR = function () {
      // No dependencies please, ref: http://www.quirksmode.org/js/xmlhttp.html
      var XMLHttpFactories = [
        function () {
          return new XMLHttpRequest()
        },
        function () {
          return new ActiveXObject("Msxml2.XMLHTTP")
        },
        function () {
          return new ActiveXObject("Msxml3.XMLHTTP")
        },
        function () {
          return new ActiveXObject("Microsoft.XMLHTTP")
        }
      ];
      /** @type {?XMLHttpRequest} */
      var xhr = null;
      for (var i = 0; i < XMLHttpFactories.length; i++) {
        try { xhr = XMLHttpFactories[i](); } catch (e) {
          continue;
        }
        break;
      }
      if (!xhr)
        throw Error("XMLHttpRequest is not supported");
      return xhr;
    };

    /**
     * Fetches a resource.
     * @param {string} path Resource path
     * @param {function(?string)=} callback Callback receiving the resource's contents. If omitted the resource will
     *   be fetched synchronously. If the request failed, contents will be null.
     * @return {?string|undefined} Resource contents if callback is omitted (null if the request failed), else undefined.
     * @expose
     */
    Util.fetch = function (path, callback) {
      if (callback && typeof callback != 'function')
        callback = null;
      if (Util.IS_NODE) {
        if (callback) {
          Util.require("fs").readFile(path, function (err, data) {
            if (err)
              callback(null);
            else
              callback("" + data);
          });
        } else
          try {
            return Util.require("fs").readFileSync(path);
          } catch (e) {
            return null;
          }
      } else {
        var xhr = Util.XHR();
        xhr.open('GET', path, callback ? true : false);
        // xhr.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
        xhr.setRequestHeader('Accept', 'text/plain');
        if (typeof xhr.overrideMimeType === 'function') xhr.overrideMimeType('text/plain');
        if (callback) {
          xhr.onreadystatechange = function () {
            if (xhr.readyState != 4) return;
            if ( /* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
              callback(xhr.responseText);
            else
              callback(null);
          };
          if (xhr.readyState == 4)
            return;
          xhr.send(null);
        } else {
          xhr.send(null);
          if ( /* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
            return xhr.responseText;
          return null;
        }
      }
    };

    /**
     * Requires a node module.
     * @function
     * @param {string} path
     * @returns {*}
     * @throws Error If node require is not supported
     * @expose
     */
    Util.require = Util.IS_NODE ? function (path) {
      return nodeRequire(path);
    } : function (path) {
      throw Error("node require is not supported by this platform")
    };

    /**
     * Converts a string to camel case.
     * @param {string} str
     * @returns {string}
     * @expose
     */
    Util.toCamelCase = function (str) {
      return str.replace(/_([a-zA-Z])/g, function ($0, $1) {
        return $1.toUpperCase();
      });
    };

    return Util;
  })();

  /**
   * Language expressions.
   * @type {!Object.<string,!RegExp>}
   * @expose
   */
  ProtoBuf.Lang = {

    // Characters always ending a statement
    DELIM: /[\s\{\}=;:\[\],'"\(\)<>]/g,

    // Field rules
    RULE: /^(?:required|optional|repeated|map)$/,

    // Field types
    TYPE: /^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,

    // Names
    NAME: /^[a-zA-Z_][a-zA-Z_0-9]*$/,

    // Type definitions
    TYPEDEF: /^[a-zA-Z][a-zA-Z_0-9]*$/,

    // Type references
    TYPEREF: /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)+$/,

    // Fully qualified type references
    FQTYPEREF: /^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/,

    // All numbers
    NUMBER: /^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,

    // Decimal numbers
    NUMBER_DEC: /^(?:[1-9][0-9]*|0)$/,

    // Hexadecimal numbers
    NUMBER_HEX: /^0[xX][0-9a-fA-F]+$/,

    // Octal numbers
    NUMBER_OCT: /^0[0-7]+$/,

    // Floating point numbers
    NUMBER_FLT: /^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,

    // Booleans
    BOOL: /^(?:true|false)$/i,

    // Id numbers
    ID: /^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,

    // Negative id numbers (enum values)
    NEGID: /^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,

    // Whitespaces
    WHITESPACE: /\s/,

    // All strings
    STRING: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,

    // Double quoted strings
    STRING_DQ: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,

    // Single quoted strings
    STRING_SQ: /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g
  };

  /**
   * @alias ProtoBuf.DotProto
   * @expose
   */
  ProtoBuf.DotProto = (function (ProtoBuf, Lang) {
    "use strict";

    /**
     * Utilities to parse .proto files.
     * @exports ProtoBuf.DotProto
     * @namespace
     */
    var DotProto = {};

    /**
     * Constructs a new Tokenizer.
     * @exports ProtoBuf.DotProto.Tokenizer
     * @class prototype tokenizer
     * @param {string} proto Proto to tokenize
     * @constructor
     */
    var Tokenizer = function (proto) {

      /**
       * Source to parse.
       * @type {string}
       * @expose
       */
      this.source = proto + "";

      /**
       * Current index.
       * @type {number}
       * @expose
       */
      this.index = 0;

      /**
       * Current line.
       * @type {number}
       * @expose
       */
      this.line = 1;

      /**
       * Token stack.
       * @type {!Array.<string>}
       * @expose
       */
      this.stack = [];

      /**
       * Opening character of the current string read, if any.
       * @type {?string}
       * @private
       */
      this._stringOpen = null;
    };

    /**
     * @alias ProtoBuf.DotProto.Tokenizer.prototype
     * @inner
     */
    var TokenizerPrototype = Tokenizer.prototype;

    /**
     * Reads a string beginning at the current index.
     * @return {string}
     * @private
     */
    TokenizerPrototype._readString = function () {
      var re = this._stringOpen === '"' ? Lang.STRING_DQ : Lang.STRING_SQ;
      re.lastIndex = this.index - 1; // Include the open quote
      var match = re.exec(this.source);
      if (!match)
        throw Error("unterminated string");
      this.index = re.lastIndex;
      this.stack.push(this._stringOpen);
      this._stringOpen = null;
      return match[1];
    };

    /**
     * Gets the next token and advances by one.
     * @return {?string} Token or `null` on EOF
     * @expose
     */
    TokenizerPrototype.next = function () {
      if (this.stack.length > 0)
        return this.stack.shift();
      if (this.index >= this.source.length)
        return null;
      if (this._stringOpen !== null)
        return this._readString();

      var repeat,
        prev,
        next;
      do {
        repeat = false;

        // Strip white spaces
        while (Lang.WHITESPACE.test(next = this.source.charAt(this.index))) {
          if (next === '\n')
            ++this.line;
          if (++this.index === this.source.length)
            return null;
        }

        // Strip comments
        if (this.source.charAt(this.index) === '/') {
          ++this.index;
          if (this.source.charAt(this.index) === '/') { // Line
            while (this.source.charAt(++this.index) !== '\n')
              if (this.index == this.source.length)
                return null;
              ++this.index;
            ++this.line;
            repeat = true;
          } else if ((next = this.source.charAt(this.index)) === '*') { /* Block */
            do {
              if (next === '\n')
                ++this.line;
              if (++this.index === this.source.length)
                return null;
              prev = next;
              next = this.source.charAt(this.index);
            } while (prev !== '*' || next !== '/');
            ++this.index;
            repeat = true;
          } else
            return '/';
        }
      } while (repeat);

      if (this.index === this.source.length)
        return null;

      // Read the next token
      var end = this.index;
      Lang.DELIM.lastIndex = 0;
      var delim = Lang.DELIM.test(this.source.charAt(end++));
      if (!delim)
        while (end < this.source.length && !Lang.DELIM.test(this.source.charAt(end)))
          ++end;
      var token = this.source.substring(this.index, this.index = end);
      if (token === '"' || token === "'")
        this._stringOpen = token;
      return token;
    };

    /**
     * Peeks for the next token.
     * @return {?string} Token or `null` on EOF
     * @expose
     */
    TokenizerPrototype.peek = function () {
      if (this.stack.length === 0) {
        var token = this.next();
        if (token === null)
          return null;
        this.stack.push(token);
      }
      return this.stack[0];
    };

    /**
     * Skips a specific token and throws if it differs.
     * @param {string} expected Expected token
     * @throws {Error} If the actual token differs
     */
    TokenizerPrototype.skip = function (expected) {
      var actual = this.next();
      if (actual !== expected)
        throw Error("illegal '" + actual + "', '" + expected + "' expected");
    };

    /**
     * Omits an optional token.
     * @param {string} expected Expected optional token
     * @returns {boolean} `true` if the token exists
     */
    TokenizerPrototype.omit = function (expected) {
      if (this.peek() === expected) {
        this.next();
        return true;
      }
      return false;
    };

    /**
     * Returns a string representation of this object.
     * @return {string} String representation as of "Tokenizer(index/length)"
     * @expose
     */
    TokenizerPrototype.toString = function () {
      return "Tokenizer (" + this.index + "/" + this.source.length + " at line " + this.line + ")";
    };

    /**
     * @alias ProtoBuf.DotProto.Tokenizer
     * @expose
     */
    DotProto.Tokenizer = Tokenizer;

    /**
     * Constructs a new Parser.
     * @exports ProtoBuf.DotProto.Parser
     * @class prototype parser
     * @param {string} source Source
     * @constructor
     */
    var Parser = function (source) {

      /**
       * Tokenizer.
       * @type {!ProtoBuf.DotProto.Tokenizer}
       * @expose
       */
      this.tn = new Tokenizer(source);

      /**
       * Whether parsing proto3 or not.
       * @type {boolean}
       */
      this.proto3 = false;
    };

    /**
     * @alias ProtoBuf.DotProto.Parser.prototype
     * @inner
     */
    var ParserPrototype = Parser.prototype;

    /**
     * Parses the source.
     * @returns {!Object}
     * @throws {Error} If the source cannot be parsed
     * @expose
     */
    ParserPrototype.parse = function () {
      var topLevel = {
        "name": "[ROOT]", // temporary
        "package": null,
        "messages": [],
        "enums": [],
        "imports": [],
        "options": {},
        "services": []
          // "syntax": undefined
      };
      var token,
        head = true;
      try {
        while (token = this.tn.next()) {
          switch (token) {
          case 'package':
            if (!head || topLevel["package"] !== null)
              throw Error("unexpected 'package'");
            token = this.tn.next();
            if (!Lang.TYPEREF.test(token))
              throw Error("illegal package name: " + token);
            this.tn.skip(";");
            topLevel["package"] = token;
            break;
          case 'import':
            if (!head)
              throw Error("unexpected 'import'");
            token = this.tn.peek();
            if (token === "public") // ignored
              this.tn.next();
            token = this._readString();
            this.tn.skip(";");
            topLevel["imports"].push(token);
            break;
          case 'syntax':
            if (!head)
              throw Error("unexpected 'syntax'");
            this.tn.skip("=");
            if ((topLevel["syntax"] = this._readString()) === "proto3")
              this.proto3 = true;
            this.tn.skip(";");
            break;
          case 'message':
            this._parseMessage(topLevel, null);
            head = false;
            break;
          case 'enum':
            this._parseEnum(topLevel);
            head = false;
            break;
          case 'option':
            this._parseOption(topLevel);
            break;
          case 'service':
            this._parseService(topLevel);
            break;
          case 'extend':
            this._parseExtend(topLevel);
            break;
          default:
            throw Error("unexpected '" + token + "'");
          }
        }
      } catch (e) {
        e.message = "Parse error at line " + this.tn.line + ": " + e.message;
        throw e;
      }
      delete topLevel["name"];
      return topLevel;
    };

    /**
     * Parses the specified source.
     * @returns {!Object}
     * @throws {Error} If the source cannot be parsed
     * @expose
     */
    Parser.parse = function (source) {
      return new Parser(source).parse();
    };

    // ----- Conversion ------

    /**
     * Converts a numerical string to an id.
     * @param {string} value
     * @param {boolean=} mayBeNegative
     * @returns {number}
     * @inner
     */
    function mkId(value, mayBeNegative) {
      var id = -1,
        sign = 1;
      if (value.charAt(0) == '-') {
        sign = -1;
        value = value.substring(1);
      }
      if (Lang.NUMBER_DEC.test(value))
        id = parseInt(value);
      else if (Lang.NUMBER_HEX.test(value))
        id = parseInt(value.substring(2), 16);
      else if (Lang.NUMBER_OCT.test(value))
        id = parseInt(value.substring(1), 8);
      else
        throw Error("illegal id value: " + (sign < 0 ? '-' : '') + value);
      id = (sign * id) | 0; // Force to 32bit
      if (!mayBeNegative && id < 0)
        throw Error("illegal id value: " + (sign < 0 ? '-' : '') + value);
      return id;
    }

    /**
     * Converts a numerical string to a number.
     * @param {string} val
     * @returns {number}
     * @inner
     */
    function mkNumber(val) {
      var sign = 1;
      if (val.charAt(0) == '-') {
        sign = -1;
        val = val.substring(1);
      }
      if (Lang.NUMBER_DEC.test(val))
        return sign * parseInt(val, 10);
      else if (Lang.NUMBER_HEX.test(val))
        return sign * parseInt(val.substring(2), 16);
      else if (Lang.NUMBER_OCT.test(val))
        return sign * parseInt(val.substring(1), 8);
      else if (val === 'inf')
        return sign * Infinity;
      else if (val === 'nan')
        return NaN;
      else if (Lang.NUMBER_FLT.test(val))
        return sign * parseFloat(val);
      throw Error("illegal number value: " + (sign < 0 ? '-' : '') + val);
    }

    // ----- Reading ------

    /**
     * Reads a string.
     * @returns {string}
     * @private
     */
    ParserPrototype._readString = function () {
      var value = "",
        token,
        delim;
      do {
        delim = this.tn.next();
        if (delim !== "'" && delim !== '"')
          throw Error("illegal string delimiter: " + delim);
        value += this.tn.next();
        this.tn.skip(delim);
        token = this.tn.peek();
      } while (token === '"' || token === '"'); // multi line?
      return value;
    };

    /**
     * Reads a value.
     * @param {boolean=} mayBeTypeRef
     * @returns {number|boolean|string}
     * @private
     */
    ParserPrototype._readValue = function (mayBeTypeRef) {
      var token = this.tn.peek(),
        value;
      if (token === '"' || token === "'")
        return this._readString();
      this.tn.next();
      if (Lang.NUMBER.test(token))
        return mkNumber(token);
      if (Lang.BOOL.test(token))
        return (token.toLowerCase() === 'true');
      if (mayBeTypeRef && Lang.TYPEREF.test(token))
        return token;
      throw Error("illegal value: " + token);

    };

    // ----- Parsing constructs -----

    /**
     * Parses a namespace option.
     * @param {!Object} parent Parent definition
     * @param {boolean=} isList
     * @private
     */
    ParserPrototype._parseOption = function (parent, isList) {
      var token = this.tn.next(),
        custom = false;
      if (token === '(') {
        custom = true;
        token = this.tn.next();
      }
      if (!Lang.TYPEREF.test(token))
      // we can allow options of the form google.protobuf.* since they will just get ignored anyways
      // if (!/google\.protobuf\./.test(token)) // FIXME: Why should that not be a valid typeref?
        throw Error("illegal option name: " + token);
      var name = token;
      if (custom) { // (my_method_option).foo, (my_method_option), some_method_option, (foo.my_option).bar
        this.tn.skip(')');
        name = '(' + name + ')';
        token = this.tn.peek();
        if (Lang.FQTYPEREF.test(token)) {
          name += token;
          this.tn.next();
        }
      }
      this.tn.skip('=');
      this._parseOptionValue(parent, name);
      if (!isList)
        this.tn.skip(";");
    };

    /**
     * Sets an option on the specified options object.
     * @param {!Object.<string,*>} options
     * @param {string} name
     * @param {string|number|boolean} value
     * @inner
     */
    function setOption(options, name, value) {
      if (typeof options[name] === 'undefined')
        options[name] = value;
      else {
        if (!Array.isArray(options[name]))
          options[name] = [options[name]];
        options[name].push(value);
      }
    }

    /**
     * Parses an option value.
     * @param {!Object} parent
     * @param {string} name
     * @private
     */
    ParserPrototype._parseOptionValue = function (parent, name) {
      var token = this.tn.peek();
      if (token !== '{') { // Plain value
        setOption(parent["options"], name, this._readValue(true));
      } else { // Aggregate options
        this.tn.skip("{");
        while ((token = this.tn.next()) !== '}') {
          if (!Lang.NAME.test(token))
            throw Error("illegal option name: " + name + "." + token);
          if (this.tn.omit(":"))
            setOption(parent["options"], name + "." + token, this._readValue(true));
          else
            this._parseOptionValue(parent, name + "." + token);
        }
      }
    };

    /**
     * Parses a service definition.
     * @param {!Object} parent Parent definition
     * @private
     */
    ParserPrototype._parseService = function (parent) {
      var token = this.tn.next();
      if (!Lang.NAME.test(token))
        throw Error("illegal service name at line " + this.tn.line + ": " + token);
      var name = token;
      var svc = {
        "name": name,
        "rpc": {},
        "options": {}
      };
      this.tn.skip("{");
      while ((token = this.tn.next()) !== '}') {
        if (token === "option")
          this._parseOption(svc);
        else if (token === 'rpc')
          this._parseServiceRPC(svc);
        else
          throw Error("illegal service token: " + token);
      }
      this.tn.omit(";");
      parent["services"].push(svc);
    };

    /**
     * Parses a RPC service definition of the form ['rpc', name, (request), 'returns', (response)].
     * @param {!Object} svc Service definition
     * @private
     */
    ParserPrototype._parseServiceRPC = function (svc) {
      var type = "rpc",
        token = this.tn.next();
      if (!Lang.NAME.test(token))
        throw Error("illegal rpc service method name: " + token);
      var name = token;
      var method = {
        "request": null,
        "response": null,
        "request_stream": false,
        "response_stream": false,
        "options": {}
      };
      this.tn.skip("(");
      token = this.tn.next();
      if (token.toLowerCase() === "stream") {
        method["request_stream"] = true;
        token = this.tn.next();
      }
      if (!Lang.TYPEREF.test(token))
        throw Error("illegal rpc service request type: " + token);
      method["request"] = token;
      this.tn.skip(")");
      token = this.tn.next();
      if (token.toLowerCase() !== "returns")
        throw Error("illegal rpc service request type delimiter: " + token);
      this.tn.skip("(");
      token = this.tn.next();
      if (token.toLowerCase() === "stream") {
        method["response_stream"] = true;
        token = this.tn.next();
      }
      method["response"] = token;
      this.tn.skip(")");
      token = this.tn.peek();
      if (token === '{') {
        this.tn.next();
        while ((token = this.tn.next()) !== '}') {
          if (token === 'option')
            this._parseOption(method);
          else
            throw Error("illegal rpc service token: " + token);
        }
        this.tn.omit(";");
      } else
        this.tn.skip(";");
      if (typeof svc[type] === 'undefined')
        svc[type] = {};
      svc[type][name] = method;
    };

    /**
     * Parses a message definition.
     * @param {!Object} parent Parent definition
     * @param {!Object=} fld Field definition if this is a group
     * @returns {!Object}
     * @private
     */
    ParserPrototype._parseMessage = function (parent, fld) {
      var isGroup = !!fld,
        token = this.tn.next();
      var msg = {
        "name": "",
        "fields": [],
        "enums": [],
        "messages": [],
        "options": {},
        "oneofs": {}
        // "extensions": undefined
      };
      if (!Lang.NAME.test(token))
        throw Error("illegal " + (isGroup ? "group" : "message") + " name: " + token);
      msg["name"] = token;
      if (isGroup) {
        this.tn.skip("=");
        fld["id"] = mkId(this.tn.next());
        msg["isGroup"] = true;
      }
      token = this.tn.peek();
      if (token === '[' && fld)
        this._parseFieldOptions(fld);
      this.tn.skip("{");
      while ((token = this.tn.next()) !== '}') {
        if (Lang.RULE.test(token))
          this._parseMessageField(msg, token);
        else if (token === "oneof")
          this._parseMessageOneOf(msg);
        else if (token === "enum")
          this._parseEnum(msg);
        else if (token === "message")
          this._parseMessage(msg);
        else if (token === "option")
          this._parseOption(msg);
        else if (token === "extensions")
          this._parseExtensions(msg);
        else if (token === "extend")
          this._parseExtend(msg);
        else if (Lang.TYPEREF.test(token)) {
          if (!this.proto3)
            throw Error("illegal field rule: " + token);
          this._parseMessageField(msg, "optional", token);
        } else
          throw Error("illegal message token: " + token);
      }
      this.tn.omit(";");
      parent["messages"].push(msg);
      return msg;
    };

    /**
     * Parses a message field.
     * @param {!Object} msg Message definition
     * @param {string} rule Field rule
     * @param {string=} type Field type if already known (never known for maps)
     * @returns {!Object} Field descriptor
     * @private
     */
    ParserPrototype._parseMessageField = function (msg, rule, type) {
      if (!Lang.RULE.test(rule))
        throw Error("illegal message field rule: " + rule);
      var fld = {
        "rule": rule,
        "type": "",
        "name": "",
        "options": {},
        "id": 0
      };
      var token;
      if (rule === "map") {

        if (type)
          throw Error("illegal type: " + type);
        this.tn.skip('<');
        token = this.tn.next();
        if (!Lang.TYPE.test(token) && !Lang.TYPEREF.test(token))
          throw Error("illegal message field type: " + token);
        fld["keytype"] = token;
        this.tn.skip(',');
        token = this.tn.next();
        if (!Lang.TYPE.test(token) && !Lang.TYPEREF.test(token))
          throw Error("illegal message field: " + token);
        fld["type"] = token;
        this.tn.skip('>');
        token = this.tn.next();
        if (!Lang.NAME.test(token))
          throw Error("illegal message field name: " + token);
        fld["name"] = token;
        this.tn.skip("=");
        fld["id"] = mkId(this.tn.next());
        token = this.tn.peek();
        if (token === '[')
          this._parseFieldOptions(fld);
        this.tn.skip(";");

      } else {

        type = typeof type !== 'undefined' ? type : this.tn.next();

        if (type === "group") {

          // "A [legacy] group simply combines a nested message type and a field into a single declaration. In your
          // code, you can treat this message just as if it had a Result type field called result (the latter name is
          // converted to lower-case so that it does not conflict with the former)."
          var grp = this._parseMessage(msg, fld);
          if (!/^[A-Z]/.test(grp["name"]))
            throw Error('illegal group name: ' + grp["name"]);
          fld["type"] = grp["name"];
          fld["name"] = grp["name"].toLowerCase();
          this.tn.omit(";");

        } else {

          if (!Lang.TYPE.test(type) && !Lang.TYPEREF.test(type))
            throw Error("illegal message field type: " + type);
          fld["type"] = type;
          token = this.tn.next();
          if (!Lang.NAME.test(token))
            throw Error("illegal message field name: " + token);
          fld["name"] = token;
          this.tn.skip("=");
          fld["id"] = mkId(this.tn.next());
          token = this.tn.peek();
          if (token === "[")
            this._parseFieldOptions(fld);
          this.tn.skip(";");

        }
      }
      msg["fields"].push(fld);
      return fld;
    };

    /**
     * Parses a message oneof.
     * @param {!Object} msg Message definition
     * @private
     */
    ParserPrototype._parseMessageOneOf = function (msg) {
      var token = this.tn.next();
      if (!Lang.NAME.test(token))
        throw Error("illegal oneof name: " + token);
      var name = token,
        fld;
      var fields = [];
      this.tn.skip("{");
      while ((token = this.tn.next()) !== "}") {
        fld = this._parseMessageField(msg, "optional", token);
        fld["oneof"] = name;
        fields.push(fld["id"]);
      }
      this.tn.omit(";");
      msg["oneofs"][name] = fields;
    };

    /**
     * Parses a set of field option definitions.
     * @param {!Object} fld Field definition
     * @private
     */
    ParserPrototype._parseFieldOptions = function (fld) {
      this.tn.skip("[");
      var token,
        first = true;
      while ((token = this.tn.peek()) !== ']') {
        if (!first)
          this.tn.skip(",");
        this._parseOption(fld, true);
        first = false;
      }
      this.tn.next();
    };

    /**
     * Parses an enum.
     * @param {!Object} msg Message definition
     * @private
     */
    ParserPrototype._parseEnum = function (msg) {
      var enm = {
        "name": "",
        "values": [],
        "options": {}
      };
      var token = this.tn.next();
      if (!Lang.NAME.test(token))
        throw Error("illegal name: " + token);
      enm["name"] = token;
      this.tn.skip("{");
      while ((token = this.tn.next()) !== '}') {
        if (token === "option")
          this._parseOption(enm);
        else {
          if (!Lang.NAME.test(token))
            throw Error("illegal name: " + token);
          this.tn.skip("=");
          var val = {
            "name": token,
            "id": mkId(this.tn.next(), true)
          };
          token = this.tn.peek();
          if (token === "[")
            this._parseFieldOptions({ "options": {} });
          this.tn.skip(";");
          enm["values"].push(val);
        }
      }
      this.tn.omit(";");
      msg["enums"].push(enm);
    };

    /**
     * Parses an extensions statement.
     * @param {!Object} msg Message object
     * @private
     */
    ParserPrototype._parseExtensions = function (msg) {
      var token = this.tn.next(),
        range = [];
      if (token === "min")
        range.push(ProtoBuf.ID_MIN);
      else if (token === "max")
        range.push(ProtoBuf.ID_MAX);
      else
        range.push(mkNumber(token));
      this.tn.skip("to");
      token = this.tn.next();
      if (token === "min")
        range.push(ProtoBuf.ID_MIN);
      else if (token === "max")
        range.push(ProtoBuf.ID_MAX);
      else
        range.push(mkNumber(token));
      this.tn.skip(";");
      msg["extensions"] = range;
    };

    /**
     * Parses an extend block.
     * @param {!Object} parent Parent object
     * @private
     */
    ParserPrototype._parseExtend = function (parent) {
      var token = this.tn.next();
      if (!Lang.TYPEREF.test(token))
        throw Error("illegal extend reference: " + token);
      var ext = {
        "ref": token,
        "fields": []
      };
      this.tn.skip("{");
      while ((token = this.tn.next()) !== '}') {
        if (Lang.RULE.test(token))
          this._parseMessageField(ext, token);
        else if (Lang.TYPEREF.test(token)) {
          if (!this.proto3)
            throw Error("illegal field rule: " + token);
          this._parseMessageField(ext, "optional", token);
        } else
          throw Error("illegal extend token: " + token);
      }
      this.tn.omit(";");
      parent["messages"].push(ext);
      return ext;
    };

    // ----- General -----

    /**
     * Returns a string representation of this parser.
     * @returns {string}
     */
    ParserPrototype.toString = function () {
      return "Parser at line " + this.tn.line;
    };

    /**
     * @alias ProtoBuf.DotProto.Parser
     * @expose
     */
    DotProto.Parser = Parser;

    return DotProto;

  })(ProtoBuf, ProtoBuf.Lang);

  /**
   * @alias ProtoBuf.Reflect
   * @expose
   */
  ProtoBuf.Reflect = (function (ProtoBuf) {
    "use strict";

    /**
     * Reflection types.
     * @exports ProtoBuf.Reflect
     * @namespace
     */
    var Reflect = {};

    /**
     * Constructs a Reflect base class.
     * @exports ProtoBuf.Reflect.T
     * @constructor
     * @abstract
     * @param {!ProtoBuf.Builder} builder Builder reference
     * @param {?ProtoBuf.Reflect.T} parent Parent object
     * @param {string} name Object name
     */
    var T = function (builder, parent, name) {

      /**
       * Builder reference.
       * @type {!ProtoBuf.Builder}
       * @expose
       */
      this.builder = builder;

      /**
       * Parent object.
       * @type {?ProtoBuf.Reflect.T}
       * @expose
       */
      this.parent = parent;

      /**
       * Object name in namespace.
       * @type {string}
       * @expose
       */
      this.name = name;

      /**
       * Fully qualified class name
       * @type {string}
       * @expose
       */
      this.className;
    };

    /**
     * @alias ProtoBuf.Reflect.T.prototype
     * @inner
     */
    var TPrototype = T.prototype;

    /**
     * Returns the fully qualified name of this object.
     * @returns {string} Fully qualified name as of ".PATH.TO.THIS"
     * @expose
     */
    TPrototype.fqn = function () {
      var name = this.name,
        ptr = this;
      do {
        ptr = ptr.parent;
        if (ptr == null)
          break;
        name = ptr.name + "." + name;
      } while (true);
      return name;
    };

    /**
     * Returns a string representation of this Reflect object (its fully qualified name).
     * @param {boolean=} includeClass Set to true to include the class name. Defaults to false.
     * @return String representation
     * @expose
     */
    TPrototype.toString = function (includeClass) {
      return (includeClass ? this.className + " " : "") + this.fqn();
    };

    /**
     * Builds this type.
     * @throws {Error} If this type cannot be built directly
     * @expose
     */
    TPrototype.build = function () {
      throw Error(this.toString(true) + " cannot be built directly");
    };

    /**
     * @alias ProtoBuf.Reflect.T
     * @expose
     */
    Reflect.T = T;

    /**
     * Constructs a new Namespace.
     * @exports ProtoBuf.Reflect.Namespace
     * @param {!ProtoBuf.Builder} builder Builder reference
     * @param {?ProtoBuf.Reflect.Namespace} parent Namespace parent
     * @param {string} name Namespace name
     * @param {Object.<string,*>=} options Namespace options
     * @param {string?} syntax The syntax level of this definition (e.g., proto3)
     * @constructor
     * @extends ProtoBuf.Reflect.T
     */
    var Namespace = function (builder, parent, name, options, syntax) {
      T.call(this, builder, parent, name);

      /**
       * @override
       */
      this.className = "Namespace";

      /**
       * Children inside the namespace.
       * @type {!Array.<ProtoBuf.Reflect.T>}
       */
      this.children = [];

      /**
       * Options.
       * @type {!Object.<string, *>}
       */
      this.options = options || {};

      /**
       * Syntax level (e.g., proto2 or proto3).
       * @type {!string}
       */
      this.syntax = syntax || "proto2";
    };

    /**
     * @alias ProtoBuf.Reflect.Namespace.prototype
     * @inner
     */
    var NamespacePrototype = Namespace.prototype = Object.create(T.prototype);

    /**
     * Returns an array of the namespace's children.
     * @param {ProtoBuf.Reflect.T=} type Filter type (returns instances of this type only). Defaults to null (all children).
     * @return {Array.<ProtoBuf.Reflect.T>}
     * @expose
     */
    NamespacePrototype.getChildren = function (type) {
      type = type || null;
      if (type == null)
        return this.children.slice();
      var children = [];
      for (var i = 0, k = this.children.length; i < k; ++i)
        if (this.children[i] instanceof type)
          children.push(this.children[i]);
      return children;
    };

    /**
     * Adds a child to the namespace.
     * @param {ProtoBuf.Reflect.T} child Child
     * @throws {Error} If the child cannot be added (duplicate)
     * @expose
     */
    NamespacePrototype.addChild = function (child) {
      var other;
      if (other = this.getChild(child.name)) {
        // Try to revert camelcase transformation on collision
        if (other instanceof Message.Field && other.name !== other.originalName && this.getChild(other.originalName) === null)
          other.name = other.originalName; // Revert previous first (effectively keeps both originals)
        else if (child instanceof Message.Field && child.name !== child.originalName && this.getChild(child.originalName) === null)
          child.name = child.originalName;
        else
          throw Error("Duplicate name in namespace " + this.toString(true) + ": " + child.name);
      }
      this.children.push(child);
    };

    /**
     * Gets a child by its name or id.
     * @param {string|number} nameOrId Child name or id
     * @return {?ProtoBuf.Reflect.T} The child or null if not found
     * @expose
     */
    NamespacePrototype.getChild = function (nameOrId) {
      var key = typeof nameOrId === 'number' ? 'id' : 'name';
      for (var i = 0, k = this.children.length; i < k; ++i)
        if (this.children[i][key] === nameOrId)
          return this.children[i];
      return null;
    };

    /**
     * Resolves a reflect object inside of this namespace.
     * @param {string|!Array.<string>} qn Qualified name to resolve
     * @param {boolean=} excludeNonNamespace Excludes non-namespace types, defaults to `false`
     * @return {?ProtoBuf.Reflect.Namespace} The resolved type or null if not found
     * @expose
     */
    NamespacePrototype.resolve = function (qn, excludeNonNamespace) {
      var part = typeof qn === 'string' ? qn.split(".") : qn,
        ptr = this,
        i = 0;
      if (part[i] === "") { // Fully qualified name, e.g. ".My.Message'
        while (ptr.parent !== null)
          ptr = ptr.parent;
        i++;
      }
      var child;
      do {
        do {
          if (!(ptr instanceof Reflect.Namespace)) {
            ptr = null;
            break;
          }
          child = ptr.getChild(part[i]);
          if (!child || !(child instanceof Reflect.T) || (excludeNonNamespace && !(child instanceof Reflect.Namespace))) {
            ptr = null;
            break;
          }
          ptr = child;
          i++;
        } while (i < part.length);
        if (ptr != null)
          break; // Found
        // Else search the parent
        if (this.parent !== null)
          return this.parent.resolve(qn, excludeNonNamespace);
      } while (ptr != null);
      return ptr;
    };

    /**
     * Determines the shortest qualified name of the specified type, if any, relative to this namespace.
     * @param {!ProtoBuf.Reflect.T} t Reflection type
     * @returns {string} The shortest qualified name or, if there is none, the fqn
     * @expose
     */
    NamespacePrototype.qn = function (t) {
      var part = [],
        ptr = t;
      do {
        part.unshift(ptr.name);
        ptr = ptr.parent;
      } while (ptr !== null);
      for (var len = 1; len <= part.length; len++) {
        var qn = part.slice(part.length - len);
        if (t === this.resolve(qn, t instanceof Reflect.Namespace))
          return qn.join(".");
      }
      return t.fqn();
    };

    /**
     * Builds the namespace and returns the runtime counterpart.
     * @return {Object.<string,Function|Object>} Runtime namespace
     * @expose
     */
    NamespacePrototype.build = function () {
      /** @dict */
      var ns = {};
      var children = this.children;
      for (var i = 0, k = children.length, child; i < k; ++i) {
        child = children[i];
        if (child instanceof Namespace)
          ns[child.name] = child.build();
      }
      if (Object.defineProperty)
        Object.defineProperty(ns, "$options", { "value": this.buildOpt() });
      return ns;
    };

    /**
     * Builds the namespace's '$options' property.
     * @return {Object.<string,*>}
     */
    NamespacePrototype.buildOpt = function () {
      var opt = {},
        keys = Object.keys(this.options);
      for (var i = 0, k = keys.length; i < k; ++i) {
        var key = keys[i],
          val = this.options[keys[i]];
        // TODO: Options are not resolved, yet.
        // if (val instanceof Namespace) {
        //     opt[key] = val.build();
        // } else {
        opt[key] = val;
        // }
      }
      return opt;
    };

    /**
     * Gets the value assigned to the option with the specified name.
     * @param {string=} name Returns the option value if specified, otherwise all options are returned.
     * @return {*|Object.<string,*>}null} Option value or NULL if there is no such option
     */
    NamespacePrototype.getOption = function (name) {
      if (typeof name === 'undefined')
        return this.options;
      return typeof this.options[name] !== 'undefined' ? this.options[name] : null;
    };

    /**
     * @alias ProtoBuf.Reflect.Namespace
     * @expose
     */
    Reflect.Namespace = Namespace;

    /**
     * Constructs a new Element implementation that checks and converts values for a
     * particular field type, as appropriate.
     *
     * An Element represents a single value: either the value of a singular field,
     * or a value contained in one entry of a repeated field or map field. This
     * class does not implement these higher-level concepts; it only encapsulates
     * the low-level typechecking and conversion.
     *
     * @exports ProtoBuf.Reflect.Element
     * @param {{name: string, wireType: number}} type Resolved data type
     * @param {ProtoBuf.Reflect.T|null} resolvedType Resolved type, if relevant
     * (e.g. submessage field).
     * @param {boolean} isMapKey Is this element a Map key? The value will be
     * converted to string form if so.
     * @param {string} syntax Syntax level of defining message type, e.g.,
     * proto2 or proto3.
     * @constructor
     */
    var Element = function (type, resolvedType, isMapKey, syntax) {

      /**
       * Element type, as a string (e.g., int32).
       * @type {{name: string, wireType: number}}
       */
      this.type = type;

      /**
       * Element type reference to submessage or enum definition, if needed.
       * @type {ProtoBuf.Reflect.T|null}
       */
      this.resolvedType = resolvedType;

      /**
       * Element is a map key.
       * @type {boolean}
       */
      this.isMapKey = isMapKey;

      /**
       * Syntax level of defining message type, e.g., proto2 or proto3.
       * @type {string}
       */
      this.syntax = syntax;

      if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0)
        throw Error("Invalid map key type: " + type.name);
    };

    var ElementPrototype = Element.prototype;

    /**
     * Obtains a (new) default value for the specified type.
     * @param type {string|{name: string, wireType: number}} Field type
     * @returns {*} Default value
     * @inner
     */
    function mkDefault(type) {
      if (typeof type === 'string')
        type = ProtoBuf.TYPES[type];
      if (typeof type.defaultValue === 'undefined')
        throw Error("default value for type " + type.name + " is not supported");
      if (type == ProtoBuf.TYPES["bytes"])
        return new ByteBuffer(0);
      return type.defaultValue;
    }

    /**
     * Returns the default value for this field in proto3.
     * @function
     * @param type {string|{name: string, wireType: number}} the field type
     * @returns {*} Default value
     */
    Element.defaultFieldValue = mkDefault;

    /**
     * Makes a Long from a value.
     * @param {{low: number, high: number, unsigned: boolean}|string|number} value Value
     * @param {boolean=} unsigned Whether unsigned or not, defaults to reuse it from Long-like objects or to signed for
     *  strings and numbers
     * @returns {!Long}
     * @throws {Error} If the value cannot be converted to a Long
     * @inner
     */
    function mkLong(value, unsigned) {
      if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean' && value.low === value.low && value.high === value.high)
        return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned);
      if (typeof value === 'string')
        return ProtoBuf.Long.fromString(value, unsigned || false, 10);
      if (typeof value === 'number')
        return ProtoBuf.Long.fromNumber(value, unsigned || false);
      throw Error("not convertible to Long");
    }

    /**
     * Checks if the given value can be set for an element of this type (singular
     * field or one element of a repeated field or map).
     * @param {*} value Value to check
     * @return {*} Verified, maybe adjusted, value
     * @throws {Error} If the value cannot be verified for this element slot
     * @expose
     */
    ElementPrototype.verifyValue = function (value) {
      var fail = function (val, msg) {
        throw Error("Illegal value for " + this.toString(true) + " of type " + this.type.name + ": " + val + " (" + msg + ")");
      }.bind(this);
      switch (this.type) {
        // Signed 32bit
      case ProtoBuf.TYPES["int32"]:
      case ProtoBuf.TYPES["sint32"]:
      case ProtoBuf.TYPES["sfixed32"]:
        // Account for !NaN: value === value
        if (typeof value !== 'number' || (value === value && value % 1 !== 0))
          fail(typeof value, "not an integer");
        return value > 4294967295 ? value | 0 : value;

        // Unsigned 32bit
      case ProtoBuf.TYPES["uint32"]:
      case ProtoBuf.TYPES["fixed32"]:
        if (typeof value !== 'number' || (value === value && value % 1 !== 0))
          fail(typeof value, "not an integer");
        return value < 0 ? value >>> 0 : value;

        // Signed 64bit
      case ProtoBuf.TYPES["int64"]:
      case ProtoBuf.TYPES["sint64"]:
      case ProtoBuf.TYPES["sfixed64"]:
        {
          if (ProtoBuf.Long)
            try {
              return mkLong(value, false);
            } catch (e) {
              fail(typeof value, e.message);
            }
          else
            fail(typeof value, "requires Long.js");
        }

        // Unsigned 64bit
      case ProtoBuf.TYPES["uint64"]:
      case ProtoBuf.TYPES["fixed64"]:
        {
          if (ProtoBuf.Long)
            try {
              return mkLong(value, true);
            } catch (e) {
              fail(typeof value, e.message);
            }
          else
            fail(typeof value, "requires Long.js");
        }

        // Bool
      case ProtoBuf.TYPES["bool"]:
        if (typeof value !== 'boolean')
          fail(typeof value, "not a boolean");
        return value;

        // Float
      case ProtoBuf.TYPES["float"]:
      case ProtoBuf.TYPES["double"]:
        if (typeof value !== 'number')
          fail(typeof value, "not a number");
        return value;

        // Length-delimited string
      case ProtoBuf.TYPES["string"]:
        if (typeof value !== 'string' && !(value && value instanceof String))
          fail(typeof value, "not a string");
        return "" + value; // Convert String object to string

        // Length-delimited bytes
      case ProtoBuf.TYPES["bytes"]:
        if (ByteBuffer.isByteBuffer(value))
          return value;
        return ByteBuffer.wrap(value, "base64");

        // Constant enum value
      case ProtoBuf.TYPES["enum"]:
        {
          var values = this.resolvedType.getChildren(ProtoBuf.Reflect.Enum.Value);
          for (i = 0; i < values.length; i++)
            if (values[i].name == value)
              return values[i].id;
            else if (values[i].id == value)
            return values[i].id;

          if (this.syntax === 'proto3') {
            // proto3: just make sure it's an integer.
            if (typeof value !== 'number' || (value === value && value % 1 !== 0))
              fail(typeof value, "not an integer");
            if (value > 4294967295 || value < 0)
              fail(typeof value, "not in range for uint32");
            return value;
          } else {
            // proto2 requires enum values to be valid.
            fail(value, "not a valid enum value");
          }
        }
        // Embedded message
      case ProtoBuf.TYPES["group"]:
      case ProtoBuf.TYPES["message"]:
        {
          if (!value || typeof value !== 'object')
            fail(typeof value, "object expected");
          if (value instanceof this.resolvedType.clazz)
            return value;
          if (value instanceof ProtoBuf.Builder.Message) {
            // Mismatched type: Convert to object (see: https://github.com/dcodeIO/ProtoBuf.js/issues/180)
            var obj = {};
            for (var i in value)
              if (value.hasOwnProperty(i))
                obj[i] = value[i];
            value = obj;
          }
          // Else let's try to construct one from a key-value object
          return new(this.resolvedType.clazz)(value); // May throw for a hundred of reasons
        }
      }

      // We should never end here
      throw Error("[INTERNAL] Illegal value for " + this.toString(true) + ": " + value + " (undefined type " + this.type + ")");
    };

    /**
     * Calculates the byte length of an element on the wire.
     * @param {number} id Field number
     * @param {*} value Field value
     * @returns {number} Byte length
     * @throws {Error} If the value cannot be calculated
     * @expose
     */
    ElementPrototype.calculateLength = function (id, value) {
      if (value === null) return 0; // Nothing to encode
      // Tag has already been written
      var n;
      switch (this.type) {
      case ProtoBuf.TYPES["int32"]:
        return value < 0 ? ByteBuffer.calculateVarint64(value) : ByteBuffer.calculateVarint32(value);
      case ProtoBuf.TYPES["uint32"]:
        return ByteBuffer.calculateVarint32(value);
      case ProtoBuf.TYPES["sint32"]:
        return ByteBuffer.calculateVarint32(ByteBuffer.zigZagEncode32(value));
      case ProtoBuf.TYPES["fixed32"]:
      case ProtoBuf.TYPES["sfixed32"]:
      case ProtoBuf.TYPES["float"]:
        return 4;
      case ProtoBuf.TYPES["int64"]:
      case ProtoBuf.TYPES["uint64"]:
        return ByteBuffer.calculateVarint64(value);
      case ProtoBuf.TYPES["sint64"]:
        return ByteBuffer.calculateVarint64(ByteBuffer.zigZagEncode64(value));
      case ProtoBuf.TYPES["fixed64"]:
      case ProtoBuf.TYPES["sfixed64"]:
        return 8;
      case ProtoBuf.TYPES["bool"]:
        return 1;
      case ProtoBuf.TYPES["enum"]:
        return ByteBuffer.calculateVarint32(value);
      case ProtoBuf.TYPES["double"]:
        return 8;
      case ProtoBuf.TYPES["string"]:
        n = ByteBuffer.calculateUTF8Bytes(value);
        return ByteBuffer.calculateVarint32(n) + n;
      case ProtoBuf.TYPES["bytes"]:
        if (value.remaining() < 0)
          throw Error("Illegal value for " + this.toString(true) + ": " + value.remaining() + " bytes remaining");
        return ByteBuffer.calculateVarint32(value.remaining()) + value.remaining();
      case ProtoBuf.TYPES["message"]:
        n = this.resolvedType.calculate(value);
        return ByteBuffer.calculateVarint32(n) + n;
      case ProtoBuf.TYPES["group"]:
        n = this.resolvedType.calculate(value);
        return n + ByteBuffer.calculateVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
      }
      // We should never end here
      throw Error("[INTERNAL] Illegal value to encode in " + this.toString(true) + ": " + value + " (unknown type)");
    };

    /**
     * Encodes a value to the specified buffer. Does not encode the key.
     * @param {number} id Field number
     * @param {*} value Field value
     * @param {ByteBuffer} buffer ByteBuffer to encode to
     * @return {ByteBuffer} The ByteBuffer for chaining
     * @throws {Error} If the value cannot be encoded
     * @expose
     */
    ElementPrototype.encodeValue = function (id, value, buffer) {
      if (value === null) return buffer; // Nothing to encode
      // Tag has already been written

      switch (this.type) {
        // 32bit signed varint
      case ProtoBuf.TYPES["int32"]:
        // "If you use int32 or int64 as the type for a negative number, the resulting varint is always ten bytes
        // long – it is, effectively, treated like a very large unsigned integer." (see #122)
        if (value < 0)
          buffer.writeVarint64(value);
        else
          buffer.writeVarint32(value);
        break;

        // 32bit unsigned varint
      case ProtoBuf.TYPES["uint32"]:
        buffer.writeVarint32(value);
        break;

        // 32bit varint zig-zag
      case ProtoBuf.TYPES["sint32"]:
        buffer.writeVarint32ZigZag(value);
        break;

        // Fixed unsigned 32bit
      case ProtoBuf.TYPES["fixed32"]:
        buffer.writeUint32(value);
        break;

        // Fixed signed 32bit
      case ProtoBuf.TYPES["sfixed32"]:
        buffer.writeInt32(value);
        break;

        // 64bit varint as-is
      case ProtoBuf.TYPES["int64"]:
      case ProtoBuf.TYPES["uint64"]:
        buffer.writeVarint64(value); // throws
        break;

        // 64bit varint zig-zag
      case ProtoBuf.TYPES["sint64"]:
        buffer.writeVarint64ZigZag(value); // throws
        break;

        // Fixed unsigned 64bit
      case ProtoBuf.TYPES["fixed64"]:
        buffer.writeUint64(value); // throws
        break;

        // Fixed signed 64bit
      case ProtoBuf.TYPES["sfixed64"]:
        buffer.writeInt64(value); // throws
        break;

        // Bool
      case ProtoBuf.TYPES["bool"]:
        if (typeof value === 'string')
          buffer.writeVarint32(value.toLowerCase() === 'false' ? 0 : !!value);
        else
          buffer.writeVarint32(value ? 1 : 0);
        break;

        // Constant enum value
      case ProtoBuf.TYPES["enum"]:
        buffer.writeVarint32(value);
        break;

        // 32bit float
      case ProtoBuf.TYPES["float"]:
        buffer.writeFloat32(value);
        break;

        // 64bit float
      case ProtoBuf.TYPES["double"]:
        buffer.writeFloat64(value);
        break;

        // Length-delimited string
      case ProtoBuf.TYPES["string"]:
        buffer.writeVString(value);
        break;

        // Length-delimited bytes
      case ProtoBuf.TYPES["bytes"]:
        if (value.remaining() < 0)
          throw Error("Illegal value for " + this.toString(true) + ": " + value.remaining() + " bytes remaining");
        var prevOffset = value.offset;
        buffer.writeVarint32(value.remaining());
        buffer.append(value);
        value.offset = prevOffset;
        break;

        // Embedded message
      case ProtoBuf.TYPES["message"]:
        var bb = new ByteBuffer().LE();
        this.resolvedType.encode(value, bb);
        buffer.writeVarint32(bb.offset);
        buffer.append(bb.flip());
        break;

        // Legacy group
      case ProtoBuf.TYPES["group"]:
        this.resolvedType.encode(value, buffer);
        buffer.writeVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
        break;

      default:
        // We should never end here
        throw Error("[INTERNAL] Illegal value to encode in " + this.toString(true) + ": " + value + " (unknown type)");
      }
      return buffer;
    };

    /**
     * Decode one element value from the specified buffer.
     * @param {ByteBuffer} buffer ByteBuffer to decode from
     * @param {number} wireType The field wire type
     * @param {number} id The field number
     * @return {*} Decoded value
     * @throws {Error} If the field cannot be decoded
     * @expose
     */
    ElementPrototype.decode = function (buffer, wireType, id) {
      if (wireType != this.type.wireType)
        throw Error("Unexpected wire type for element");

      var value, nBytes;
      switch (this.type) {
        // 32bit signed varint
      case ProtoBuf.TYPES["int32"]:
        return buffer.readVarint32() | 0;

        // 32bit unsigned varint
      case ProtoBuf.TYPES["uint32"]:
        return buffer.readVarint32() >>> 0;

        // 32bit signed varint zig-zag
      case ProtoBuf.TYPES["sint32"]:
        return buffer.readVarint32ZigZag() | 0;

        // Fixed 32bit unsigned
      case ProtoBuf.TYPES["fixed32"]:
        return buffer.readUint32() >>> 0;

      case ProtoBuf.TYPES["sfixed32"]:
        return buffer.readInt32() | 0;

        // 64bit signed varint
      case ProtoBuf.TYPES["int64"]:
        return buffer.readVarint64();

        // 64bit unsigned varint
      case ProtoBuf.TYPES["uint64"]:
        return buffer.readVarint64().toUnsigned();

        // 64bit signed varint zig-zag
      case ProtoBuf.TYPES["sint64"]:
        return buffer.readVarint64ZigZag();

        // Fixed 64bit unsigned
      case ProtoBuf.TYPES["fixed64"]:
        return buffer.readUint64();

        // Fixed 64bit signed
      case ProtoBuf.TYPES["sfixed64"]:
        return buffer.readInt64();

        // Bool varint
      case ProtoBuf.TYPES["bool"]:
        return !!buffer.readVarint32();

        // Constant enum value (varint)
      case ProtoBuf.TYPES["enum"]:
        // The following Builder.Message#set will already throw
        return buffer.readVarint32();

        // 32bit float
      case ProtoBuf.TYPES["float"]:
        return buffer.readFloat();

        // 64bit float
      case ProtoBuf.TYPES["double"]:
        return buffer.readDouble();

        // Length-delimited string
      case ProtoBuf.TYPES["string"]:
        return buffer.readVString();

        // Length-delimited bytes
      case ProtoBuf.TYPES["bytes"]:
        {
          nBytes = buffer.readVarint32();
          if (buffer.remaining() < nBytes)
            throw Error("Illegal number of bytes for " + this.toString(true) + ": " + nBytes + " required but got only " + buffer.remaining());
          value = buffer.clone(); // Offset already set
          value.limit = value.offset + nBytes;
          buffer.offset += nBytes;
          return value;
        }

        // Length-delimited embedded message
      case ProtoBuf.TYPES["message"]:
        {
          nBytes = buffer.readVarint32();
          return this.resolvedType.decode(buffer, nBytes);
        }

        // Legacy group
      case ProtoBuf.TYPES["group"]:
        return this.resolvedType.decode(buffer, -1, id);
      }

      // We should never end here
      throw Error("[INTERNAL] Illegal decode type");
    };

    /**
     * Converts a value from a string to the canonical element type.
     *
     * Legal only when isMapKey is true.
     *
     * @param {string} str The string value
     * @returns {*} The value
     */
    ElementPrototype.valueFromString = function (str) {
      if (!this.isMapKey) {
        throw Error("valueFromString() called on non-map-key element");
      }

      switch (this.type) {
      case ProtoBuf.TYPES["int32"]:
      case ProtoBuf.TYPES["sint32"]:
      case ProtoBuf.TYPES["sfixed32"]:
      case ProtoBuf.TYPES["uint32"]:
      case ProtoBuf.TYPES["fixed32"]:
        return this.verifyValue(parseInt(str));

      case ProtoBuf.TYPES["int64"]:
      case ProtoBuf.TYPES["sint64"]:
      case ProtoBuf.TYPES["sfixed64"]:
      case ProtoBuf.TYPES["uint64"]:
      case ProtoBuf.TYPES["fixed64"]:
        // Long-based fields support conversions from string already.
        return this.verifyValue(str);

      case ProtoBuf.TYPES["bool"]:
        return str === "true";

      case ProtoBuf.TYPES["string"]:
        return this.verifyValue(str);

      case ProtoBuf.TYPES["bytes"]:
        return ByteBuffer.fromBinary(str);
      }
    };

    /**
     * Converts a value from the canonical element type to a string.
     *
     * It should be the case that `valueFromString(valueToString(val))` returns
     * a value equivalent to `verifyValue(val)` for every legal value of `val`
     * according to this element type.
     *
     * This may be used when the element must be stored or used as a string,
     * e.g., as a map key on an Object.
     *
     * Legal only when isMapKey is true.
     *
     * @param {*} val The value
     * @returns {string} The string form of the value.
     */
    ElementPrototype.valueToString = function (value) {
      if (!this.isMapKey) {
        throw Error("valueToString() called on non-map-key element");
      }

      if (this.type === ProtoBuf.TYPES["bytes"]) {
        return value.toString("binary");
      } else {
        return value.toString();
      }
    };

    /**
     * @alias ProtoBuf.Reflect.Element
     * @expose
     */
    Reflect.Element = Element;

    /**
     * Constructs a new Message.
     * @exports ProtoBuf.Reflect.Message
     * @param {!ProtoBuf.Builder} builder Builder reference
     * @param {!ProtoBuf.Reflect.Namespace} parent Parent message or namespace
     * @param {string} name Message name
     * @param {Object.<string,*>=} options Message options
     * @param {boolean=} isGroup `true` if this is a legacy group
     * @param {string?} syntax The syntax level of this definition (e.g., proto3)
     * @constructor
     * @extends ProtoBuf.Reflect.Namespace
     */
    var Message = function (builder, parent, name, options, isGroup, syntax) {
      Namespace.call(this, builder, parent, name, options, syntax);

      /**
       * @override
       */
      this.className = "Message";

      /**
       * Extensions range.
       * @type {!Array.<number>}
       * @expose
       */
      this.extensions = [ProtoBuf.ID_MIN, ProtoBuf.ID_MAX];

      /**
       * Runtime message class.
       * @type {?function(new:ProtoBuf.Builder.Message)}
       * @expose
       */
      this.clazz = null;

      /**
       * Whether this is a legacy group or not.
       * @type {boolean}
       * @expose
       */
      this.isGroup = !!isGroup;

      // The following cached collections are used to efficiently iterate over or look up fields when decoding.

      /**
       * Cached fields.
       * @type {?Array.<!ProtoBuf.Reflect.Message.Field>}
       * @private
       */
      this._fields = null;

      /**
       * Cached fields by id.
       * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>}
       * @private
       */
      this._fieldsById = null;

      /**
       * Cached fields by name.
       * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>}
       * @private
       */
      this._fieldsByName = null;
    };

    /**
     * @alias ProtoBuf.Reflect.Message.prototype
     * @inner
     */
    var MessagePrototype = Message.prototype = Object.create(Namespace.prototype);

    /**
     * Builds the message and returns the runtime counterpart, which is a fully functional class.
     * @see ProtoBuf.Builder.Message
     * @param {boolean=} rebuild Whether to rebuild or not, defaults to false
     * @return {ProtoBuf.Reflect.Message} Message class
     * @throws {Error} If the message cannot be built
     * @expose
     */
    MessagePrototype.build = function (rebuild) {
      if (this.clazz && !rebuild)
        return this.clazz;

      // Create the runtime Message class in its own scope
      var clazz = (function (ProtoBuf, T) {

        var fields = T.getChildren(ProtoBuf.Reflect.Message.Field),
          oneofs = T.getChildren(ProtoBuf.Reflect.Message.OneOf);

        /**
         * Constructs a new runtime Message.
         * @name ProtoBuf.Builder.Message
         * @class Barebone of all runtime messages.
         * @param {!Object.<string,*>|string} values Preset values
         * @param {...string} var_args
         * @constructor
         * @throws {Error} If the message cannot be created
         */
        var Message = function (values, var_args) {
          ProtoBuf.Builder.Message.call(this);

          // Create virtual oneof properties
          for (var i = 0, k = oneofs.length; i < k; ++i)
            this[oneofs[i].name] = null;
          // Create fields and set default values
          for (i = 0, k = fields.length; i < k; ++i) {
            var field = fields[i];
            this[field.name] =
              field.repeated ? [] :
              (field.map ? new ProtoBuf.Map(field) : null);
            if ((field.required || T.syntax === 'proto3') &&
              field.defaultValue !== null)
              this[field.name] = field.defaultValue;
          }

          if (arguments.length > 0) {
            var value;
            // Set field values from a values object
            if (arguments.length === 1 && values !== null && typeof values === 'object' &&
              /* not _another_ Message */
              (typeof values.encode !== 'function' || values instanceof Message) &&
              /* not a repeated field */
              !Array.isArray(values) &&
              /* not a Map */
              !(values instanceof ProtoBuf.Map) &&
              /* not a ByteBuffer */
              !ByteBuffer.isByteBuffer(values) &&
              /* not an ArrayBuffer */
              !(values instanceof ArrayBuffer) &&
              /* not a Long */
              !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) {
              this.$set(values);
            } else // Set field values from arguments, in declaration order
              for (i = 0, k = arguments.length; i < k; ++i)
              if (typeof (value = arguments[i]) !== 'undefined')
                this.$set(fields[i].name, value); // May throw
          }
        };

        /**
         * @alias ProtoBuf.Builder.Message.prototype
         * @inner
         */
        var MessagePrototype = Message.prototype = Object.create(ProtoBuf.Builder.Message.prototype);

        /**
         * Adds a value to a repeated field.
         * @name ProtoBuf.Builder.Message#add
         * @function
         * @param {string} key Field name
         * @param {*} value Value to add
         * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
         * @returns {!ProtoBuf.Builder.Message} this
         * @throws {Error} If the value cannot be added
         * @expose
         */
        MessagePrototype.add = function (key, value, noAssert) {
          var field = T._fieldsByName[key];
          if (!noAssert) {
            if (!field)
              throw Error(this + "#" + key + " is undefined");
            if (!(field instanceof ProtoBuf.Reflect.Message.Field))
              throw Error(this + "#" + key + " is not a field: " + field.toString(true)); // May throw if it's an enum or embedded message
            if (!field.repeated)
              throw Error(this + "#" + key + " is not a repeated field");
            value = field.verifyValue(value, true);
          }
          if (this[key] === null)
            this[key] = [];
          this[key].push(value);
          return this;
        };

        /**
         * Adds a value to a repeated field. This is an alias for {@link ProtoBuf.Builder.Message#add}.
         * @name ProtoBuf.Builder.Message#$add
         * @function
         * @param {string} key Field name
         * @param {*} value Value to add
         * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
         * @returns {!ProtoBuf.Builder.Message} this
         * @throws {Error} If the value cannot be added
         * @expose
         */
        MessagePrototype.$add = MessagePrototype.add;

        /**
         * Sets a field's value.
         * @name ProtoBuf.Builder.Message#set
         * @function
         * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
         * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
         * @param {boolean=} noAssert Whether to not assert for an actual field / proper value type, defaults to `false`
         * @returns {!ProtoBuf.Builder.Message} this
         * @throws {Error} If the value cannot be set
         * @expose
         */
        MessagePrototype.set = function (keyOrObj, value, noAssert) {
          if (keyOrObj && typeof keyOrObj === 'object') {
            noAssert = value;
            for (var ikey in keyOrObj)
              if (keyOrObj.hasOwnProperty(ikey) && typeof (value = keyOrObj[ikey]) !== 'undefined')
                this.$set(ikey, value, noAssert);
            return this;
          }
          var field = T._fieldsByName[keyOrObj];
          if (!noAssert) {
            if (!field)
              throw Error(this + "#" + keyOrObj + " is not a field: undefined");
            if (!(field instanceof ProtoBuf.Reflect.Message.Field))
              throw Error(this + "#" + keyOrObj + " is not a field: " + field.toString(true));
            this[field.name] = (value = field.verifyValue(value)); // May throw
          } else
            this[keyOrObj] = value;
          if (field && field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
            var currentField = this[field.oneof.name]; // Virtual field references currently set field
            if (value !== null) {
              if (currentField !== null && currentField !== field.name)
                this[currentField] = null; // Clear currently set field
              this[field.oneof.name] = field.name; // Point virtual field at this field
            } else if ( /* value === null && */ currentField === keyOrObj)
              this[field.oneof.name] = null; // Clear virtual field (current field explicitly cleared)
          }
          return this;
        };

        /**
         * Sets a field's value. This is an alias for [@link ProtoBuf.Builder.Message#set}.
         * @name ProtoBuf.Builder.Message#$set
         * @function
         * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
         * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
         * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
         * @throws {Error} If the value cannot be set
         * @expose
         */
        MessagePrototype.$set = MessagePrototype.set;

        /**
         * Gets a field's value.
         * @name ProtoBuf.Builder.Message#get
         * @function
         * @param {string} key Key
         * @param {boolean=} noAssert Whether to not assert for an actual field, defaults to `false`
         * @return {*} Value
         * @throws {Error} If there is no such field
         * @expose
         */
        MessagePrototype.get = function (key, noAssert) {
          if (noAssert)
            return this[key];
          var field = T._fieldsByName[key];
          if (!field || !(field instanceof ProtoBuf.Reflect.Message.Field))
            throw Error(this + "#" + key + " is not a field: undefined");
          if (!(field instanceof ProtoBuf.Reflect.Message.Field))
            throw Error(this + "#" + key + " is not a field: " + field.toString(true));
          return this[field.name];
        };

        /**
         * Gets a field's value. This is an alias for {@link ProtoBuf.Builder.Message#$get}.
         * @name ProtoBuf.Builder.Message#$get
         * @function
         * @param {string} key Key
         * @return {*} Value
         * @throws {Error} If there is no such field
         * @expose
         */
        MessagePrototype.$get = MessagePrototype.get;

        // Getters and setters

        for (var i = 0; i < fields.length; i++) {
          var field = fields[i];
          // no setters for extension fields as these are named by their fqn
          if (field instanceof ProtoBuf.Reflect.Message.ExtensionField)
            continue;

          if (T.builder.options['populateAccessors'])
            (function (field) {
              // set/get[SomeValue]
              var Name = field.originalName.replace(/(_[a-zA-Z])/g, function (match) {
                return match.toUpperCase().replace('_', '');
              });
              Name = Name.substring(0, 1).toUpperCase() + Name.substring(1);

              // set/get_[some_value] FIXME: Do we really need these?
              var name = field.originalName.replace(/([A-Z])/g, function (match) {
                return "_" + match;
              });

              /**
               * The current field's unbound setter function.
               * @function
               * @param {*} value
               * @param {boolean=} noAssert
               * @returns {!ProtoBuf.Builder.Message}
               * @inner
               */
              var setter = function (value, noAssert) {
                this[field.name] = noAssert ? value : field.verifyValue(value);
                return this;
              };

              /**
               * The current field's unbound getter function.
               * @function
               * @returns {*}
               * @inner
               */
              var getter = function () {
                return this[field.name];
              };

              if (T.getChild("set" + Name) === null)
              /**
               * Sets a value. This method is present for each field, but only if there is no name conflict with
               *  another field.
               * @name ProtoBuf.Builder.Message#set[SomeField]
               * @function
               * @param {*} value Value to set
               * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
               * @returns {!ProtoBuf.Builder.Message} this
               * @abstract
               * @throws {Error} If the value cannot be set
               */
                MessagePrototype["set" + Name] = setter;

              if (T.getChild("set_" + name) === null)
              /**
               * Sets a value. This method is present for each field, but only if there is no name conflict with
               *  another field.
               * @name ProtoBuf.Builder.Message#set_[some_field]
               * @function
               * @param {*} value Value to set
               * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
               * @returns {!ProtoBuf.Builder.Message} this
               * @abstract
               * @throws {Error} If the value cannot be set
               */
                MessagePrototype["set_" + name] = setter;

              if (T.getChild("get" + Name) === null)
              /**
               * Gets a value. This method is present for each field, but only if there is no name conflict with
               *  another field.
               * @name ProtoBuf.Builder.Message#get[SomeField]
               * @function
               * @abstract
               * @return {*} The value
               */
                MessagePrototype["get" + Name] = getter;

              if (T.getChild("get_" + name) === null)
              /**
               * Gets a value. This method is present for each field, but only if there is no name conflict with
               *  another field.
               * @name ProtoBuf.Builder.Message#get_[some_field]
               * @function
               * @return {*} The value
               * @abstract
               */
                MessagePrototype["get_" + name] = getter;

            })(field);
        }

        // En-/decoding

        /**
         * Encodes the message.
         * @name ProtoBuf.Builder.Message#$encode
         * @function
         * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
         * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
         * @return {!ByteBuffer} Encoded message as a ByteBuffer
         * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
         *  returns the encoded ByteBuffer in the `encoded` property on the error.
         * @expose
         * @see ProtoBuf.Builder.Message#encode64
         * @see ProtoBuf.Builder.Message#encodeHex
         * @see ProtoBuf.Builder.Message#encodeAB
         */
        MessagePrototype.encode = function (buffer, noVerify) {
          if (typeof buffer === 'boolean')
            noVerify = buffer,
            buffer = undefined;
          var isNew = false;
          if (!buffer)
            buffer = new ByteBuffer(),
            isNew = true;
          var le = buffer.littleEndian;
          try {
            T.encode(this, buffer.LE(), noVerify);
            return (isNew ? buffer.flip() : buffer).LE(le);
          } catch (e) {
            buffer.LE(le);
            throw (e);
          }
        };

        /**
         * Encodes a message using the specified data payload.
         * @param {!Object.<string,*>} data Data payload
         * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
         * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
         * @return {!ByteBuffer} Encoded message as a ByteBuffer
         * @expose
         */
        Message.encode = function (data, buffer, noVerify) {
          return new Message(data).encode(buffer, noVerify);
        };

        /**
         * Calculates the byte length of the message.
         * @name ProtoBuf.Builder.Message#calculate
         * @function
         * @returns {number} Byte length
         * @throws {Error} If the message cannot be calculated or if required fields are missing.
         * @expose
         */
        MessagePrototype.calculate = function () {
          return T.calculate(this);
        };

        /**
         * Encodes the varint32 length-delimited message.
         * @name ProtoBuf.Builder.Message#encodeDelimited
         * @function
         * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
         * @return {!ByteBuffer} Encoded message as a ByteBuffer
         * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
         *  returns the encoded ByteBuffer in the `encoded` property on the error.
         * @expose
         */
        MessagePrototype.encodeDelimited = function (buffer) {
          var isNew = false;
          if (!buffer)
            buffer = new ByteBuffer(),
            isNew = true;
          var enc = new ByteBuffer().LE();
          T.encode(this, enc).flip();
          buffer.writeVarint32(enc.remaining());
          buffer.append(enc);
          return isNew ? buffer.flip() : buffer;
        };

        /**
         * Directly encodes the message to an ArrayBuffer.
         * @name ProtoBuf.Builder.Message#encodeAB
         * @function
         * @return {ArrayBuffer} Encoded message as ArrayBuffer
         * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
         *  returns the encoded ArrayBuffer in the `encoded` property on the error.
         * @expose
         */
        MessagePrototype.encodeAB = function () {
          try {
            return this.encode().toArrayBuffer();
          } catch (e) {
            if (e["encoded"]) e["encoded"] = e["encoded"].toArrayBuffer();
            throw (e);
          }
        };

        /**
         * Returns the message as an ArrayBuffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeAB}.
         * @name ProtoBuf.Builder.Message#toArrayBuffer
         * @function
         * @return {ArrayBuffer} Encoded message as ArrayBuffer
         * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
         *  returns the encoded ArrayBuffer in the `encoded` property on the error.
         * @expose
         */
        MessagePrototype.toArrayBuffer = MessagePrototype.encodeAB;

        /**
         * Directly encodes the message to a node Buffer.
         * @name ProtoBuf.Builder.Message#encodeNB
         * @function
         * @return {!Buffer}
         * @throws {Error} If the message cannot be encoded, not running under node.js or if required fields are
         *  missing. The later still returns the encoded node Buffer in the `encoded` property on the error.
         * @expose
         */
        MessagePrototype.encodeNB = function () {
          try {
            return this.encode().toBuffer();
          } catch (e) {
            if (e["encoded"]) e["encoded"] = e["encoded"].toBuffer();
            throw (e);
          }
        };

        /**
         * Returns the message as a node Buffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeNB}.
         * @name ProtoBuf.Builder.Message#toBuffer
         * @function
         * @return {!Buffer}
         * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
         *  returns the encoded node Buffer in the `encoded` property on the error.
         * @expose
         */
        MessagePrototype.toBuffer = MessagePrototype.encodeNB;

        /**
         * Directly encodes the message to a base64 encoded string.
         * @name ProtoBuf.Builder.Message#encode64
         * @function
         * @return {string} Base64 encoded string
         * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
         *  still returns the encoded base64 string in the `encoded` property on the error.
         * @expose
         */
        MessagePrototype.encode64 = function () {
          try {
            return this.encode().toBase64();
          } catch (e) {
            if (e["encoded"]) e["encoded"] = e["encoded"].toBase64();
            throw (e);
          }
        };

        /**
         * Returns the message as a base64 encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encode64}.
         * @name ProtoBuf.Builder.Message#toBase64
         * @function
         * @return {string} Base64 encoded string
         * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
         *  returns the encoded base64 string in the `encoded` property on the error.
         * @expose
         */
        MessagePrototype.toBase64 = MessagePrototype.encode64;

        /**
         * Directly encodes the message to a hex encoded string.
         * @name ProtoBuf.Builder.Message#encodeHex
         * @function
         * @return {string} Hex encoded string
         * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
         *  still returns the encoded hex string in the `encoded` property on the error.
         * @expose
         */
        MessagePrototype.encodeHex = function () {
          try {
            return this.encode().toHex();
          } catch (e) {
            if (e["encoded"]) e["encoded"] = e["encoded"].toHex();
            throw (e);
          }
        };

        /**
         * Returns the message as a hex encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encodeHex}.
         * @name ProtoBuf.Builder.Message#toHex
         * @function
         * @return {string} Hex encoded string
         * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
         *  returns the encoded hex string in the `encoded` property on the error.
         * @expose
         */
        MessagePrototype.toHex = MessagePrototype.encodeHex;

        /**
         * Clones a message object or field value to a raw object.
         * @param {*} obj Object to clone
         * @param {boolean} binaryAsBase64 Whether to include binary data as base64 strings or as a buffer otherwise
         * @param {boolean} longsAsStrings Whether to encode longs as strings
         * @param {!ProtoBuf.Reflect.T=} resolvedType The resolved field type if a field
         * @returns {*} Cloned object
         * @inner
         */
        function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) {
          if (obj === null || typeof obj !== 'object') {
            // Convert enum values to their respective names
            if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) {
              var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj);
              if (name !== null)
                return name;
            }
            // Pass-through string, number, boolean, null...
            return obj;
          }
          // Convert ByteBuffers to raw buffer or strings
          if (ByteBuffer.isByteBuffer(obj))
            return binaryAsBase64 ? obj.toBase64() : obj.toBuffer();
          // Convert Longs to proper objects or strings
          if (ProtoBuf.Long.isLong(obj))
            return longsAsStrings ? obj.toString() : new ProtoBuf.Long(obj);
          var clone;
          // Clone arrays
          if (Array.isArray(obj)) {
            clone = [];
            obj.forEach(function (v, k) {
              clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType);
            });
            return clone;
          }
          clone = {};
          // Convert maps to objects
          if (obj instanceof ProtoBuf.Map) {
            var it = obj.entries();
            for (var e = it.next(); !e.done; e = it.next())
              clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType);
            return clone;
          }
          // Everything else is a non-null object
          var type = obj.$type,
            field = undefined;
          for (var i in obj)
            if (obj.hasOwnProperty(i)) {
              if (type && (field = type.getChild(i)))
                clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType);
              else
                clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings);
            }
          return clone;
        }

        /**
         * Returns the message's raw payload.
         * @param {boolean=} binaryAsBase64 Whether to include binary data as base64 strings instead of Buffers, defaults to `false`
         * @param {boolean} longsAsStrings Whether to encode longs as strings
         * @returns {Object.<string,*>} Raw payload
         * @expose
         */
        MessagePrototype.toRaw = function (binaryAsBase64, longsAsStrings) {
          return cloneRaw(this, !!binaryAsBase64, !!longsAsStrings, this.$type);
        };

        /**
         * Encodes a message to JSON.
         * @returns {string} JSON string
         * @expose
         */
        MessagePrototype.encodeJSON = function () {
          return JSON.stringify(
            cloneRaw(this,
              /* binary-as-base64 */
              true,
              /* longs-as-strings */
              true,
              this.$type
            )
          );
        };

        /**
         * Decodes a message from the specified buffer or string.
         * @name ProtoBuf.Builder.Message.decode
         * @function
         * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
         * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
         * @return {!ProtoBuf.Builder.Message} Decoded message
         * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
         *  returns the decoded message with missing fields in the `decoded` property on the error.
         * @expose
         * @see ProtoBuf.Builder.Message.decode64
         * @see ProtoBuf.Builder.Message.decodeHex
         */
        Message.decode = function (buffer, enc) {
          if (typeof buffer === 'string')
            buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
          buffer = ByteBuffer.isByteBuffer(buffer) ? buffer : ByteBuffer.wrap(buffer); // May throw
          var le = buffer.littleEndian;
          try {
            var msg = T.decode(buffer.LE());
            buffer.LE(le);
            return msg;
          } catch (e) {
            buffer.LE(le);
            throw (e);
          }
        };

        /**
         * Decodes a varint32 length-delimited message from the specified buffer or string.
         * @name ProtoBuf.Builder.Message.decodeDelimited
         * @function
         * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
         * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
         * @return {ProtoBuf.Builder.Message} Decoded message or `null` if not enough bytes are available yet
         * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
         *  returns the decoded message with missing fields in the `decoded` property on the error.
         * @expose
         */
        Message.decodeDelimited = function (buffer, enc) {
          if (typeof buffer === 'string')
            buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
          buffer = ByteBuffer.isByteBuffer(buffer) ? buffer : ByteBuffer.wrap(buffer); // May throw
          if (buffer.remaining() < 1)
            return null;
          var off = buffer.offset,
            len = buffer.readVarint32();
          if (buffer.remaining() < len) {
            buffer.offset = off;
            return null;
          }
          try {
            var msg = T.decode(buffer.slice(buffer.offset, buffer.offset + len).LE());
            buffer.offset += len;
            return msg;
          } catch (err) {
            buffer.offset += len;
            throw err;
          }
        };

        /**
         * Decodes the message from the specified base64 encoded string.
         * @name ProtoBuf.Builder.Message.decode64
         * @function
         * @param {string} str String to decode from
         * @return {!ProtoBuf.Builder.Message} Decoded message
         * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
         *  returns the decoded message with missing fields in the `decoded` property on the error.
         * @expose
         */
        Message.decode64 = function (str) {
          return Message.decode(str, "base64");
        };

        /**
         * Decodes the message from the specified hex encoded string.
         * @name ProtoBuf.Builder.Message.decodeHex
         * @function
         * @param {string} str String to decode from
         * @return {!ProtoBuf.Builder.Message} Decoded message
         * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
         *  returns the decoded message with missing fields in the `decoded` property on the error.
         * @expose
         */
        Message.decodeHex = function (str) {
          return Message.decode(str, "hex");
        };

        /**
         * Decodes the message from a JSON string.
         * @name ProtoBuf.Builder.Message.decodeJSON
         * @function
         * @param {string} str String to decode from
         * @return {!ProtoBuf.Builder.Message} Decoded message
         * @throws {Error} If the message cannot be decoded or if required fields are
         * missing.
         * @expose
         */
        Message.decodeJSON = function (str) {
          return new Message(JSON.parse(str));
        };

        // Utility

        /**
         * Returns a string representation of this Message.
         * @name ProtoBuf.Builder.Message#toString
         * @function
         * @return {string} String representation as of ".Fully.Qualified.MessageName"
         * @expose
         */
        MessagePrototype.toString = function () {
          return T.toString();
        };

        // Properties

        /**
         * Message options.
         * @name ProtoBuf.Builder.Message.$options
         * @type {Object.<string,*>}
         * @expose
         */
        var $optionsS; // cc needs this

        /**
         * Message options.
         * @name ProtoBuf.Builder.Message#$options
         * @type {Object.<string,*>}
         * @expose
         */
        var $options;

        /**
         * Reflection type.
         * @name ProtoBuf.Builder.Message.$type
         * @type {!ProtoBuf.Reflect.Message}
         * @expose
         */
        var $typeS;

        /**
         * Reflection type.
         * @name ProtoBuf.Builder.Message#$type
         * @type {!ProtoBuf.Reflect.Message}
         * @expose
         */
        var $type;

        if (Object.defineProperty)
          Object.defineProperty(Message, '$options', { "value": T.buildOpt() }),
          Object.defineProperty(MessagePrototype, "$options", { "value": Message["$options"] }),
          Object.defineProperty(Message, "$type", { "value": T }),
          Object.defineProperty(MessagePrototype, "$type", { "value": T });

        return Message;

      })(ProtoBuf, this);

      // Static enums and prototyped sub-messages / cached collections
      this._fields = [];
      this._fieldsById = {};
      this._fieldsByName = {};
      for (var i = 0, k = this.children.length, child; i < k; i++) {
        child = this.children[i];
        if (child instanceof Enum || child instanceof Message || child instanceof Service) {
          if (clazz.hasOwnProperty(child.name))
            throw Error("Illegal reflect child of " + this.toString(true) + ": " + child.toString(true) + " cannot override static property '" + child.name + "'");
          clazz[child.name] = child.build();
        } else if (child instanceof Message.Field)
          child.build(),
          this._fields.push(child),
          this._fieldsById[child.id] = child,
          this._fieldsByName[child.name] = child;
        else if (!(child instanceof Message.OneOf) && !(child instanceof Extension)) // Not built
          throw Error("Illegal reflect child of " + this.toString(true) + ": " + this.children[i].toString(true));
      }

      return this.clazz = clazz;
    };

    /**
     * Encodes a runtime message's contents to the specified buffer.
     * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
     * @param {ByteBuffer} buffer ByteBuffer to write to
     * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
     * @return {ByteBuffer} The ByteBuffer for chaining
     * @throws {Error} If required fields are missing or the message cannot be encoded for another reason
     * @expose
     */
    MessagePrototype.encode = function (message, buffer, noVerify) {
      var fieldMissing = null,
        field;
      for (var i = 0, k = this._fields.length, val; i < k; ++i) {
        field = this._fields[i];
        val = message[field.name];
        if (field.required && val === null) {
          if (fieldMissing === null)
            fieldMissing = field;
        } else
          field.encode(noVerify ? val : field.verifyValue(val), buffer, message);
      }
      if (fieldMissing !== null) {
        var err = Error("Missing at least one required field for " + this.toString(true) + ": " + fieldMissing);
        err["encoded"] = buffer; // Still expose what we got
        throw (err);
      }
      return buffer;
    };

    /**
     * Calculates a runtime message's byte length.
     * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
     * @returns {number} Byte length
     * @throws {Error} If required fields are missing or the message cannot be calculated for another reason
     * @expose
     */
    MessagePrototype.calculate = function (message) {
      for (var n = 0, i = 0, k = this._fields.length, field, val; i < k; ++i) {
        field = this._fields[i];
        val = message[field.name];
        if (field.required && val === null)
          throw Error("Missing at least one required field for " + this.toString(true) + ": " + field);
        else
          n += field.calculate(val, message);
      }
      return n;
    };

    /**
     * Skips all data until the end of the specified group has been reached.
     * @param {number} expectedId Expected GROUPEND id
     * @param {!ByteBuffer} buf ByteBuffer
     * @returns {boolean} `true` if a value as been skipped, `false` if the end has been reached
     * @throws {Error} If it wasn't possible to find the end of the group (buffer overrun or end tag mismatch)
     * @inner
     */
    function skipTillGroupEnd(expectedId, buf) {
      var tag = buf.readVarint32(), // Throws on OOB
        wireType = tag & 0x07,
        id = tag >>> 3;
      switch (wireType) {
      case ProtoBuf.WIRE_TYPES.VARINT:
        do tag = buf.readUint8();
        while ((tag & 0x80) === 0x80);
        break;
      case ProtoBuf.WIRE_TYPES.BITS64:
        buf.offset += 8;
        break;
      case ProtoBuf.WIRE_TYPES.LDELIM:
        tag = buf.readVarint32(); // reads the varint
        buf.offset += tag; // skips n bytes
        break;
      case ProtoBuf.WIRE_TYPES.STARTGROUP:
        skipTillGroupEnd(id, buf);
        break;
      case ProtoBuf.WIRE_TYPES.ENDGROUP:
        if (id === expectedId)
          return false;
        else
          throw Error("Illegal GROUPEND after unknown group: " + id + " (" + expectedId + " expected)");
      case ProtoBuf.WIRE_TYPES.BITS32:
        buf.offset += 4;
        break;
      default:
        throw Error("Illegal wire type in unknown group " + expectedId + ": " + wireType);
      }
      return true;
    }

    /**
     * Decodes an encoded message and returns the decoded message.
     * @param {ByteBuffer} buffer ByteBuffer to decode from
     * @param {number=} length Message length. Defaults to decode all the available data.
     * @param {number=} expectedGroupEndId Expected GROUPEND id if this is a legacy group
     * @return {ProtoBuf.Builder.Message} Decoded message
     * @throws {Error} If the message cannot be decoded
     * @expose
     */
    MessagePrototype.decode = function (buffer, length, expectedGroupEndId) {
      length = typeof length === 'number' ? length : -1;
      var start = buffer.offset,
        msg = new(this.clazz)(),
        tag, wireType, id, field;
      while (buffer.offset < start + length || (length === -1 && buffer.remaining() > 0)) {
        tag = buffer.readVarint32();
        wireType = tag & 0x07;
        id = tag >>> 3;
        if (wireType === ProtoBuf.WIRE_TYPES.ENDGROUP) {
          if (id !== expectedGroupEndId)
            throw Error("Illegal group end indicator for " + this.toString(true) + ": " + id + " (" + (expectedGroupEndId ? expectedGroupEndId + " expected" : "not a group") + ")");
          break;
        }
        if (!(field = this._fieldsById[id])) {
          // "messages created by your new code can be parsed by your old code: old binaries simply ignore the new field when parsing."
          switch (wireType) {
          case ProtoBuf.WIRE_TYPES.VARINT:
            buffer.readVarint32();
            break;
          case ProtoBuf.WIRE_TYPES.BITS32:
            buffer.offset += 4;
            break;
          case ProtoBuf.WIRE_TYPES.BITS64:
            buffer.offset += 8;
            break;
          case ProtoBuf.WIRE_TYPES.LDELIM:
            var len = buffer.readVarint32();
            buffer.offset += len;
            break;
          case ProtoBuf.WIRE_TYPES.STARTGROUP:
            while (skipTillGroupEnd(id, buffer)) {}
            break;
          default:
            throw Error("Illegal wire type for unknown field " + id + " in " + this.toString(true) + "#decode: " + wireType);
          }
          continue;
        }
        if (field.repeated && !field.options["packed"]) {
          msg[field.name].push(field.decode(wireType, buffer));
        } else if (field.map) {
          var keyval = field.decode(wireType, buffer);
          msg[field.name].set(keyval[0], keyval[1]);
        } else {
          msg[field.name] = field.decode(wireType, buffer);
          if (field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
            var currentField = msg[field.oneof.name]; // Virtual field references currently set field
            if (currentField !== null && currentField !== field.name)
              msg[currentField] = null; // Clear currently set field
            msg[field.oneof.name] = field.name; // Point virtual field at this field
          }
        }
      }

      // Check if all required fields are present and set default values for optional fields that are not
      for (var i = 0, k = this._fields.length; i < k; ++i) {
        field = this._fields[i];
        if (msg[field.name] === null) {
          if (this.syntax === "proto3") { // Proto3 sets default values by specification
            msg[field.name] = field.defaultValue;
          } else if (field.required) {
            var err = Error("Missing at least one required field for " + this.toString(true) + ": " + field.name);
            err["decoded"] = msg; // Still expose what we got
            throw (err);
          } else if (ProtoBuf.populateDefaults && field.defaultValue !== null)
            msg[field.name] = field.defaultValue;
        }
      }
      return msg;
    };

    /**
     * @alias ProtoBuf.Reflect.Message
     * @expose
     */
    Reflect.Message = Message;

    /**
     * Constructs a new Message Field.
     * @exports ProtoBuf.Reflect.Message.Field
     * @param {!ProtoBuf.Builder} builder Builder reference
     * @param {!ProtoBuf.Reflect.Message} message Message reference
     * @param {string} rule Rule, one of requried, optional, repeated
     * @param {string?} keytype Key data type, if any.
     * @param {string} type Data type, e.g. int32
     * @param {string} name Field name
     * @param {number} id Unique field id
     * @param {Object.<string,*>=} options Options
     * @param {!ProtoBuf.Reflect.Message.OneOf=} oneof Enclosing OneOf
     * @param {string?} syntax The syntax level of this definition (e.g., proto3)
     * @constructor
     * @extends ProtoBuf.Reflect.T
     */
    var Field = function (builder, message, rule, keytype, type, name, id, options, oneof, syntax) {
      T.call(this, builder, message, name);

      /**
       * @override
       */
      this.className = "Message.Field";

      /**
       * Message field required flag.
       * @type {boolean}
       * @expose
       */
      this.required = rule === "required";

      /**
       * Message field repeated flag.
       * @type {boolean}
       * @expose
       */
      this.repeated = rule === "repeated";

      /**
       * Message field map flag.
       * @type {boolean}
       * @expose
       */
      this.map = rule === "map";

      /**
       * Message field key type. Type reference string if unresolved, protobuf
       * type if resolved. Valid only if this.map === true, null otherwise.
       * @type {string|{name: string, wireType: number}|null}
       * @expose
       */
      this.keyType = keytype || null;

      /**
       * Message field type. Type reference string if unresolved, protobuf type if
       * resolved. In a map field, this is the value type.
       * @type {string|{name: string, wireType: number}}
       * @expose
       */
      this.type = type;

      /**
       * Resolved type reference inside the global namespace.
       * @type {ProtoBuf.Reflect.T|null}
       * @expose
       */
      this.resolvedType = null;

      /**
       * Unique message field id.
       * @type {number}
       * @expose
       */
      this.id = id;

      /**
       * Message field options.
       * @type {!Object.<string,*>}
       * @dict
       * @expose
       */
      this.options = options || {};

      /**
       * Default value.
       * @type {*}
       * @expose
       */
      this.defaultValue = null;

      /**
       * Enclosing OneOf.
       * @type {?ProtoBuf.Reflect.Message.OneOf}
       * @expose
       */
      this.oneof = oneof || null;

      /**
       * Syntax level of this definition (e.g., proto3).
       * @type {string}
       * @expose
       */
      this.syntax = syntax || 'proto2';

      /**
       * Original field name.
       * @type {string}
       * @expose
       */
      this.originalName = this.name; // Used to revert camelcase transformation on naming collisions

      /**
       * Element implementation. Created in build() after types are resolved.
       * @type {ProtoBuf.Element}
       * @expose
       */
      this.element = null;

      /**
       * Key element implementation, for map fields. Created in build() after
       * types are resolved.
       * @type {ProtoBuf.Element}
       * @expose
       */
      this.keyElement = null;

      // Convert field names to camel case notation if the override is set
      if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField))
        this.name = ProtoBuf.Util.toCamelCase(this.name);
    };

    /**
     * @alias ProtoBuf.Reflect.Message.Field.prototype
     * @inner
     */
    var FieldPrototype = Field.prototype = Object.create(T.prototype);

    /**
     * Builds the field.
     * @override
     * @expose
     */
    FieldPrototype.build = function () {
      this.element = new Element(this.type, this.resolvedType, false, this.syntax);
      if (this.map)
        this.keyElement = new Element(this.keyType, undefined, true, this.syntax);

      // In proto3, fields do not have field presence, and every field is set to
      // its type's default value ("", 0, 0.0, or false).
      if (this.syntax === 'proto3' && !this.repeated && !this.map)
        this.defaultValue = Element.defaultFieldValue(this.type);

      // Otherwise, default values are present when explicitly specified
      else if (typeof this.options['default'] !== 'undefined')
        this.defaultValue = this.verifyValue(this.options['default']);
    };

    /**
     * Checks if the given value can be set for this field.
     * @param {*} value Value to check
     * @param {boolean=} skipRepeated Whether to skip the repeated value check or not. Defaults to false.
     * @return {*} Verified, maybe adjusted, value
     * @throws {Error} If the value cannot be set for this field
     * @expose
     */
    FieldPrototype.verifyValue = function (value, skipRepeated) {
      skipRepeated = skipRepeated || false;
      var fail = function (val, msg) {
        throw Error("Illegal value for " + this.toString(true) + " of type " + this.type.name + ": " + val + " (" + msg + ")");
      }.bind(this);
      if (value === null) { // NULL values for optional fields
        if (this.required)
          fail(typeof value, "required");
        if (this.syntax === 'proto3' && this.type !== ProtoBuf.TYPES["message"])
          fail(typeof value, "proto3 field without field presence cannot be null");
        return null;
      }
      var i;
      if (this.repeated && !skipRepeated) { // Repeated values as arrays
        if (!Array.isArray(value))
          value = [value];
        var res = [];
        for (i = 0; i < value.length; i++)
          res.push(this.element.verifyValue(value[i]));
        return res;
      }
      if (this.map && !skipRepeated) { // Map values as objects
        if (!(value instanceof ProtoBuf.Map)) {
          // If not already a Map, attempt to convert.
          if (!(value instanceof Object)) {
            fail(typeof value,
              "expected ProtoBuf.Map or raw object for map field");
          }
          return new ProtoBuf.Map(this, value);
        } else {
          return value;
        }
      }
      // All non-repeated fields expect no array
      if (!this.repeated && Array.isArray(value))
        fail(typeof value, "no array expected");

      return this.element.verifyValue(value);
    };

    /**
     * Determines whether the field will have a presence on the wire given its
     * value.
     * @param {*} value Verified field value
     * @param {!ProtoBuf.Builder.Message} message Runtime message
     * @return {boolean} Whether the field will be present on the wire
     */
    FieldPrototype.hasWirePresence = function (value, message) {
      if (this.syntax !== 'proto3')
        return (value !== null);
      if (this.oneof && message[this.oneof.name] === this.name)
        return true;
      switch (this.type) {
      case ProtoBuf.TYPES["int32"]:
      case ProtoBuf.TYPES["sint32"]:
      case ProtoBuf.TYPES["sfixed32"]:
      case ProtoBuf.TYPES["uint32"]:
      case ProtoBuf.TYPES["fixed32"]:
        return value !== 0;

      case ProtoBuf.TYPES["int64"]:
      case ProtoBuf.TYPES["sint64"]:
      case ProtoBuf.TYPES["sfixed64"]:
      case ProtoBuf.TYPES["uint64"]:
      case ProtoBuf.TYPES["fixed64"]:
        return value.low !== 0 || value.high !== 0;

      case ProtoBuf.TYPES["bool"]:
        return value;

      case ProtoBuf.TYPES["float"]:
      case ProtoBuf.TYPES["double"]:
        return value !== 0.0;

      case ProtoBuf.TYPES["string"]:
        return value.length > 0;

      case ProtoBuf.TYPES["bytes"]:
        return value.remaining() > 0;

      case ProtoBuf.TYPES["enum"]:
        return value !== 0;

      case ProtoBuf.TYPES["message"]:
        return value !== null;
      default:
        return true;
      }
    };

    /**
     * Encodes the specified field value to the specified buffer.
     * @param {*} value Verified field value
     * @param {ByteBuffer} buffer ByteBuffer to encode to
     * @param {!ProtoBuf.Builder.Message} message Runtime message
     * @return {ByteBuffer} The ByteBuffer for chaining
     * @throws {Error} If the field cannot be encoded
     * @expose
     */
    FieldPrototype.encode = function (value, buffer, message) {
      if (this.type === null || typeof this.type !== 'object')
        throw Error("[INTERNAL] Unresolved type in " + this.toString(true) + ": " + this.type);
      if (value === null || (this.repeated && value.length == 0))
        return buffer; // Optional omitted
      try {
        if (this.repeated) {
          var i;
          // "Only repeated fields of primitive numeric types (types which use the varint, 32-bit, or 64-bit wire
          // types) can be declared 'packed'."
          if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
            // "All of the elements of the field are packed into a single key-value pair with wire type 2
            // (length-delimited). Each element is encoded the same way it would be normally, except without a
            // tag preceding it."
            buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
            buffer.ensureCapacity(buffer.offset += 1); // We do not know the length yet, so let's assume a varint of length 1
            var start = buffer.offset; // Remember where the contents begin
            for (i = 0; i < value.length; i++)
              this.element.encodeValue(this.id, value[i], buffer);
            var len = buffer.offset - start,
              varintLen = ByteBuffer.calculateVarint32(len);
            if (varintLen > 1) { // We need to move the contents
              var contents = buffer.slice(start, buffer.offset);
              start += varintLen - 1;
              buffer.offset = start;
              buffer.append(contents);
            }
            buffer.writeVarint32(len, start - varintLen);
          } else {
            // "If your message definition has repeated elements (without the [packed=true] option), the encoded
            // message has zero or more key-value pairs with the same tag number"
            for (i = 0; i < value.length; i++)
              buffer.writeVarint32((this.id << 3) | this.type.wireType),
              this.element.encodeValue(this.id, value[i], buffer);
          }
        } else if (this.map) {
          // Write out each map entry as a submessage.
          value.forEach(function (val, key, m) {
            // Compute the length of the submessage (key, val) pair.
            var length =
              ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
              this.keyElement.calculateLength(1, key) +
              ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
              this.element.calculateLength(2, val);

            // Submessage with wire type of length-delimited.
            buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
            buffer.writeVarint32(length);

            // Write out the key and val.
            buffer.writeVarint32((1 << 3) | this.keyType.wireType);
            this.keyElement.encodeValue(1, key, buffer);
            buffer.writeVarint32((2 << 3) | this.type.wireType);
            this.element.encodeValue(2, val, buffer);
          }, this);
        } else {
          if (this.hasWirePresence(value, message)) {
            buffer.writeVarint32((this.id << 3) | this.type.wireType);
            this.element.encodeValue(this.id, value, buffer);
          }
        }
      } catch (e) {
        throw Error("Illegal value for " + this.toString(true) + ": " + value + " (" + e + ")");
      }
      return buffer;
    };

    /**
     * Calculates the length of this field's value on the network level.
     * @param {*} value Field value
     * @param {!ProtoBuf.Builder.Message} message Runtime message
     * @returns {number} Byte length
     * @expose
     */
    FieldPrototype.calculate = function (value, message) {
      value = this.verifyValue(value); // May throw
      if (this.type === null || typeof this.type !== 'object')
        throw Error("[INTERNAL] Unresolved type in " + this.toString(true) + ": " + this.type);
      if (value === null || (this.repeated && value.length == 0))
        return 0; // Optional omitted
      var n = 0;
      try {
        if (this.repeated) {
          var i, ni;
          if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
            n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
            ni = 0;
            for (i = 0; i < value.length; i++)
              ni += this.element.calculateLength(this.id, value[i]);
            n += ByteBuffer.calculateVarint32(ni);
            n += ni;
          } else {
            for (i = 0; i < value.length; i++)
              n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType),
              n += this.element.calculateLength(this.id, value[i]);
          }
        } else if (this.map) {
          // Each map entry becomes a submessage.
          value.forEach(function (val, key, m) {
            // Compute the length of the submessage (key, val) pair.
            var length =
              ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
              this.keyElement.calculateLength(1, key) +
              ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
              this.element.calculateLength(2, val);

            n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
            n += ByteBuffer.calculateVarint32(length);
            n += length;
          }, this);
        } else {
          if (this.hasWirePresence(value, message)) {
            n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType);
            n += this.element.calculateLength(this.id, value);
          }
        }
      } catch (e) {
        throw Error("Illegal value for " + this.toString(true) + ": " + value + " (" + e + ")");
      }
      return n;
    };

    /**
     * Decode the field value from the specified buffer.
     * @param {number} wireType Leading wire type
     * @param {ByteBuffer} buffer ByteBuffer to decode from
     * @param {boolean=} skipRepeated Whether to skip the repeated check or not. Defaults to false.
     * @return {*} Decoded value: array for packed repeated fields, [key, value] for
     *             map fields, or an individual value otherwise.
     * @throws {Error} If the field cannot be decoded
     * @expose
     */
    FieldPrototype.decode = function (wireType, buffer, skipRepeated) {
      var value, nBytes;

      // We expect wireType to match the underlying type's wireType unless we see
      // a packed repeated field, or unless this is a map field.
      var wireTypeOK =
        (!this.map && wireType == this.type.wireType) ||
        (!skipRepeated && this.repeated && this.options["packed"] &&
          wireType == ProtoBuf.WIRE_TYPES.LDELIM) ||
        (this.map && wireType == ProtoBuf.WIRE_TYPES.LDELIM);
      if (!wireTypeOK)
        throw Error("Illegal wire type for field " + this.toString(true) + ": " + wireType + " (" + this.type.wireType + " expected)");

      // Handle packed repeated fields.
      if (wireType == ProtoBuf.WIRE_TYPES.LDELIM && this.repeated && this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
        if (!skipRepeated) {
          nBytes = buffer.readVarint32();
          nBytes = buffer.offset + nBytes; // Limit
          var values = [];
          while (buffer.offset < nBytes)
            values.push(this.decode(this.type.wireType, buffer, true));
          return values;
        }
        // Read the next value otherwise...
      }

      // Handle maps.
      if (this.map) {
        // Read one (key, value) submessage, and return [key, value]
        var key = Element.defaultFieldValue(this.keyType);
        value = Element.defaultFieldValue(this.type);

        // Read the length
        nBytes = buffer.readVarint32();
        if (buffer.remaining() < nBytes)
          throw Error("Illegal number of bytes for " + this.toString(true) + ": " + nBytes + " required but got only " + buffer.remaining());

        // Get a sub-buffer of this key/value submessage
        var msgbuf = buffer.clone();
        msgbuf.limit = msgbuf.offset + nBytes;
        buffer.offset += nBytes;

        while (msgbuf.remaining() > 0) {
          var tag = msgbuf.readVarint32();
          wireType = tag & 0x07;
          var id = tag >>> 3;
          if (id === 1) {
            key = this.keyElement.decode(msgbuf, wireType, id);
          } else if (id === 2) {
            value = this.element.decode(msgbuf, wireType, id);
          } else {
            throw Error("Unexpected tag in map field key/value submessage");
          }
        }

        return [key, value];
      }

      // Handle singular and non-packed repeated field values.
      return this.element.decode(buffer, wireType, this.id);
    };

    /**
     * @alias ProtoBuf.Reflect.Message.Field
     * @expose
     */
    Reflect.Message.Field = Field;

    /**
     * Constructs a new Message ExtensionField.
     * @exports ProtoBuf.Reflect.Message.ExtensionField
     * @param {!ProtoBuf.Builder} builder Builder reference
     * @param {!ProtoBuf.Reflect.Message} message Message reference
     * @param {string} rule Rule, one of requried, optional, repeated
     * @param {string} type Data type, e.g. int32
     * @param {string} name Field name
     * @param {number} id Unique field id
     * @param {!Object.<string,*>=} options Options
     * @constructor
     * @extends ProtoBuf.Reflect.Message.Field
     */
    var ExtensionField = function (builder, message, rule, type, name, id, options) {
      Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options);

      /**
       * Extension reference.
       * @type {!ProtoBuf.Reflect.Extension}
       * @expose
       */
      this.extension;
    };

    // Extends Field
    ExtensionField.prototype = Object.create(Field.prototype);

    /**
     * @alias ProtoBuf.Reflect.Message.ExtensionField
     * @expose
     */
    Reflect.Message.ExtensionField = ExtensionField;

    /**
     * Constructs a new Message OneOf.
     * @exports ProtoBuf.Reflect.Message.OneOf
     * @param {!ProtoBuf.Builder} builder Builder reference
     * @param {!ProtoBuf.Reflect.Message} message Message reference
     * @param {string} name OneOf name
     * @constructor
     * @extends ProtoBuf.Reflect.T
     */
    var OneOf = function (builder, message, name) {
      T.call(this, builder, message, name);

      /**
       * Enclosed fields.
       * @type {!Array.<!ProtoBuf.Reflect.Message.Field>}
       * @expose
       */
      this.fields = [];
    };

    /**
     * @alias ProtoBuf.Reflect.Message.OneOf
     * @expose
     */
    Reflect.Message.OneOf = OneOf;

    /**
     * Constructs a new Enum.
     * @exports ProtoBuf.Reflect.Enum
     * @param {!ProtoBuf.Builder} builder Builder reference
     * @param {!ProtoBuf.Reflect.T} parent Parent Reflect object
     * @param {string} name Enum name
     * @param {Object.<string,*>=} options Enum options
     * @param {string?} syntax The syntax level (e.g., proto3)
     * @constructor
     * @extends ProtoBuf.Reflect.Namespace
     */
    var Enum = function (builder, parent, name, options, syntax) {
      Namespace.call(this, builder, parent, name, options, syntax);

      /**
       * @override
       */
      this.className = "Enum";

      /**
       * Runtime enum object.
       * @type {Object.<string,number>|null}
       * @expose
       */
      this.object = null;
    };

    /**
     * Gets the string name of an enum value.
     * @param {!ProtoBuf.Builder.Enum} enm Runtime enum
     * @param {number} value Enum value
     * @returns {?string} Name or `null` if not present
     * @expose
     */
    Enum.getName = function (enm, value) {
      var keys = Object.keys(enm);
      for (var i = 0, key; i < keys.length; ++i)
        if (enm[key = keys[i]] === value)
          return key;
      return null;
    };

    /**
     * @alias ProtoBuf.Reflect.Enum.prototype
     * @inner
     */
    var EnumPrototype = Enum.prototype = Object.create(Namespace.prototype);

    /**
     * Builds this enum and returns the runtime counterpart.
     * @param {boolean} rebuild Whether to rebuild or not, defaults to false
     * @returns {!Object.<string,number>}
     * @expose
     */
    EnumPrototype.build = function (rebuild) {
      if (this.object && !rebuild)
        return this.object;
      var enm = new ProtoBuf.Builder.Enum(),
        values = this.getChildren(Enum.Value);
      for (var i = 0, k = values.length; i < k; ++i)
        enm[values[i]['name']] = values[i]['id'];
      if (Object.defineProperty)
        Object.defineProperty(enm, '$options', {
          "value": this.buildOpt(),
          "enumerable": false
        });
      return this.object = enm;
    };

    /**
     * @alias ProtoBuf.Reflect.Enum
     * @expose
     */
    Reflect.Enum = Enum;

    /**
     * Constructs a new Enum Value.
     * @exports ProtoBuf.Reflect.Enum.Value
     * @param {!ProtoBuf.Builder} builder Builder reference
     * @param {!ProtoBuf.Reflect.Enum} enm Enum reference
     * @param {string} name Field name
     * @param {number} id Unique field id
     * @constructor
     * @extends ProtoBuf.Reflect.T
     */
    var Value = function (builder, enm, name, id) {
      T.call(this, builder, enm, name);

      /**
       * @override
       */
      this.className = "Enum.Value";

      /**
       * Unique enum value id.
       * @type {number}
       * @expose
       */
      this.id = id;
    };

    // Extends T
    Value.prototype = Object.create(T.prototype);

    /**
     * @alias ProtoBuf.Reflect.Enum.Value
     * @expose
     */
    Reflect.Enum.Value = Value;

    /**
     * An extension (field).
     * @exports ProtoBuf.Reflect.Extension
     * @constructor
     * @param {!ProtoBuf.Builder} builder Builder reference
     * @param {!ProtoBuf.Reflect.T} parent Parent object
     * @param {string} name Object name
     * @param {!ProtoBuf.Reflect.Message.Field} field Extension field
     */
    var Extension = function (builder, parent, name, field) {
      T.call(this, builder, parent, name);

      /**
       * Extended message field.
       * @type {!ProtoBuf.Reflect.Message.Field}
       * @expose
       */
      this.field = field;
    };

    // Extends T
    Extension.prototype = Object.create(T.prototype);

    /**
     * @alias ProtoBuf.Reflect.Extension
     * @expose
     */
    Reflect.Extension = Extension;

    /**
     * Constructs a new Service.
     * @exports ProtoBuf.Reflect.Service
     * @param {!ProtoBuf.Builder} builder Builder reference
     * @param {!ProtoBuf.Reflect.Namespace} root Root
     * @param {string} name Service name
     * @param {Object.<string,*>=} options Options
     * @constructor
     * @extends ProtoBuf.Reflect.Namespace
     */
    var Service = function (builder, root, name, options) {
      Namespace.call(this, builder, root, name, options);

      /**
       * @override
       */
      this.className = "Service";

      /**
       * Built runtime service class.
       * @type {?function(new:ProtoBuf.Builder.Service)}
       */
      this.clazz = null;
    };

    /**
     * @alias ProtoBuf.Reflect.Service.prototype
     * @inner
     */
    var ServicePrototype = Service.prototype = Object.create(Namespace.prototype);

    /**
     * Builds the service and returns the runtime counterpart, which is a fully functional class.
     * @see ProtoBuf.Builder.Service
     * @param {boolean=} rebuild Whether to rebuild or not
     * @return {Function} Service class
     * @throws {Error} If the message cannot be built
     * @expose
     */
    ServicePrototype.build = function (rebuild) {
      if (this.clazz && !rebuild)
        return this.clazz;

      // Create the runtime Service class in its own scope
      return this.clazz = (function (ProtoBuf, T) {

        /**
         * Constructs a new runtime Service.
         * @name ProtoBuf.Builder.Service
         * @param {function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))=} rpcImpl RPC implementation receiving the method name and the message
         * @class Barebone of all runtime services.
         * @constructor
         * @throws {Error} If the service cannot be created
         */
        var Service = function (rpcImpl) {
          ProtoBuf.Builder.Service.call(this);

          /**
           * Service implementation.
           * @name ProtoBuf.Builder.Service#rpcImpl
           * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))}
           * @expose
           */
          this.rpcImpl = rpcImpl || function (name, msg, callback) {
            // This is what a user has to implement: A function receiving the method name, the actual message to
            // send (type checked) and the callback that's either provided with the error as its first
            // argument or null and the actual response message.
            setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async!
          };
        };

        /**
         * @alias ProtoBuf.Builder.Service.prototype
         * @inner
         */
        var ServicePrototype = Service.prototype = Object.create(ProtoBuf.Builder.Service.prototype);

        /**
         * Asynchronously performs an RPC call using the given RPC implementation.
         * @name ProtoBuf.Builder.Service.[Method]
         * @function
         * @param {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} rpcImpl RPC implementation
         * @param {ProtoBuf.Builder.Message} req Request
         * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
         *  the error if any and the response either as a pre-parsed message or as its raw bytes
         * @abstract
         */

        /**
         * Asynchronously performs an RPC call using the instance's RPC implementation.
         * @name ProtoBuf.Builder.Service#[Method]
         * @function
         * @param {ProtoBuf.Builder.Message} req Request
         * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
         *  the error if any and the response either as a pre-parsed message or as its raw bytes
         * @abstract
         */

        var rpc = T.getChildren(ProtoBuf.Reflect.Service.RPCMethod);
        for (var i = 0; i < rpc.length; i++) {
          (function (method) {

            // service#Method(message, callback)
            ServicePrototype[method.name] = function (req, callback) {
              try {
                try {
                  // If given as a buffer, decode the request. Will throw a TypeError if not a valid buffer.
                  req = method.resolvedRequestType.clazz.decode(ByteBuffer.wrap(req));
                } catch (err) {
                  if (!(err instanceof TypeError))
                    throw err;
                }
                if (req === null || typeof req !== 'object')
                  throw Error("Illegal arguments");
                if (!(req instanceof method.resolvedRequestType.clazz))
                  req = new method.resolvedRequestType.clazz(req);
                this.rpcImpl(method.fqn(), req, function (err, res) { // Assumes that this is properly async
                  if (err) {
                    callback(err);
                    return;
                  }
                  try { res = method.resolvedResponseType.clazz.decode(res); } catch (notABuffer) {}
                  if (!res || !(res instanceof method.resolvedResponseType.clazz)) {
                    callback(Error("Illegal response type received in service method " + T.name + "#" + method.name));
                    return;
                  }
                  callback(null, res);
                });
              } catch (err) {
                setTimeout(callback.bind(this, err), 0);
              }
            };

            // Service.Method(rpcImpl, message, callback)
            Service[method.name] = function (rpcImpl, req, callback) {
              new Service(rpcImpl)[method.name](req, callback);
            };

            if (Object.defineProperty)
              Object.defineProperty(Service[method.name], "$options", { "value": method.buildOpt() }),
              Object.defineProperty(ServicePrototype[method.name], "$options", { "value": Service[method.name]["$options"] });
          })(rpc[i]);
        }

        // Properties

        /**
         * Service options.
         * @name ProtoBuf.Builder.Service.$options
         * @type {Object.<string,*>}
         * @expose
         */
        var $optionsS; // cc needs this

        /**
         * Service options.
         * @name ProtoBuf.Builder.Service#$options
         * @type {Object.<string,*>}
         * @expose
         */
        var $options;

        /**
         * Reflection type.
         * @name ProtoBuf.Builder.Service.$type
         * @type {!ProtoBuf.Reflect.Service}
         * @expose
         */
        var $typeS;

        /**
         * Reflection type.
         * @name ProtoBuf.Builder.Service#$type
         * @type {!ProtoBuf.Reflect.Service}
         * @expose
         */
        var $type;

        if (Object.defineProperty)
          Object.defineProperty(Service, "$options", { "value": T.buildOpt() }),
          Object.defineProperty(ServicePrototype, "$options", { "value": Service["$options"] }),
          Object.defineProperty(Service, "$type", { "value": T }),
          Object.defineProperty(ServicePrototype, "$type", { "value": T });

        return Service;

      })(ProtoBuf, this);
    };

    /**
     * @alias ProtoBuf.Reflect.Service
     * @expose
     */
    Reflect.Service = Service;

    /**
     * Abstract service method.
     * @exports ProtoBuf.Reflect.Service.Method
     * @param {!ProtoBuf.Builder} builder Builder reference
     * @param {!ProtoBuf.Reflect.Service} svc Service
     * @param {string} name Method name
     * @param {Object.<string,*>=} options Options
     * @constructor
     * @extends ProtoBuf.Reflect.T
     */
    var Method = function (builder, svc, name, options) {
      T.call(this, builder, svc, name);

      /**
       * @override
       */
      this.className = "Service.Method";

      /**
       * Options.
       * @type {Object.<string, *>}
       * @expose
       */
      this.options = options || {};
    };

    /**
     * @alias ProtoBuf.Reflect.Service.Method.prototype
     * @inner
     */
    var MethodPrototype = Method.prototype = Object.create(T.prototype);

    /**
     * Builds the method's '$options' property.
     * @name ProtoBuf.Reflect.Service.Method#buildOpt
     * @function
     * @return {Object.<string,*>}
     */
    MethodPrototype.buildOpt = NamespacePrototype.buildOpt;

    /**
     * @alias ProtoBuf.Reflect.Service.Method
     * @expose
     */
    Reflect.Service.Method = Method;

    /**
     * RPC service method.
     * @exports ProtoBuf.Reflect.Service.RPCMethod
     * @param {!ProtoBuf.Builder} builder Builder reference
     * @param {!ProtoBuf.Reflect.Service} svc Service
     * @param {string} name Method name
     * @param {string} request Request message name
     * @param {string} response Response message name
     * @param {boolean} request_stream Whether requests are streamed
     * @param {boolean} response_stream Whether responses are streamed
     * @param {Object.<string,*>=} options Options
     * @constructor
     * @extends ProtoBuf.Reflect.Service.Method
     */
    var RPCMethod = function (builder, svc, name, request, response, request_stream, response_stream, options) {
      Method.call(this, builder, svc, name, options);

      /**
       * @override
       */
      this.className = "Service.RPCMethod";

      /**
       * Request message name.
       * @type {string}
       * @expose
       */
      this.requestName = request;

      /**
       * Response message name.
       * @type {string}
       * @expose
       */
      this.responseName = response;

      /**
       * Whether requests are streamed
       * @type {bool}
       * @expose
       */
      this.requestStream = request_stream;

      /**
       * Whether responses are streamed
       * @type {bool}
       * @expose
       */
      this.responseStream = response_stream;

      /**
       * Resolved request message type.
       * @type {ProtoBuf.Reflect.Message}
       * @expose
       */
      this.resolvedRequestType = null;

      /**
       * Resolved response message type.
       * @type {ProtoBuf.Reflect.Message}
       * @expose
       */
      this.resolvedResponseType = null;
    };

    // Extends Method
    RPCMethod.prototype = Object.create(Method.prototype);

    /**
     * @alias ProtoBuf.Reflect.Service.RPCMethod
     * @expose
     */
    Reflect.Service.RPCMethod = RPCMethod;

    return Reflect;

  })(ProtoBuf);

  /**
   * @alias ProtoBuf.Builder
   * @expose
   */
  ProtoBuf.Builder = (function (ProtoBuf, Lang, Reflect) {
    "use strict";

    /**
     * Constructs a new Builder.
     * @exports ProtoBuf.Builder
     * @class Provides the functionality to build protocol messages.
     * @param {Object.<string,*>=} options Options
     * @constructor
     */
    var Builder = function (options) {

      /**
       * Namespace.
       * @type {ProtoBuf.Reflect.Namespace}
       * @expose
       */
      this.ns = new Reflect.Namespace(this, null, ""); // Global namespace

      /**
       * Namespace pointer.
       * @type {ProtoBuf.Reflect.T}
       * @expose
       */
      this.ptr = this.ns;

      /**
       * Resolved flag.
       * @type {boolean}
       * @expose
       */
      this.resolved = false;

      /**
       * The current building result.
       * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null}
       * @expose
       */
      this.result = null;

      /**
       * Imported files.
       * @type {Array.<string>}
       * @expose
       */
      this.files = {};

      /**
       * Import root override.
       * @type {?string}
       * @expose
       */
      this.importRoot = null;

      /**
       * Options.
       * @type {!Object.<string, *>}
       * @expose
       */
      this.options = options || {};
    };

    /**
     * @alias ProtoBuf.Builder.prototype
     * @inner
     */
    var BuilderPrototype = Builder.prototype;

    // ----- Definition tests -----

    /**
     * Tests if a definition most likely describes a message.
     * @param {!Object} def
     * @returns {boolean}
     * @expose
     */
    Builder.isMessage = function (def) {
      // Messages require a string name
      if (typeof def["name"] !== 'string')
        return false;
      // Messages do not contain values (enum) or rpc methods (service)
      if (typeof def["values"] !== 'undefined' || typeof def["rpc"] !== 'undefined')
        return false;
      return true;
    };

    /**
     * Tests if a definition most likely describes a message field.
     * @param {!Object} def
     * @returns {boolean}
     * @expose
     */
    Builder.isMessageField = function (def) {
      // Message fields require a string rule, name and type and an id
      if (typeof def["rule"] !== 'string' || typeof def["name"] !== 'string' || typeof def["type"] !== 'string' || typeof def["id"] === 'undefined')
        return false;
      return true;
    };

    /**
     * Tests if a definition most likely describes an enum.
     * @param {!Object} def
     * @returns {boolean}
     * @expose
     */
    Builder.isEnum = function (def) {
      // Enums require a string name
      if (typeof def["name"] !== 'string')
        return false;
      // Enums require at least one value
      if (typeof def["values"] === 'undefined' || !Array.isArray(def["values"]) || def["values"].length === 0)
        return false;
      return true;
    };

    /**
     * Tests if a definition most likely describes a service.
     * @param {!Object} def
     * @returns {boolean}
     * @expose
     */
    Builder.isService = function (def) {
      // Services require a string name and an rpc object
      if (typeof def["name"] !== 'string' || typeof def["rpc"] !== 'object' || !def["rpc"])
        return false;
      return true;
    };

    /**
     * Tests if a definition most likely describes an extended message
     * @param {!Object} def
     * @returns {boolean}
     * @expose
     */
    Builder.isExtend = function (def) {
      // Extends rquire a string ref
      if (typeof def["ref"] !== 'string')
        return false;
      return true;
    };

    // ----- Building -----

    /**
     * Resets the pointer to the root namespace.
     * @returns {!ProtoBuf.Builder} this
     * @expose
     */
    BuilderPrototype.reset = function () {
      this.ptr = this.ns;
      return this;
    };

    /**
     * Defines a namespace on top of the current pointer position and places the pointer on it.
     * @param {string} namespace
     * @return {!ProtoBuf.Builder} this
     * @expose
     */
    BuilderPrototype.define = function (namespace) {
      if (typeof namespace !== 'string' || !Lang.TYPEREF.test(namespace))
        throw Error("illegal namespace: " + namespace);
      namespace.split(".").forEach(function (part) {
        var ns = this.ptr.getChild(part);
        if (ns === null) // Keep existing
          this.ptr.addChild(ns = new Reflect.Namespace(this, this.ptr, part));
        this.ptr = ns;
      }, this);
      return this;
    };

    /**
     * Creates the specified definitions at the current pointer position.
     * @param {!Array.<!Object>} defs Messages, enums or services to create
     * @returns {!ProtoBuf.Builder} this
     * @throws {Error} If a message definition is invalid
     * @expose
     */
    BuilderPrototype.create = function (defs) {
      if (!defs)
        return this; // Nothing to create
      if (!Array.isArray(defs))
        defs = [defs];
      else {
        if (defs.length === 0)
          return this;
        defs = defs.slice();
      }

      // It's quite hard to keep track of scopes and memory here, so let's do this iteratively.
      var stack = [defs];
      while (stack.length > 0) {
        defs = stack.pop();

        if (!Array.isArray(defs)) // Stack always contains entire namespaces
          throw Error("not a valid namespace: " + JSON.stringify(defs));

        while (defs.length > 0) {
          var def = defs.shift(); // Namespaces always contain an array of messages, enums and services

          if (Builder.isMessage(def)) {
            var obj = new Reflect.Message(this, this.ptr, def["name"], def["options"], def["isGroup"], def["syntax"]);

            // Create OneOfs
            var oneofs = {};
            if (def["oneofs"])
              Object.keys(def["oneofs"]).forEach(function (name) {
                obj.addChild(oneofs[name] = new Reflect.Message.OneOf(this, obj, name));
              }, this);

            // Create fields
            if (def["fields"])
              def["fields"].forEach(function (fld) {
                if (obj.getChild(fld["id"] | 0) !== null)
                  throw Error("duplicate or invalid field id in " + obj.name + ": " + fld['id']);
                if (fld["options"] && typeof fld["options"] !== 'object')
                  throw Error("illegal field options in " + obj.name + "#" + fld["name"]);
                var oneof = null;
                if (typeof fld["oneof"] === 'string' && !(oneof = oneofs[fld["oneof"]]))
                  throw Error("illegal oneof in " + obj.name + "#" + fld["name"] + ": " + fld["oneof"]);
                fld = new Reflect.Message.Field(this, obj, fld["rule"], fld["keytype"], fld["type"], fld["name"], fld["id"], fld["options"], oneof, def["syntax"]);
                if (oneof)
                  oneof.fields.push(fld);
                obj.addChild(fld);
              }, this);

            // Push children to stack
            var subObj = [];
            if (def["enums"])
              def["enums"].forEach(function (enm) {
                subObj.push(enm);
              });
            if (def["messages"])
              def["messages"].forEach(function (msg) {
                subObj.push(msg);
              });
            if (def["services"])
              def["services"].forEach(function (svc) {
                subObj.push(svc);
              });

            // Set extension range
            if (def["extensions"]) {
              obj.extensions = def["extensions"];
              if (obj.extensions[0] < ProtoBuf.ID_MIN)
                obj.extensions[0] = ProtoBuf.ID_MIN;
              if (obj.extensions[1] > ProtoBuf.ID_MAX)
                obj.extensions[1] = ProtoBuf.ID_MAX;
            }

            // Create on top of current namespace
            this.ptr.addChild(obj);
            if (subObj.length > 0) {
              stack.push(defs); // Push the current level back
              defs = subObj; // Continue processing sub level
              subObj = null;
              this.ptr = obj; // And move the pointer to this namespace
              obj = null;
              continue;
            }
            subObj = null;

          } else if (Builder.isEnum(def)) {

            obj = new Reflect.Enum(this, this.ptr, def["name"], def["options"], def["syntax"]);
            def["values"].forEach(function (val) {
              obj.addChild(new Reflect.Enum.Value(this, obj, val["name"], val["id"]));
            }, this);
            this.ptr.addChild(obj);

          } else if (Builder.isService(def)) {

            obj = new Reflect.Service(this, this.ptr, def["name"], def["options"]);
            Object.keys(def["rpc"]).forEach(function (name) {
              var mtd = def["rpc"][name];
              obj.addChild(new Reflect.Service.RPCMethod(this, obj, name, mtd["request"], mtd["response"], !!mtd["request_stream"], !!mtd["response_stream"], mtd["options"]));
            }, this);
            this.ptr.addChild(obj);

          } else if (Builder.isExtend(def)) {

            obj = this.ptr.resolve(def["ref"], true);
            if (obj) {
              def["fields"].forEach(function (fld) {
                if (obj.getChild(fld['id'] | 0) !== null)
                  throw Error("duplicate extended field id in " + obj.name + ": " + fld['id']);
                if (fld['id'] < obj.extensions[0] || fld['id'] > obj.extensions[1])
                  throw Error("illegal extended field id in " + obj.name + ": " + fld['id'] + " (" + obj.extensions.join(' to ') + " expected)");
                // Convert extension field names to camel case notation if the override is set
                var name = fld["name"];
                if (this.options['convertFieldsToCamelCase'])
                  name = ProtoBuf.Util.toCamelCase(name);
                // see #161: Extensions use their fully qualified name as their runtime key and...
                var field = new Reflect.Message.ExtensionField(this, obj, fld["rule"], fld["type"], this.ptr.fqn() + '.' + name, fld["id"], fld["options"]);
                // ...are added on top of the current namespace as an extension which is used for
                // resolving their type later on (the extension always keeps the original name to
                // prevent naming collisions)
                var ext = new Reflect.Extension(this, this.ptr, fld["name"], field);
                field.extension = ext;
                this.ptr.addChild(ext);
                obj.addChild(field);
              }, this);

            } else if (!/\.?google\.protobuf\./.test(def["ref"])) // Silently skip internal extensions
              throw Error("extended message " + def["ref"] + " is not defined");

          } else
            throw Error("not a valid definition: " + JSON.stringify(def));

          def = null;
          obj = null;
        }
        // Break goes here
        defs = null;
        this.ptr = this.ptr.parent; // Namespace done, continue at parent
      }
      this.resolved = false; // Require re-resolve
      this.result = null; // Require re-build
      return this;
    };

    /**
     * Propagates syntax to all children.
     * @param {!Object} parent
     * @inner
     */
    function propagateSyntax(parent) {
      if (parent['messages']) {
        parent['messages'].forEach(function (child) {
          child["syntax"] = parent["syntax"];
          propagateSyntax(child);
        });
      }
      if (parent['enums']) {
        parent['enums'].forEach(function (child) {
          child["syntax"] = parent["syntax"];
        });
      }
    }

    /**
     * Imports another definition into this builder.
     * @param {Object.<string,*>} json Parsed import
     * @param {(string|{root: string, file: string})=} filename Imported file name
     * @returns {!ProtoBuf.Builder} this
     * @throws {Error} If the definition or file cannot be imported
     * @expose
     */
    BuilderPrototype["import"] = function (json, filename) {
      var delim = '/';

      // Make sure to skip duplicate imports

      if (typeof filename === 'string') {

        if (ProtoBuf.Util.IS_NODE)
          filename = ProtoBuf.Util.require("path")['resolve'](filename);
        if (this.files[filename] === true)
          return this.reset();
        this.files[filename] = true;

      } else if (typeof filename === 'object') { // Object with root, file.

        var root = filename.root;
        if (ProtoBuf.Util.IS_NODE)
          root = ProtoBuf.Util.require("path")['resolve'](root);
        if (root.indexOf("\\") >= 0 || filename.file.indexOf("\\") >= 0)
          delim = '\\';
        var fname = root + delim + filename.file;
        if (this.files[fname] === true)
          return this.reset();
        this.files[fname] = true;
      }

      // Import imports

      if (json['imports'] && json['imports'].length > 0) {
        var importRoot,
          resetRoot = false;

        if (typeof filename === 'object') { // If an import root is specified, override

          this.importRoot = filename["root"];
          resetRoot = true; // ... and reset afterwards
          importRoot = this.importRoot;
          filename = filename["file"];
          if (importRoot.indexOf("\\") >= 0 || filename.indexOf("\\") >= 0)
            delim = '\\';

        } else if (typeof filename === 'string') {

          if (this.importRoot) // If import root is overridden, use it
            importRoot = this.importRoot;
          else { // Otherwise compute from filename
            if (filename.indexOf("/") >= 0) { // Unix
              importRoot = filename.replace(/\/[^\/]*$/, "");
              if ( /* /file.proto */ importRoot === "")
                importRoot = "/";
            } else if (filename.indexOf("\\") >= 0) { // Windows
              importRoot = filename.replace(/\\[^\\]*$/, "");
              delim = '\\';
            } else
              importRoot = ".";
          }

        } else
          importRoot = null;

        for (var i = 0; i < json['imports'].length; i++) {
          if (typeof json['imports'][i] === 'string') { // Import file
            if (!importRoot)
              throw Error("cannot determine import root");
            var importFilename = json['imports'][i];
            if (importFilename === "google/protobuf/descriptor.proto")
              continue; // Not needed and therefore not used
            importFilename = importRoot + delim + importFilename;
            if (this.files[importFilename] === true)
              continue; // Already imported
            if (/\.proto$/i.test(importFilename) && !ProtoBuf.DotProto) // If this is a light build
              importFilename = importFilename.replace(/\.proto$/, ".json"); // always load the JSON file
            var contents = ProtoBuf.Util.fetch(importFilename);
            if (contents === null)
              throw Error("failed to import '" + importFilename + "' in '" + filename + "': file not found");
            if (/\.json$/i.test(importFilename)) // Always possible
              this["import"](JSON.parse(contents + ""), importFilename); // May throw
            else
              this["import"](ProtoBuf.DotProto.Parser.parse(contents), importFilename); // May throw
          } else // Import structure
          if (!filename)
            this["import"](json['imports'][i]);
          else if (/\.(\w+)$/.test(filename)) // With extension: Append _importN to the name portion to make it unique
            this["import"](json['imports'][i], filename.replace(/^(.+)\.(\w+)$/, function ($0, $1, $2) {
            return $1 + "_import" + i + "." + $2;
          }));
          else // Without extension: Append _importN to make it unique
            this["import"](json['imports'][i], filename + "_import" + i);
        }
        if (resetRoot) // Reset import root override when all imports are done
          this.importRoot = null;
      }

      // Import structures

      if (json['package'])
        this.define(json['package']);
      if (json['syntax'])
        propagateSyntax(json);
      var base = this.ptr;
      if (json['options'])
        Object.keys(json['options']).forEach(function (key) {
          base.options[key] = json['options'][key];
        });
      if (json['messages'])
        this.create(json['messages']),
        this.ptr = base;
      if (json['enums'])
        this.create(json['enums']),
        this.ptr = base;
      if (json['services'])
        this.create(json['services']),
        this.ptr = base;
      if (json['extends'])
        this.create(json['extends']);

      return this.reset();
    };

    /**
     * Resolves all namespace objects.
     * @throws {Error} If a type cannot be resolved
     * @returns {!ProtoBuf.Builder} this
     * @expose
     */
    BuilderPrototype.resolveAll = function () {
      // Resolve all reflected objects
      var res;
      if (this.ptr == null || typeof this.ptr.type === 'object')
        return this; // Done (already resolved)

      if (this.ptr instanceof Reflect.Namespace) { // Resolve children

        this.ptr.children.forEach(function (child) {
          this.ptr = child;
          this.resolveAll();
        }, this);

      } else if (this.ptr instanceof Reflect.Message.Field) { // Resolve type

        if (!Lang.TYPE.test(this.ptr.type)) {
          if (!Lang.TYPEREF.test(this.ptr.type))
            throw Error("illegal type reference in " + this.ptr.toString(true) + ": " + this.ptr.type);
          res = (this.ptr instanceof Reflect.Message.ExtensionField ? this.ptr.extension.parent : this.ptr.parent).resolve(this.ptr.type, true);
          if (!res)
            throw Error("unresolvable type reference in " + this.ptr.toString(true) + ": " + this.ptr.type);
          this.ptr.resolvedType = res;
          if (res instanceof Reflect.Enum) {
            this.ptr.type = ProtoBuf.TYPES["enum"];
            if (this.ptr.syntax === 'proto3' && res.syntax !== 'proto3')
              throw Error("proto3 message cannot reference proto2 enum");
          } else if (res instanceof Reflect.Message)
            this.ptr.type = res.isGroup ? ProtoBuf.TYPES["group"] : ProtoBuf.TYPES["message"];
          else
            throw Error("illegal type reference in " + this.ptr.toString(true) + ": " + this.ptr.type);
        } else
          this.ptr.type = ProtoBuf.TYPES[this.ptr.type];

        // If it's a map field, also resolve the key type. The key type can be only a numeric, string, or bool type
        // (i.e., no enums or messages), so we don't need to resolve against the current namespace.
        if (this.ptr.map) {
          if (!Lang.TYPE.test(this.ptr.keyType))
            throw Error("illegal key type for map field in " + this.ptr.toString(true) + ": " + this.ptr.keyType);
          this.ptr.keyType = ProtoBuf.TYPES[this.ptr.keyType];
        }

      } else if (this.ptr instanceof ProtoBuf.Reflect.Service.Method) {

        if (this.ptr instanceof ProtoBuf.Reflect.Service.RPCMethod) {
          res = this.ptr.parent.resolve(this.ptr.requestName, true);
          if (!res || !(res instanceof ProtoBuf.Reflect.Message))
            throw Error("Illegal type reference in " + this.ptr.toString(true) + ": " + this.ptr.requestName);
          this.ptr.resolvedRequestType = res;
          res = this.ptr.parent.resolve(this.ptr.responseName, true);
          if (!res || !(res instanceof ProtoBuf.Reflect.Message))
            throw Error("Illegal type reference in " + this.ptr.toString(true) + ": " + this.ptr.responseName);
          this.ptr.resolvedResponseType = res;
        } else // Should not happen as nothing else is implemented
          throw Error("illegal service type in " + this.ptr.toString(true));

      } else if (!(this.ptr instanceof ProtoBuf.Reflect.Message.OneOf) && // Not built
        !(this.ptr instanceof ProtoBuf.Reflect.Extension) && // Not built
        !(this.ptr instanceof ProtoBuf.Reflect.Enum.Value) // Built in enum
      )
        throw Error("illegal object in namespace: " + typeof (this.ptr) + ": " + this.ptr);

      return this.reset();
    };

    /**
     * Builds the protocol. This will first try to resolve all definitions and, if this has been successful,
     * return the built package.
     * @param {(string|Array.<string>)=} path Specifies what to return. If omitted, the entire namespace will be returned.
     * @returns {!ProtoBuf.Builder.Message|!Object.<string,*>}
     * @throws {Error} If a type could not be resolved
     * @expose
     */
    BuilderPrototype.build = function (path) {
      this.reset();
      if (!this.resolved)
        this.resolveAll(),
        this.resolved = true,
        this.result = null; // Require re-build
      if (this.result === null) // (Re-)Build
        this.result = this.ns.build();
      if (!path)
        return this.result;
      var part = typeof path === 'string' ? path.split(".") : path,
        ptr = this.result; // Build namespace pointer (no hasChild etc.)
      for (var i = 0; i < part.length; i++)
        if (ptr[part[i]])
          ptr = ptr[part[i]];
        else {
          ptr = null;
          break;
        }
      return ptr;
    };

    /**
     * Similar to {@link ProtoBuf.Builder#build}, but looks up the internal reflection descriptor.
     * @param {string=} path Specifies what to return. If omitted, the entire namespace wiil be returned.
     * @param {boolean=} excludeNonNamespace Excludes non-namespace types like fields, defaults to `false`
     * @returns {?ProtoBuf.Reflect.T} Reflection descriptor or `null` if not found
     */
    BuilderPrototype.lookup = function (path, excludeNonNamespace) {
      return path ? this.ns.resolve(path, excludeNonNamespace) : this.ns;
    };

    /**
     * Returns a string representation of this object.
     * @return {string} String representation as of "Builder"
     * @expose
     */
    BuilderPrototype.toString = function () {
      return "Builder";
    };

    // ----- Base classes -----
    // Exist for the sole purpose of being able to "... instanceof ProtoBuf.Builder.Message" etc.

    /**
     * @alias ProtoBuf.Builder.Message
     */
    Builder.Message = function () {};

    /**
     * @alias ProtoBuf.Builder.Enum
     */
    Builder.Enum = function () {};

    /**
     * @alias ProtoBuf.Builder.Message
     */
    Builder.Service = function () {};

    return Builder;

  })(ProtoBuf, ProtoBuf.Lang, ProtoBuf.Reflect);

  /**
   * @alias ProtoBuf.Map
   * @expose
   */
  ProtoBuf.Map = (function (ProtoBuf, Reflect) {
    "use strict";

    /**
     * Constructs a new Map. A Map is a container that is used to implement map
     * fields on message objects. It closely follows the ES6 Map API; however,
     * it is distinct because we do not want to depend on external polyfills or
     * on ES6 itself.
     *
     * @exports ProtoBuf.Map
     * @param {!ProtoBuf.Reflect.Field} field Map field
     * @param {Object.<string,*>=} contents Initial contents
     * @constructor
     */
    var Map = function (field, contents) {
      if (!field.map)
        throw Error("field is not a map");

      /**
       * The field corresponding to this map.
       * @type {!ProtoBuf.Reflect.Field}
       */
      this.field = field;

      /**
       * Element instance corresponding to key type.
       * @type {!ProtoBuf.Reflect.Element}
       */
      this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax);

      /**
       * Element instance corresponding to value type.
       * @type {!ProtoBuf.Reflect.Element}
       */
      this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax);

      /**
       * Internal map: stores mapping of (string form of key) -> (key, value)
       * pair.
       *
       * We provide map semantics for arbitrary key types, but we build on top
       * of an Object, which has only string keys. In order to avoid the need
       * to convert a string key back to its native type in many situations,
       * we store the native key value alongside the value. Thus, we only need
       * a one-way mapping from a key type to its string form that guarantees
       * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1
       * === K2).
       *
       * @type {!Object<string, {key: *, value: *}>}
       */
      this.map = {};

      /**
       * Returns the number of elements in the map.
       */
      Object.defineProperty(this, "size", {
        get: function () {
          return Object.keys(this.map).length;
        }
      });

      // Fill initial contents from a raw object.
      if (contents) {
        var keys = Object.keys(contents);
        for (var i = 0; i < keys.length; i++) {
          var key = this.keyElem.valueFromString(keys[i]);
          var val = this.valueElem.verifyValue(contents[keys[i]]);
          this.map[this.keyElem.valueToString(key)] = { key: key, value: val };
        }
      }
    };

    var MapPrototype = Map.prototype;

    /**
     * Helper: return an iterator over an array.
     * @param {!Array<*>} arr the array
     * @returns {!Object} an iterator
     * @inner
     */
    function arrayIterator(arr) {
      var idx = 0;
      return {
        next: function () {
          if (idx < arr.length)
            return { done: false, value: arr[idx++] };
          return { done: true };
        }
      }
    }

    /**
     * Clears the map.
     */
    MapPrototype.clear = function () {
      this.map = {};
    };

    /**
     * Deletes a particular key from the map.
     * @returns {boolean} Whether any entry with this key was deleted.
     */
    MapPrototype["delete"] = function (key) {
      var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
      var hadKey = keyValue in this.map;
      delete this.map[keyValue];
      return hadKey;
    };

    /**
     * Returns an iterator over [key, value] pairs in the map.
     * @returns {Object} The iterator
     */
    MapPrototype.entries = function () {
      var entries = [];
      var strKeys = Object.keys(this.map);
      for (var i = 0, entry; i < strKeys.length; i++)
        entries.push([(entry = this.map[strKeys[i]]).key, entry.value]);
      return arrayIterator(entries);
    };

    /**
     * Returns an iterator over keys in the map.
     * @returns {Object} The iterator
     */
    MapPrototype.keys = function () {
      var keys = [];
      var strKeys = Object.keys(this.map);
      for (var i = 0; i < strKeys.length; i++)
        keys.push(this.map[strKeys[i]].key);
      return arrayIterator(keys);
    };

    /**
     * Returns an iterator over values in the map.
     * @returns {!Object} The iterator
     */
    MapPrototype.values = function () {
      var values = [];
      var strKeys = Object.keys(this.map);
      for (var i = 0; i < strKeys.length; i++)
        values.push(this.map[strKeys[i]].value);
      return arrayIterator(values);
    };

    /**
     * Iterates over entries in the map, calling a function on each.
     * @param {function(this:*, *, *, *)} cb The callback to invoke with value, key, and map arguments.
     * @param {Object=} thisArg The `this` value for the callback
     */
    MapPrototype.forEach = function (cb, thisArg) {
      var strKeys = Object.keys(this.map);
      for (var i = 0, entry; i < strKeys.length; i++)
        cb.call(thisArg, (entry = this.map[strKeys[i]]).value, entry.key, this);
    };

    /**
     * Sets a key in the map to the given value.
     * @param {*} key The key
     * @param {*} value The value
     * @returns {!ProtoBuf.Map} The map instance
     */
    MapPrototype.set = function (key, value) {
      var keyValue = this.keyElem.verifyValue(key);
      var valValue = this.valueElem.verifyValue(value);
      this.map[this.keyElem.valueToString(keyValue)] = { key: keyValue, value: valValue };
      return this;
    };

    /**
     * Gets the value corresponding to a key in the map.
     * @param {*} key The key
     * @returns {*|undefined} The value, or `undefined` if key not present
     */
    MapPrototype.get = function (key) {
      var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
      if (!(keyValue in this.map))
        return undefined;
      return this.map[keyValue].value;
    };

    /**
     * Determines whether the given key is present in the map.
     * @param {*} key The key
     * @returns {boolean} `true` if the key is present
     */
    MapPrototype.has = function (key) {
      var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
      return (keyValue in this.map);
    };

    return Map;
  })(ProtoBuf, ProtoBuf.Reflect);

  /**
   * Loads a .proto string and returns the Builder.
   * @param {string} proto .proto file contents
   * @param {(ProtoBuf.Builder|string|{root: string, file: string})=} builder Builder to append to. Will create a new one if omitted.
   * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
   * @return {ProtoBuf.Builder} Builder to create new messages
   * @throws {Error} If the definition cannot be parsed or built
   * @expose
   */
  ProtoBuf.loadProto = function (proto, builder, filename) {
    if (typeof builder === 'string' || (builder && typeof builder["file"] === 'string' && typeof builder["root"] === 'string'))
      filename = builder,
      builder = undefined;
    return ProtoBuf.loadJson(ProtoBuf.DotProto.Parser.parse(proto), builder, filename);
  };

  /**
   * Loads a .proto string and returns the Builder. This is an alias of {@link ProtoBuf.loadProto}.
   * @function
   * @param {string} proto .proto file contents
   * @param {(ProtoBuf.Builder|string)=} builder Builder to append to. Will create a new one if omitted.
   * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
   * @return {ProtoBuf.Builder} Builder to create new messages
   * @throws {Error} If the definition cannot be parsed or built
   * @expose
   */
  ProtoBuf.protoFromString = ProtoBuf.loadProto; // Legacy

  /**
   * Loads a .proto file and returns the Builder.
   * @param {string|{root: string, file: string}} filename Path to proto file or an object specifying 'file' with
   *  an overridden 'root' path for all imported files.
   * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
   *  the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
   *  file will be read synchronously and this function will return the Builder.
   * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
   * @return {?ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
   *   request has failed), else undefined
   * @expose
   */
  ProtoBuf.loadProtoFile = function (filename, callback, builder) {
    if (callback && typeof callback === 'object')
      builder = callback,
      callback = null;
    else if (!callback || typeof callback !== 'function')
      callback = null;
    if (callback)
      return ProtoBuf.Util.fetch(typeof filename === 'string' ? filename : filename["root"] + "/" + filename["file"], function (contents) {
        if (contents === null) {
          callback(Error("Failed to fetch file"));
          return;
        }
        try {
          callback(null, ProtoBuf.loadProto(contents, builder, filename));
        } catch (e) {
          callback(e);
        }
      });
    var contents = ProtoBuf.Util.fetch(typeof filename === 'object' ? filename["root"] + "/" + filename["file"] : filename);
    return contents === null ? null : ProtoBuf.loadProto(contents, builder, filename);
  };

  /**
   * Loads a .proto file and returns the Builder. This is an alias of {@link ProtoBuf.loadProtoFile}.
   * @function
   * @param {string|{root: string, file: string}} filename Path to proto file or an object specifying 'file' with
   *  an overridden 'root' path for all imported files.
   * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
   *  the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
   *  file will be read synchronously and this function will return the Builder.
   * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
   * @return {!ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
   *   request has failed), else undefined
   * @expose
   */
  ProtoBuf.protoFromFile = ProtoBuf.loadProtoFile; // Legacy

  /**
   * Constructs a new empty Builder.
   * @param {Object.<string,*>=} options Builder options, defaults to global options set on ProtoBuf
   * @return {!ProtoBuf.Builder} Builder
   * @expose
   */
  ProtoBuf.newBuilder = function (options) {
    options = options || {};
    if (typeof options['convertFieldsToCamelCase'] === 'undefined')
      options['convertFieldsToCamelCase'] = ProtoBuf.convertFieldsToCamelCase;
    if (typeof options['populateAccessors'] === 'undefined')
      options['populateAccessors'] = ProtoBuf.populateAccessors;
    return new ProtoBuf.Builder(options);
  };

  /**
   * Loads a .json definition and returns the Builder.
   * @param {!*|string} json JSON definition
   * @param {(ProtoBuf.Builder|string|{root: string, file: string})=} builder Builder to append to. Will create a new one if omitted.
   * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
   * @return {ProtoBuf.Builder} Builder to create new messages
   * @throws {Error} If the definition cannot be parsed or built
   * @expose
   */
  ProtoBuf.loadJson = function (json, builder, filename) {
    if (typeof builder === 'string' || (builder && typeof builder["file"] === 'string' && typeof builder["root"] === 'string'))
      filename = builder,
      builder = null;
    if (!builder || typeof builder !== 'object')
      builder = ProtoBuf.newBuilder();
    if (typeof json === 'string')
      json = JSON.parse(json);
    builder["import"](json, filename);
    builder.resolveAll();
    return builder;
  };

  /**
   * Loads a .json file and returns the Builder.
   * @param {string|!{root: string, file: string}} filename Path to json file or an object specifying 'file' with
   *  an overridden 'root' path for all imported files.
   * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
   *  the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
   *  file will be read synchronously and this function will return the Builder.
   * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
   * @return {?ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
   *   request has failed), else undefined
   * @expose
   */
  ProtoBuf.loadJsonFile = function (filename, callback, builder) {
    if (callback && typeof callback === 'object')
      builder = callback,
      callback = null;
    else if (!callback || typeof callback !== 'function')
      callback = null;
    if (callback)
      return ProtoBuf.Util.fetch(typeof filename === 'string' ? filename : filename["root"] + "/" + filename["file"], function (contents) {
        if (contents === null) {
          callback(Error("Failed to fetch file"));
          return;
        }
        try {
          callback(null, ProtoBuf.loadJson(JSON.parse(contents), builder, filename));
        } catch (e) {
          callback(e);
        }
      });
    var contents = ProtoBuf.Util.fetch(typeof filename === 'object' ? filename["root"] + "/" + filename["file"] : filename);
    return contents === null ? null : ProtoBuf.loadJson(JSON.parse(contents), builder, filename);
  };

  return ProtoBuf;
});