All files / src/Ice InputStream.js

74.2% Statements 1165/1570
77.85% Branches 239/307
92.47% Functions 86/93
74.2% Lines 1165/1570

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 157141x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x             41x 41x 41x       41x 41x 41x 41x 202x 202x 202x 202x 202x 202x 202x 202x 202x 202x 41x 41x 4x 4x 41x 41x 41x 41x 561x 140x 140x 140x 561x 561x 561x 274x 274x     561x 287x 287x 287x 561x 561x 41x 41x 293x 293x 41x 41x 358x 358x 358x 358x 358x 358x 358x 358x 128x 128x 128x 230x 343x 74x 74x 74x 230x 230x 230x 230x 230x 230x 230x 343x 205x 205x 205x 205x 205x 205x 205x 230x 230x 230x 230x 230x 358x 41x 41x 267x 267x 267x 267x 267x 267x 267x 267x 267x 267x 267x 267x 200x 200x 200x 200x 200x 198x 198x 198x 198x 198x 198x 219x 219x 197x 197x 197x 197x 197x 197x 197x 200x 266x 267x 99x 267x 167x 39x 39x 39x 167x 167x 167x 39x 39x 39x 39x 39x 39x 39x 147x 147x 39x 39x 167x 267x 41x 41x 41x 41x 100x 100x 100x 41x 41x 403x 403x 403x 403x 403x     403x 403x 403x 60x 403x 343x 343x 403x 41x 41x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 35x 35x 35x 35x 35x 35x 32x 32x 6x 6x 32x 32x 32x 32x 3x 3x 3x 3x 3x 3x 3x 17x                   35x 32x 41x 41x 232x 232x 232x 41x 41x 232x 232x 232x 232x 200x 200x 200x     200x 200x 232x 232x 232x 232x 41x 41x 788x 788x 788x 788x 788x 232x 232x 232x 556x 556x 556x 556x 556x 556x 556x 741x 494x 494x 494x 788x 62x 62x 556x 556x 788x     788x 41x 41x 41x 41x 27x 27x 27x 27x 41x 41x 73x 73x 206x 206x 203x 203x 73x 69x 73x             73x 41x 41x 203x 203x 203x 203x     203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 227x 227x 227x 227x 227x 1x 1x 226x 226x 226x 226x 226x 226x 227x 202x 202x 24x 24x 24x 24x 24x 24x 24x 202x 202x 202x 202x 202x 202x 202x 203x 203x 200x 200x 221x 95x 95x 221x 200x 202x 203x 2x 2x 200x 200x 200x 200x 200x 203x 41x 41x 41x 41x 102x 102x 102x 102x 41x 41x 82x 82x   82x   82x                                 82x 82x 82x 82x 41x 41x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x                         35x 41x 41x 102x 102x 102x 102x 41x 41x 102x 102x       102x 102x 102x 41x 41x 215x 215x 215x 215x 215x 102x 102x 102x 113x 113x 113x 113x 113x 113x 113x 113x 196x 76x       76x 76x 76x 76x 67x 67x 67x 67x 76x 9x 9x 9x 9x 9x 9x 215x 37x 37x 37x 113x 113x 113x 113x 184x 37x 37x     215x 76x 76x 215x 41x 41x 113x 36x 36x 113x 113x 113x 113x 113x 113x                                                                             113x 41x 41x                                                                                                                                         41x 41x 475x   475x 362x 362x 113x 475x 41x 41x 82x 82x 82x 82x 82x 15x 15x 15x 15x 15x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x                                   67x 82x     67x 67x 67x 67x 67x 67x 67x 67x 82x             67x 67x 67x 67x 67x 67x 82x 41x 41x 102x 102x 102x 102x                                               102x 41x 41x 102x 102x 102x     102x 102x 102x 41x 41x 41x 41x 102x     102x 102x 102x 102x 102x 102x 102x 102x 102x 102x 102x 102x 102x 102x 102x 102x 41x 41x 41x             41x 41x 41x 41x 2202x 2202x 2202x 2202x 2202x 2202x 2202x 41x 41x 2206x 2206x 41x 41x 2208x 2208x 2208x 41x 41x 41x 41x 230x 230x 230x 41x 41x 219x 219x 41x 41x 316x 316x 41x 41x 41x 41x 8837x 8837x     8837x 8837x 8796x 8796x 8796x 8796x         8796x 8796x 8796x 6198x 8796x 2598x 2598x     8837x 41x 41x 41x 41x 82x 42x 1x         1x 42x         41x 41x     41x 41x     42x 41x 41x 41x     41x 41x     8837x 8837x 8837x 8837x 8837x 8837x 8837x 8837x 8837x 41x 41x 1277x 2x 2x 2x 2x 2x 2x 1277x 1277x 1277x 41x 41x 5873x 5873x 5873x 5873x 5873x 5873x 5873x 5873x 5873x 5873x 5873x 5873x 5873x 5873x 5873x 5873x 5873x 5873x 41x 41x 11746x 11746x 41x 41x 7305x 7305x 7305x 41x 41x 267x 267x 267x 41x 41x 267x 267x 267x 41x 41x 67x 67x 67x 41x 41x 67x 67x 67x 41x 41x 2202x 2202x 6x 6x 2202x 2196x 2196x 2202x 2202x 2202x 2202x 2202x 2202x 2202x 2202x 2202x 2202x 2202x 2202x     2202x     2202x 2202x 2202x 2202x 2202x 2202x 2202x 2202x 2202x 41x 41x 2198x 2198x 2198x 2038x 2038x     2198x                                   2198x 2198x 2198x 2198x 2198x 2198x 2198x 41x 41x 1509x 1509x     1509x     1509x 1509x 1509x 1509x 1509x 1509x 63x     1509x 1446x 1446x 1446x 1446x 1509x 1509x 41x 41x                                       41x 41x 893x 893x 41x 41x 1x 1x 1x 41x 41x 4902x 4902x     4902x 4902x 4902x 4902x 4902x     4902x 4902x 41x 41x 439x 439x 439x 41x 41x 439x 439x 439x 41x 41x       41x 41x 136x 134x 136x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 136x 41x 41x 25709x 25709x 25709x 100x 100x     100x 100x 25609x 25709x     25709x 41x 41x 5066x 5066x 5066x 4052x 4052x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 5066x 754x 754x 2730x 260x 260x 1014x 1014x 1014x 1014x 1014x 1014x 2730x     1014x 1014x 5066x 41x 41x 244x     244x 244x 244x     244x 41x 41x 836x 836x 479x 479x 357x 836x 41x 41x 299x 118x 299x 181x 181x 299x 41x 41x 126994x 126994x 126994x     126994x 41x 41x 146x 146x 41x 41x 2279x 2279x 2279x 1x 1x 2279x 41x 41x 2020x 2020x 2020x     2020x 41x 41x 49845x 49845x 49845x     49845x 41x 41x 684x 684x 684x     684x 41x 41x 637x 637x 637x     637x 41x 41x 650x 650x 650x     650x 41x 41x 15105x 15105x 4453x 4453x 10652x 10652x 10652x 15105x     10652x 10652x 10652x 15105x     15105x 41x 41x 537x 537x 537x 537x 537x 537x 41x 41x 27x 10x 10x 27x 17x 17x 27x 41x 41x 405x 405x 52x 42x 52x 4x 10x 6x 6x 405x 353x 353x 405x 405x 405x     405x 405x 41x 41x 27x 10x 27x 17x 17x 27x 41x 41x 485x 485x 474x 1x 1x 473x 485x 485x 41x 41x 67x 67x 67x 41x 41x 719x     719x 719x 719x 229x 229x 490x 490x 490x 718x 24x 24x 24x 466x 466x 466x 718x 7x 7x 466x 718x 132x 132x 132x 718x   334x 334x     334x 334x 719x 719x 41x 41x                                                                             41x 41x 2074x 2074x 2074x 2074x 2074x 2038x 2038x 36x 36x 2074x 2074x 36x 36x               2074x 41x 41x 149x     149x 149x 41x 41x 88x 88x 29x 29x 88x 41x 41x 3885x 3885x 41x 41x 719x 719x 41x 41x 552x 6x 6x 6x   6x 6x 6x 6x 6x 6x 552x 552x 202x 202x 100x 202x 102x 102x 202x 552x 41x 41x 27x               27x 41x 41x 16873x 16873x 41x 41x 26961x 26961x 41x 41x 11579x 11579x 41x 41x 2881x 2881x 41x 41x 15562x 15562x 41x  
// Copyright (c) ZeroC, Inc.
 
import { throwUOE } from "./ExUtil.js";
import { ArrayUtil } from "./ArrayUtil.js";
import { Buffer } from "./Buffer.js";
import { OptionalFormat } from "./OptionalFormat.js";
import { Encoding_1_0, Protocol } from "./Protocol.js";
import { SlicedData, SliceInfo, UnknownSlicedValue } from "./UnknownSlicedValue.js";
import { Value } from "./Value.js";
import { InitializationException, MarshalException } from "./LocalExceptions.js";
import { Ice as Ice_Identity } from "./Identity.js";
const { Identity } = Ice_Identity;
import { Ice as Ice_Version } from "./Version.js";
const { EncodingVersion } = Ice_Version;
import { Instance } from "./Instance.js";
import { Communicator } from "./Communicator.js";
import { ObjectPrx } from "./ObjectPrx.js";
import { SliceType } from "./SliceType.js";
 
const endOfBufferMessage = "Attempting to unmarshal past the end of the buffer.";
 
const slicingIds = new Map();
function traceSlicing(kind, typeId, slicingCat, logger) {
    if (!slicingIds.has(typeId)) {
        logger.trace(slicingCat, `unknown ${kind} type \`${typeId}'`);
        slicingIds.set(typeId, 1);
    }
}
 
class IndirectPatchEntry {
    constructor(index, cb) {
        this.index = index;
        this.cb = cb;
    }
}
 
class EncapsDecoder {
    constructor(stream, encaps, classGraphDepth) {
        this._stream = stream;
        this._encaps = encaps;
        this._classGraphDepthMax = classGraphDepth;
        this._classGraphDepth = 0;
        this._patchMap = null; // Lazy initialized, Map<int, Patcher[] >()
        this._unmarshaledMap = new Map(); // Map<int, Value>()
        this._typeIdMap = null; // Lazy initialized, Map<int, String>
        this._typeIdIndex = 0;
        this._valueList = null; // Lazy initialized. Value[]
    }
 
    readOptional() {
        return false;
    }
 
    readPendingValues() {}
 
    readTypeId(isIndex) {
        if (this._typeIdMap === null) {
            // Lazy initialization
            this._typeIdMap = new Map(); // Map<int, String>();
        }
 
        let typeId;
        if (isIndex) {
            typeId = this._typeIdMap.get(this._stream.readSize());
            if (typeId === undefined) {
                throw new MarshalException(endOfBufferMessage);
            }
        } else {
            typeId = this._stream.readString();
            this._typeIdMap.set(++this._typeIdIndex, typeId);
        }
        return typeId;
    }
 
    newInstance(typeId) {
        return this._stream.instance._initData.sliceLoader.newInstance(typeId);
    }
 
    addPatchEntry(index, cb) {
        console.assert(index > 0);
 
        //
        // Check if we have already unmarshaled the instance. If that's the case,
        // just call the callback and we're done.
        //
        const obj = this._unmarshaledMap.get(index);
        if (obj !== undefined && obj !== null) {
            cb(obj);
            return;
        }
 
        if (this._patchMap === null) {
            // Lazy initialization
            this._patchMap = new Map(); // Map<Integer, Patcher[] >();
        }
 
        //
        // Add a patch entry if the instance isn't unmarshaled yet,
        // the callback will be called when the instance is
        // unmarshaled.
        //
        let l = this._patchMap.get(index);
        if (l === undefined) {
            //
            // We have no outstanding instances to be patched for this
            // index, so make a new entry in the patch map.
            //
            l = []; // ReadValueCallback[]
            this._patchMap.set(index, l);
        }
 
        //
        // Append a patch entry for this instance.
        //
        l.push(new PatchEntry(cb, this._classGraphDepth));
    }
 
    unmarshal(index, v) {
        //
        // Add the instance to the map of unmarshaled instances, this must
        // be done before reading the instances (for circular references).
        //
        this._unmarshaledMap.set(index, v);
 
        //
        // Read the instance.
        //
        v._iceRead(this._stream);
 
        if (this._patchMap !== null) {
            //
            // Patch all instances now that the instance is unmarshaled.
            //
            const l = this._patchMap.get(index);
            if (l !== undefined) {
                console.assert(l.length > 0);
 
                //
                // Patch all pointers that refer to the instance.
                //
                for (let i = 0; i < l.length; ++i) {
                    l[i].cb(v);
                }
 
                //
                // Clear out the patch map for that index -- there is nothing left
                // to patch for that index for the time being.
                //
                this._patchMap.delete(index);
            }
        }
 
        if ((this._patchMap === null || this._patchMap.size === 0) && this._valueList === null) {
            v.ice_postUnmarshal();
        } else {
            if (this._valueList === null) {
                // Lazy initialization
                this._valueList = []; // Value[]
            }
            this._valueList.push(v);
 
            if (this._patchMap === null || this._patchMap.size === 0) {
                //
                // Iterate over the instance list and invoke ice_postUnmarshal on
                // each instance. We must do this after all instances have been
                // unmarshaled in order to ensure that any instance data members
                // have been properly patched.
                //
                for (let i = 0; i < this._valueList.length; i++) {
                    this._valueList[i].ice_postUnmarshal();
                }
                this._valueList = [];
            }
        }
    }
}
 
class EncapsDecoder10 extends EncapsDecoder {
    constructor(stream, encaps, classGraphDepth, f) {
        super(stream, encaps, classGraphDepth, f);
        this._sliceType = SliceType.NoSlice;
    }
 
    readValue(cb) {
        //
        // Instance references are encoded as a negative integer in 1.0.
        //
        let index = this._stream.readInt();
        if (index > 0) {
            throw new MarshalException("invalid object id");
        }
        index = -index;
 
        if (index === 0) {
            cb(null);
        } else {
            this.addPatchEntry(index, cb);
        }
    }
 
    throwException() {
        console.assert(this._sliceType === SliceType.NoSlice);
 
        //
        // User exceptions with the 1.0 encoding start with a boolean flag
        // that indicates whether or not the exception has classes.
        //
        // This allows reading the pending instances even if some part of
        // the exception was sliced.
        //
        const usesClasses = this._stream.readBool();
 
        this._sliceType = SliceType.ExceptionSlice;
        this._skipFirstSlice = false;
 
        //
        // Read the first slice header.
        //
        this.startSlice();
        const mostDerivedId = this._typeId;
        while (true) {
            const userEx = this._stream.instance._initData.sliceLoader.newInstance(this._typeId);
 
            //
            // We found the exception.
            //
            if (userEx !== null) {
                userEx._read(this._stream);
                if (usesClasses) {
                    this.readPendingValues();
                }
                throw userEx;
 
                // Never reached.
            }
 
            //
            // Slice off what we don't understand.
            //
            this.skipSlice();
            try {
                this.startSlice();
            } catch (ex) {
                //
                // An oversight in the 1.0 encoding means there is no marker to indicate
                // the last slice of an exception. As a result, we just try to read the
                // next type ID, which raises MarshalException when the input buffer underflow.
                if (ex instanceof MarshalException) {
                    throw new MarshalException(`unknown exception type '${mostDerivedId}'`);
                }
                throw ex;
            }
        }
    }
 
    startInstance(sliceType) {
        console.assert(this._sliceType === sliceType);
        this._skipFirstSlice = true;
    }
 
    endInstance() {
        //
        // Read the Ice::Object slice.
        //
        if (this._sliceType === SliceType.ValueSlice) {
            this.startSlice();
            const sz = this._stream.readSize(); // For compatibility with the old AFM.
            if (sz !== 0) {
                throw new MarshalException("invalid Object slice");
            }
            this.endSlice();
        }
 
        this._sliceType = SliceType.NoSlice;
        return null;
    }
 
    startSlice() {
        //
        // If first slice, don't read the header, it was already read in
        // readInstance or throwException to find the factory.
        //
        if (this._skipFirstSlice) {
            this._skipFirstSlice = false;
            return;
        }
 
        //
        // For instances, first read the type ID boolean which indicates
        // whether or not the type ID is encoded as a string or as an
        // index. For exceptions, the type ID is always encoded as a
        // string.
        //
        if (this._sliceType === SliceType.ValueSlice) {
            // For exceptions, the type ID is always encoded as a string
            const isIndex = this._stream.readBool();
            this._typeId = this.readTypeId(isIndex);
        } else {
            this._typeId = this._stream.readString();
        }
 
        this._sliceSize = this._stream.readInt();
        if (this._sliceSize < 4) {
            throw new MarshalException(endOfBufferMessage);
        }
    }
 
    endSlice() {}
 
    skipSlice() {
        this._stream.traceSkipSlice(this._typeId, this._sliceType);
        console.assert(this._sliceSize >= 4);
        this._stream.skip(this._sliceSize - 4);
    }
 
    readPendingValues() {
        let num;
        do {
            num = this._stream.readSize();
            for (let k = num; k > 0; --k) {
                this.readInstance();
            }
        } while (num > 0);
 
        if (this._patchMap !== null && this._patchMap.size !== 0) {
            //
            // If any entries remain in the patch map, the sender has sent an index for an instance, but failed
            // to supply the instance.
            //
            throw new MarshalException("index for class received, but no instance");
        }
    }
 
    readInstance() {
        const index = this._stream.readInt();
        let v = null;
 
        if (index <= 0) {
            throw new MarshalException("invalid object id");
        }
 
        this._sliceType = SliceType.ValueSlice;
        this._skipFirstSlice = false;
 
        //
        // Read the first slice header.
        //
        this.startSlice();
        const mostDerivedId = this._typeId;
        while (true) {
            //
            // For the 1.0 encoding, the type ID for the base Object class
            // marks the last slice.
            //
            if (this._typeId == Value.ice_staticId()) {
                throw new MarshalException(`The Slice loader cannot find a class for type ID '${mostDerivedId}'.`);
            }
 
            v = this.newInstance(this._typeId);
 
            //
            // We found a factory, we get out of this loop.
            //
            if (v) {
                break;
            }
 
            //
            // Slice off what we don't understand.
            //
            this.skipSlice();
            this.startSlice(); // Read next Slice header for next iteration.
        }
 
        //
        // Compute the biggest class graph depth of this object. To compute this,
        // we get the class graph depth of each ancestor from the patch map and
        // keep the biggest one.
        //
        this._classGraphDepth = 0;
        const l = this._patchMap === null ? null : this._patchMap.get(index);
        if (l !== undefined) {
            console.assert(l.length > 0);
            for (const entry of l) {
                if (entry.classGraphDepth > this._classGraphDepth) {
                    this._classGraphDepth = entry.classGraphDepth;
                }
            }
        }
 
        if (++this._classGraphDepth > this._classGraphDepthMax) {
            throw new MarshalException("maximum class graph depth reached");
        }
 
        //
        // Unmarshal the instance and add it to the map of unmarshaled instances.
        //
        this.unmarshal(index, v);
    }
}
 
class EncapsDecoder11 extends EncapsDecoder {
    constructor(stream, encaps, classGraphDepth, f) {
        super(stream, encaps, classGraphDepth, f);
        this._current = null;
        this._valueIdIndex = 1;
    }
 
    readValue(cb) {
        const index = this._stream.readSize();
        if (index < 0) {
            throw new MarshalException("invalid object id");
        } else if (index === 0) {
            cb(null);
        } else if (this._current !== null && (this._current.sliceFlags & Protocol.FLAG_HAS_INDIRECTION_TABLE) !== 0) {
            //
            // When reading an instance within a slice and there's an
            // indirect instance table, always read an indirect reference
            // that points to an instance from the indirect instance table
            // marshaled at the end of the Slice.
            //
            // Maintain a list of indirect references. Note that the
            // indirect index starts at 1, so we decrement it by one to
            // derive an index into the indirection table that we'll read
            // at the end of the slice.
            //
            if (this._current.indirectPatchList === null) {
                // Lazy initialization
                this._current.indirectPatchList = []; // IndirectPatchEntry[]
            }
            this._current.indirectPatchList.push(new IndirectPatchEntry(index - 1, cb));
        } else {
            this.readInstance(index, cb);
        }
    }
 
    throwException() {
        console.assert(this._current === null);
 
        this.push(SliceType.ExceptionSlice);
 
        //
        // Read the first slice header.
        //
        this.startSlice();
        const mostDerivedId = this._current.typeId;
        while (true) {
            const userEx = this._stream.instance._initData.sliceLoader.newInstance(this._current.typeId);
 
            //
            // We found the exception.
            //
            if (userEx !== null) {
                userEx._read(this._stream);
                throw userEx;
 
                // Never reached.
            }

            //
            // Slice off what we don't understand.
            //
            this.skipSlice();

            if ((this._current.sliceFlags & Protocol.FLAG_IS_LAST_SLICE) !== 0) {
                throw new MarshalException(`cannot unmarshal user exception with type ID '${mostDerivedId}'`);
            }

            this.startSlice();
        }
    }
 
    startInstance(sliceType) {
        console.assert(sliceType !== undefined);
        console.assert(this._current.sliceType !== null && this._current.sliceType === sliceType);
        this._current.skipFirstSlice = true;
    }
 
    endInstance() {
        let slicedData = this.readSlicedData();
        if (this._current.slices !== null) {
            this._current.slices.length = 0; // Clear the array.
            this._current.indirectionTables.length = 0; // Clear the array.
        }
        this._current = this._current.previous;
        return slicedData;
    }
 
    startSlice() {
        //
        // If first slice, don't read the header, it was already read in
        // readInstance or throwException to find the factory.
        //
        if (this._current.skipFirstSlice) {
            this._current.skipFirstSlice = false;
            return;
        }
 
        this._current.sliceFlags = this._stream.readByte();
 
        //
        // Read the type ID, for instance slices the type ID is encoded as a
        // string or as an index, for exceptions it's always encoded as a
        // string.
        //
        if (this._current.sliceType === SliceType.ValueSlice) {
            if ((this._current.sliceFlags & Protocol.FLAG_HAS_TYPE_ID_COMPACT) === Protocol.FLAG_HAS_TYPE_ID_COMPACT) {
                // Must be checked 1st!
                this._current.compactId = this._stream.readSize();
                this._current.typeId = this._current.compactId.toString();
            } else if (
                (this._current.sliceFlags & (Protocol.FLAG_HAS_TYPE_ID_INDEX | Protocol.FLAG_HAS_TYPE_ID_STRING)) !==
                0
            ) {
                this._current.typeId = this.readTypeId(
                    (this._current.sliceFlags & Protocol.FLAG_HAS_TYPE_ID_INDEX) !== 0,
                );
                this._current.compactId = -1;
            } else {
                //
                // Only the most derived slice encodes the type ID for the compact format.
                //
                this._current.typeId = "";
                this._current.compactId = -1;
            }
        } else {
            this._current.typeId = this._stream.readString();
            this._current.compactId = -1;
        }
 
        //
        // Read the slice size if necessary.
        //
        if ((this._current.sliceFlags & Protocol.FLAG_HAS_SLICE_SIZE) !== 0) {
            this._current.sliceSize = this._stream.readInt();
            if (this._current.sliceSize < 4) {
                throw new MarshalException(endOfBufferMessage);
            }
        } else {
            this._current.sliceSize = 0;
        }
    }
 
    endSlice() {
        if ((this._current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) !== 0) {
            this._stream.skipOptionals();
        }
 
        //
        // Read the indirection table if one is present and transform the
        // indirect patch list into patch entries with direct references.
        //
        if ((this._current.sliceFlags & Protocol.FLAG_HAS_INDIRECTION_TABLE) !== 0) {
            const indirectionTable = [];
            //
            // The table is written as a sequence<size> to conserve space.
            //
            const length = this._stream.readAndCheckSeqSize(1);
            for (let i = 0; i < length; ++i) {
                indirectionTable[i] = this.readInstance(this._stream.readSize(), null);
            }

            //
            // Sanity checks. If there are optional members, it's possible
            // that not all instance references were read if they are from
            // unknown optional data members.
            //
            if (indirectionTable.length === 0) {
                throw new MarshalException("empty indirection table");
            }
            if (
                (this._current.indirectPatchList === null || this._current.indirectPatchList.length === 0) &&
                (this._current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) === 0
            ) {
                throw new MarshalException("no references to indirection table");
            }

            //
            // Convert indirect references into direct references.
            //
            if (this._current.indirectPatchList !== null) {
                this._current.indirectPatchList.forEach(e => {
                    console.assert(e.index >= 0);
                    if (e.index >= indirectionTable.length) {
                        throw new MarshalException("indirection out of range");
                    }
                    this.addPatchEntry(indirectionTable[e.index], e.cb);
                });
                this._current.indirectPatchList.length = 0;
            }
        }
    }
 
    skipSlice() {
        this._stream.traceSkipSlice(this._current.typeId, this._current.sliceType);

        const start = this._stream.pos;

        if ((this._current.sliceFlags & Protocol.FLAG_HAS_SLICE_SIZE) !== 0) {
            console.assert(this._current.sliceSize >= 4);
            this._stream.skip(this._current.sliceSize - 4);
        } else {
            if (this._current.sliceType == SliceType.ValueSlice) {
                throw new MarshalException(
                    `The Slice loader cannot find a class for type ID '${this._current.typeId}' and compact format prevents slicing.`,
                );
            } else {
                throw new MarshalException(
                    `The Slice loader cannot find a user exception class for type ID '${this._current.typeId}' and compact format prevents slicing.`,
                );
            }
        }

        //
        // Preserve this slice.
        //
        const info = new SliceInfo();
        info.typeId = this._current.typeId;
        info.compactId = this._current.compactId;
        info.hasOptionalMembers = (this._current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) !== 0;
        info.isLastSlice = (this._current.sliceFlags & Protocol.FLAG_IS_LAST_SLICE) !== 0;

        const b = this._stream._buf;
        const end = b.position;
        let dataEnd = end;
        if (info.hasOptionalMembers) {
            //
            // Don't include the optional member end marker. It will be re-written by
            // endSlice when the sliced data is re-written.
            //
            --dataEnd;
        }

        b.position = start;
        info.bytes = b.getArray(dataEnd - start);
        b.position = end;

        if (this._current.slices === null) {
            // Lazy initialization
            this._current.slices = []; // Ice.SliceInfo[]
            this._current.indirectionTables = []; // int[]
        }

        //
        // Read the indirect instance table. We read the instances or their
        // IDs if the instance is a reference to an already unmarshaled
        // instance.
        //

        if ((this._current.sliceFlags & Protocol.FLAG_HAS_INDIRECTION_TABLE) !== 0) {
            const length = this._stream.readAndCheckSeqSize(1);
            const indirectionTable = [];
            for (let i = 0; i < length; ++i) {
                indirectionTable[i] = this.readInstance(this._stream.readSize(), null);
            }
            this._current.indirectionTables.push(indirectionTable);
        } else {
            this._current.indirectionTables.push(null);
        }

        this._current.slices.push(info);
    }
 
    readOptional(readTag, expectedFormat) {
        if (this._current === null) {
            return this._stream.readOptImpl(readTag, expectedFormat);
        } else if ((this._current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) !== 0) {
            return this._stream.readOptImpl(readTag, expectedFormat);
        }
        return false;
    }
 
    readInstance(index, cb) {
        console.assert(index > 0);
 
        let v = null;
 
        if (index > 1) {
            if (cb !== null) {
                this.addPatchEntry(index, cb);
            }
            return index;
        }
 
        this.push(SliceType.ValueSlice);
 
        //
        // Get the instance ID before we start reading slices. If some
        // slices are skipped, the indirect instance table is still read and
        // might read other instances.
        //
        index = ++this._valueIdIndex;
 
        //
        // Read the first slice header.
        //
        this.startSlice();
        const mostDerivedId = this._current.typeId;
        while (true) {
            if (this._current.typeId.length > 0) {
                v = this.newInstance(this._current.typeId);
            }
 
            if (v !== null && v !== undefined) {
                //
                // We have an instance, we get out of this loop.
                //
                break;
            }

            //
            // Slice off what we don't understand.
            //
            this.skipSlice();

            //
            // If this is the last slice, keep the instance as an opaque
            // UnknownSlicedValue object.
            //
            if ((this._current.sliceFlags & Protocol.FLAG_IS_LAST_SLICE) !== 0) {
                v = new UnknownSlicedValue(mostDerivedId);
                break;
            }

            this.startSlice(); // Read next Slice header for next iteration.
        }
 
        if (++this._classGraphDepth > this._classGraphDepthMax) {
            throw new MarshalException("maximum class graph depth reached");
        }
 
        //
        // Unmarshal the instance.
        //
        this.unmarshal(index, v);
 
        --this._classGraphDepth;
 
        if (this._current === null && this._patchMap !== null && this._patchMap.size !== 0) {
            //
            // If any entries remain in the patch map, the sender has sent an index for an instance, but failed
            // to supply the instance.
            //
            throw new MarshalException("index for class received, but no instance");
        }
 
        if (cb !== null) {
            cb(v);
        }
 
        return index;
    }
 
    readSlicedData() {
        if (this._current.slices === null) {
            // No preserved slices.
            return null;
        }

        //
        // The _indirectionTables member holds the indirection table for each slice
        // in _slices.
        //
        console.assert(this._current.slices.length === this._current.indirectionTables.length);
        for (let i = 0; i < this._current.slices.length; ++i) {
            //
            // We use the "instances" list in SliceInfo to hold references
            // to the target instances. Note that the instances might not have
            // been read yet in the case of a circular reference to an
            // enclosing instance.
            //
            const table = this._current.indirectionTables[i];
            const info = this._current.slices[i];
            info.instances = [];
            if (table) {
                for (let j = 0; j < table.length; ++j) {
                    this.addPatchEntry(table[j], sequencePatcher(info.instances, j, Value));
                }
            }
        }
        return new SlicedData(ArrayUtil.clone(this._current.slices));
    }
 
    push(sliceType) {
        if (this._current === null) {
            this._current = new EncapsDecoder11.InstanceData(null);
        } else {
            this._current = !this._current.next ? new EncapsDecoder11.InstanceData(this._current) : this._current.next;
        }
        this._current.sliceType = sliceType;
        this._current.skipFirstSlice = false;
    }
}
 
EncapsDecoder11.InstanceData = class {
    constructor(previous) {
        if (previous !== null) {
            previous.next = this;
        }
        this.previous = previous;
        this.next = null;
 
        // Instance attributes
        this.sliceType = null;
        this.skipFirstSlice = false;
        this.slices = null; // Preserved slices. Ice.SliceInfo[]
        this.indirectionTables = null; // int[][]
 
        // Slice attributes
        this.sliceFlags = 0;
        this.sliceSize = 0;
        this.typeId = null;
        this.compactId = -1;
        this.indirectPatchList = null; // Lazy initialized, IndirectPatchEntry[]
    }
};
 
const sequencePatcher = function (seq, index, T) {
    return v => {
        if (v !== null && !(v instanceof T)) {
            throwUOE(T.ice_staticId(), v);
        }
        seq[index] = v;
    };
};
 
class ReadEncaps {
    constructor() {
        this.start = 0;
        this.sz = 0;
        this.encoding = null;
        this.encoding_1_0 = false;
        this.decoder = null;
        this.next = null;
    }
 
    reset() {
        this.decoder = null;
    }
 
    setEncoding(encoding) {
        this.encoding = encoding;
        this.encoding_1_0 = encoding.equals(Encoding_1_0);
    }
}
 
class PatchEntry {
    constructor(cb, classGraphDepth) {
        this._cb = cb;
        this._classGraphDepth = classGraphDepth;
    }
 
    get cb() {
        return this._cb;
    }
 
    get classGraphDepth() {
        return this._classGraphDepth;
    }
}
 
export class InputStream {
    constructor(arg1, arg2, arg3) {
        // The first argument must be a Communicator or an Instance.
        if (arg1 === null || arg1 === undefined) {
            throw new InitializationException("missing argument(s) for InputStream constructor");
        }
 
        if (arg1.constructor === Instance) {
            // (instance, encoding) or (instance, encoding, buffer)
 
            this._instance = arg1;
            if (arg2 === null || arg2 === undefined || arg2.constructor !== EncodingVersion) {
                throw new InitializationException(
                    "expected the encoding version as the second argument to the InputStream constructor",
                );
            }
            this._encoding = arg2;
 
            if (arg3 === undefined || arg3 === null) {
                this._buf = new Buffer();
            } else if (arg3.constructor === Buffer) {
                this._buf = arg3;
            } else {
                throw new InitializationException("unknown third argument to InputStream constructor");
            }
        } else if (arg1.constructor === Communicator) {
            // (communicator, encoding, buffer) or (communicator, buffer), with two flavors for buffer
            this._instance = arg1.instance;
 
            [arg2, arg3].forEach(arg => {
                if (arg !== null && arg !== undefined) {
                    if (arg.constructor === EncodingVersion) {
                        if (this._encoding !== undefined) {
                            throw new InitializationException(
                                "expected buffer as the third argument to InputStream constructor",
                            );
                        }
                        this._encoding = arg;
                    } else if (arg.constructor === ArrayBuffer) {
                        if (this._buf !== undefined) {
                            throw new InitializationException("duplicate buffer argument to InputStream constructor");
                        }
                        this._buf = new Buffer(arg.bytes);
                    } else if (arg.constructor === Uint8Array) {
                        if (this._buf !== undefined) {
                            throw new InitializationException("duplicate buffer argument to InputStream constructor");
                        }
                        this._buf = new Buffer(arg.buffer);
                    } else {
                        throw new InitializationException("unknown argument to InputStream constructor");
                    }
                }
            });
 
            if (this._buf === undefined) {
                throw new InitializationException("missing buffer argument to InputStream constructor");
            }
            this._encoding ??= this._instance.defaultsAndOverrides().defaultEncoding;
        } else {
            throw new InitializationException("unknown first argument to InputStream constructor");
        }
 
        this._encapsStack = null;
        this._encapsCache = null;
        this._closure = null;
        this._startSeq = -1;
        this._sizePos = -1;
 
        this._classGraphDepthMax = this._instance.classGraphDepthMax();
    }
 
    clear() {
        if (this._encapsStack !== null) {
            console.assert(this._encapsStack.next === null);
            this._encapsStack.next = this._encapsCache;
            this._encapsCache = this._encapsStack;
            this._encapsCache.reset();
            this._encapsStack = null;
        }
 
        this._startSeq = -1;
    }
 
    swap(other) {
        console.assert(this._instance === other._instance);
 
        // These are cached values derived from instance.
        console.assert(this._classGraphDepthMax === other._classGraphDepthMax);
 
        [other._buf, this._buf] = [this._buf, other._buf];
        [other._encoding, this._encoding] = [this._encoding, other._encoding];
 
        [other._startSeq, this._startSeq] = [this._startSeq, other._startSeq];
        [other._minSeqSize, this._minSeqSize] = [this._minSeqSize, other._minSeqSize];
        [other._sizePos, this._sizePos] = [this._sizePos, other._sizePos];
 
        // Swap is never called for InputStreams that have encapsulations being read/write. However,
        // encapsulations might still be set in case marshaling or unmarshaling failed. We just
        // reset the encapsulations if there are still some set.
        this.resetEncapsulation();
        other.resetEncapsulation();
    }
 
    resetEncapsulation() {
        this._encapsStack = null;
    }
 
    resize(sz) {
        this._buf.resize(sz);
        this._buf.position = sz;
    }
 
    startValue() {
        console.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
        this._encapsStack.decoder.startInstance(SliceType.ValueSlice);
    }
 
    endValue() {
        console.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
        return this._encapsStack.decoder.endInstance();
    }
 
    startException() {
        console.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
        this._encapsStack.decoder.startInstance(SliceType.ExceptionSlice);
    }
 
    endException() {
        console.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
        return this._encapsStack.decoder.endInstance();
    }
 
    startEncapsulation() {
        let curr = this._encapsCache;
        if (curr !== null) {
            curr.reset();
            this._encapsCache = this._encapsCache.next;
        } else {
            curr = new ReadEncaps();
        }
        curr.next = this._encapsStack;
        this._encapsStack = curr;
 
        this._encapsStack.start = this._buf.position;
 
        //
        // I don't use readSize() for encapsulations, because when creating an encapsulation,
        // I must know in advance how many bytes the size information will require in the data
        // stream. If I use an Int, it is always 4 bytes. For readSize(), it could be 1 or 5 bytes.
        //
        const sz = this.readInt();
        if (sz < 6) {
            throw new MarshalException(endOfBufferMessage);
        }
        if (sz - 4 > this._buf.remaining) {
            throw new MarshalException(endOfBufferMessage);
        }
        this._encapsStack.sz = sz;
 
        const encoding = new EncodingVersion();
        encoding._read(this);
        Protocol.checkSupportedEncoding(encoding); // Make sure the encoding is supported.
        this._encapsStack.setEncoding(encoding);
 
        return encoding;
    }
 
    endEncapsulation() {
        console.assert(this._encapsStack !== null);
 
        if (!this._encapsStack.encoding_1_0) {
            this.skipOptionals();
            if (this._buf.position !== this._encapsStack.start + this._encapsStack.sz) {
                throw new MarshalException("Failed to unmarshal encapsulation.");
            }
        } else if (this._buf.position !== this._encapsStack.start + this._encapsStack.sz) {
            if (this._buf.position + 1 !== this._encapsStack.start + this._encapsStack.sz) {
                throw new MarshalException("Failed to unmarshal encapsulation.");
            }

            //
            // Ice version < 3.3 had a bug where user exceptions with
            // class members could be encoded with a trailing byte
            // when dispatched with AMD. So we tolerate an extra byte
            // in the encapsulation.
            //

            try {
                this._buf.get();
            } catch {
                throw new MarshalException(endOfBufferMessage);
            }
        }
 
        const curr = this._encapsStack;
        this._encapsStack = curr.next;
        curr.next = this._encapsCache;
        this._encapsCache = curr;
        this._encapsCache.reset();
    }
 
    skipEmptyEncapsulation() {
        const sz = this.readInt();
        if (sz < 6) {
            throw new MarshalException(`${sz} is not a valid encapsulation size.`);
        }
        if (sz - 4 > this._buf.remaining) {
            throw new MarshalException(endOfBufferMessage);
        }
 
        const encoding = new EncodingVersion();
        encoding._read(this);
        Protocol.checkSupportedEncoding(encoding); // Make sure the encoding is supported.
 
        if (encoding.equals(Encoding_1_0)) {
            if (sz != 6) {
                throw new MarshalException(`${sz} is not a valid encapsulation size for a 1.0 empty encapsulation.`);
            }
        } else {
            // Skip the optional content of the encapsulation if we are expecting an
            // empty encapsulation.
            this._buf.position = this._buf.position + sz - 6;
        }
        return encoding;
    }
 
    readEncapsulation() {
        const sz = this.readInt();
        if (sz < 6) {
            throw new MarshalException(endOfBufferMessage);
        }

        if (sz - 4 > this._buf.remaining) {
            throw new MarshalException(endOfBufferMessage);
        }

        const encoding = new EncodingVersion();
        encoding._read(this);
        this._buf.position = this._buf.position - 6;

        try {
            return [encoding, this._buf.getArray(sz)];
        } catch {
            throw new MarshalException(endOfBufferMessage);
        }
    }
 
    getEncoding() {
        return this._encapsStack !== null ? this._encapsStack.encoding : this._encoding;
    }
 
    getEncapsulationSize() {
        console.assert(this._encapsStack !== null);
        return this._encapsStack.sz - 6;
    }
 
    skipEncapsulation() {
        const sz = this.readInt();
        if (sz < 6) {
            throw new MarshalException(endOfBufferMessage);
        }
        const encoding = new EncodingVersion();
        encoding._read(this);
        try {
            this._buf.position = this._buf.position + sz - 6;
        } catch {
            throw new MarshalException(endOfBufferMessage);
        }
        return encoding;
    }
 
    startSlice() {
        console.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
        this._encapsStack.decoder.startSlice();
    }
 
    endSlice() {
        console.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
        this._encapsStack.decoder.endSlice();
    }
 
    skipSlice() {
        console.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
        this._encapsStack.decoder.skipSlice();
    }
 
    readPendingValues() {
        if (this._encapsStack !== null && this._encapsStack.decoder !== null) {
            this._encapsStack.decoder.readPendingValues();
        } else if (
            (this._encapsStack !== null && this._encapsStack.encoding_1_0) ||
            (this._encapsStack === null && this._encoding.equals(Encoding_1_0))
        ) {
            //
            // If using the 1.0 encoding and no instances were read, we
            // still read an empty sequence of pending instances if
            // requested (i.e.: if this is called).
            //
            // This is required by the 1.0 encoding, even if no instances
            // are written we do marshal an empty sequence if marshaled
            // data types use classes.
            //
            this.skipSize();
        }
    }
 
    readSize() {
        try {
            const b = this._buf.get();
            if (b === 255) {
                const v = this._buf.getInt();
                if (v < 0) {
                    throw new MarshalException(endOfBufferMessage);
                }
                return v;
            }
            return b;
        } catch {
            throw new MarshalException(endOfBufferMessage);
        }
    }
 
    readAndCheckSeqSize(minSize) {
        const sz = this.readSize();
 
        if (sz === 0) {
            return sz;
        }
 
        //
        // The _startSeq variable points to the start of the sequence for which
        // we expect to read at least _minSeqSize bytes from the stream.
        //
        // If not initialized or if we already read more data than _minSeqSize,
        // we reset _startSeq and _minSeqSize for this sequence (possibly a
        // top-level sequence or enclosed sequence it doesn't really matter).
        //
        // Otherwise, we are reading an enclosed sequence and we have to bump
        // _minSeqSize by the minimum size that this sequence will require on
        // the stream.
        //
        // The goal of this check is to ensure that when we start unmarshaling
        // a new sequence, we check the minimal size of this new sequence against
        // the estimated remaining buffer size. This estimation is based on
        // the minimum size of the enclosing sequences, it's _minSeqSize.
        //
        if (this._startSeq === -1 || this._buf.position > this._startSeq + this._minSeqSize) {
            this._startSeq = this._buf.position;
            this._minSeqSize = sz * minSize;
        } else {
            this._minSeqSize += sz * minSize;
        }
 
        //
        // If there isn't enough data to read on the stream for the sequence (and
        // possibly enclosed sequences), something is wrong with the marshaled
        // data: it's claiming having more data that what is possible to read.
        //
        if (this._startSeq + this._minSeqSize > this._buf.limit) {
            throw new MarshalException(endOfBufferMessage);
        }
 
        return sz;
    }
 
    readBlob(sz) {
        if (this._buf.remaining < sz) {
            throw new MarshalException(endOfBufferMessage);
        }
        try {
            return this._buf.getArray(sz);
        } catch {
            throw new MarshalException(endOfBufferMessage);
        }
    }
 
    readOptional(tag, expectedFormat) {
        console.assert(this._encapsStack !== null);
        if (this._encapsStack.decoder !== null) {
            return this._encapsStack.decoder.readOptional(tag, expectedFormat);
        }
        return this.readOptImpl(tag, expectedFormat);
    }
 
    readOptionalHelper(tag, format, read) {
        if (this.readOptional(tag, format)) {
            return read.call(this);
        } else {
            return undefined;
        }
    }
 
    readByte() {
        try {
            return this._buf.get();
        } catch {
            throw new MarshalException(endOfBufferMessage);
        }
    }
 
    readByteSeq() {
        return this._buf.getArray(this.readAndCheckSeqSize(1));
    }
 
    readBool() {
        try {
            return this._buf.get() === 1;
        } catch {
            throw new MarshalException(endOfBufferMessage);
        }
    }
 
    readShort() {
        try {
            return this._buf.getShort();
        } catch {
            throw new MarshalException(endOfBufferMessage);
        }
    }
 
    readInt() {
        try {
            return this._buf.getInt();
        } catch {
            throw new MarshalException(endOfBufferMessage);
        }
    }
 
    readLong() {
        try {
            return this._buf.getLong();
        } catch {
            throw new MarshalException(endOfBufferMessage);
        }
    }
 
    readFloat() {
        try {
            return this._buf.getFloat();
        } catch {
            throw new MarshalException(endOfBufferMessage);
        }
    }
 
    readDouble() {
        try {
            return this._buf.getDouble();
        } catch {
            throw new MarshalException(endOfBufferMessage);
        }
    }
 
    readString() {
        const len = this.readSize();
        if (len === 0) {
            return "";
        }
        //
        // Check the buffer has enough bytes to read.
        //
        if (this._buf.remaining < len) {
            throw new MarshalException(endOfBufferMessage);
        }
 
        try {
            return this._buf.getString(len);
        } catch {
            throw new MarshalException(endOfBufferMessage);
        }
    }
 
    readProxy(type) {
        const ident = new Identity();
        ident._read(this);
        const reference = this._instance.referenceFactory().createFromStream(ident, this);
        const TPrx = type == null ? ObjectPrx : type;
        return reference == null ? null : new TPrx(reference);
    }
 
    readOptionalProxy(tag, type) {
        if (this.readOptional(tag, OptionalFormat.FSize)) {
            this.skip(4);
            return this.readProxy(type);
        } else {
            return undefined;
        }
    }
 
    readEnum(T) {
        let v;
        if (this.getEncoding().equals(Encoding_1_0)) {
            if (T.maxValue < 127) {
                v = this.readByte();
            } else if (T.maxValue < 32767) {
                v = this.readShort();
            } else {
                v = this.readInt();
            }
        } else {
            v = this.readSize();
        }
 
        const e = T.valueOf(v);
        if (e === undefined) {
            throw new MarshalException(`enumerator value '${v}' is out of range`);
        }
        return e;
    }
 
    readOptionalEnum(tag, T) {
        if (this.readOptional(tag, OptionalFormat.Size)) {
            return this.readEnum(T);
        } else {
            return undefined;
        }
    }
 
    readValue(cb, T) {
        this.initEncaps();
        this._encapsStack.decoder.readValue(obj => {
            if (obj !== null && !(obj instanceof T)) {
                throwUOE(T.ice_staticId(), obj);
            }
            cb(obj);
        });
    }
 
    throwException() {
        this.initEncaps();
        this._encapsStack.decoder.throwException();
    }
 
    readOptImpl(readTag, expectedFormat) {
        if (this.isEncoding_1_0()) {
            return false; // Optional members aren't supported with the 1.0 encoding.
        }
 
        while (true) {
            if (this._buf.position >= this._encapsStack.start + this._encapsStack.sz) {
                return false; // End of encapsulation also indicates end of optionals.
            }
 
            const v = this.readByte();
 
            if (v === Protocol.OPTIONAL_END_MARKER) {
                this._buf.position -= 1; // Rewind.
                return false;
            }
 
            const format = OptionalFormat.valueOf(v & 0x07); // First 3 bits.
            let tag = v >> 3;
            if (tag === 30) {
                tag = this.readSize();
            }
 
            if (tag > readTag) {
                const offset = tag < 30 ? 1 : tag < 255 ? 2 : 6; // Rewind
                this._buf.position -= offset;
                return false; // No optional data members with the requested tag.
            } else if (tag < readTag) {
                this.skipOptional(format); // Skip optional data members
            } else {
                if (format !== expectedFormat) {
                    throw new MarshalException(`invalid optional data member '${tag}': unexpected format`);
                }
                return true;
            }
        }
    }
 
    skipOptional(format) {
        switch (format) {
            case OptionalFormat.F1: {
                this.skip(1);
                break;
            }
            case OptionalFormat.F2: {
                this.skip(2);
                break;
            }
            case OptionalFormat.F4: {
                this.skip(4);
                break;
            }
            case OptionalFormat.F8: {
                this.skip(8);
                break;
            }
            case OptionalFormat.Size: {
                this.skipSize();
                break;
            }
            case OptionalFormat.VSize: {
                this.skip(this.readSize());
                break;
            }
            case OptionalFormat.FSize: {
                this.skip(this.readInt());
                break;
            }
            case OptionalFormat.Class: {
                throw new MarshalException("cannot skip an optional class");
            }
            default: {
                console.assert(false);
                break;
            }
        }
    }
 
    skipOptionals() {
        //
        // Skip remaining un-read optional members.
        //
        while (true) {
            if (this._buf.position >= this._encapsStack.start + this._encapsStack.sz) {
                return; // End of encapsulation also indicates end of optionals.
            }
 
            const b = this.readByte();
            const v = b < 0 ? b + 256 : b;
            if (v === Protocol.OPTIONAL_END_MARKER) {
                return;
            }

            const format = OptionalFormat.valueOf(v & 0x07); // Read first 3 bits.
            if (v >> 3 === 30) {
                this.skipSize();
            }
            this.skipOptional(format);
        }
    }
 
    skip(size) {
        if (size > this._buf.remaining) {
            throw new MarshalException(endOfBufferMessage);
        }
        this._buf.position += size;
    }
 
    skipSize() {
        const b = this.readByte();
        if (b === 255) {
            this.skip(4);
        }
    }
 
    isEmpty() {
        return this._buf.empty();
    }
 
    isEncoding_1_0() {
        return this._encapsStack !== null ? this._encapsStack.encoding_1_0 : this._encoding.equals(Encoding_1_0);
    }
 
    initEncaps() {
        if (this._encapsStack === null) {
            // Lazy initialization
            this._encapsStack = this._encapsCache;
            if (this._encapsStack !== null) {
                this._encapsCache = this._encapsCache.next;
            } else {
                this._encapsStack = new ReadEncaps();
            }
            this._encapsStack.setEncoding(this._encoding);
            this._encapsStack.sz = this._buf.limit;
        }
 
        if (this._encapsStack.decoder === null) {
            // Lazy initialization.
            if (this._encapsStack.encoding_1_0) {
                this._encapsStack.decoder = new EncapsDecoder10(this, this._encapsStack, this._classGraphDepthMax);
            } else {
                this._encapsStack.decoder = new EncapsDecoder11(this, this._encapsStack, this._classGraphDepthMax);
            }
        }
    }
 
    traceSkipSlice(typeId, sliceType) {
        if (this._instance.traceLevels().slicing > 0) {
            traceSlicing(
                sliceType === SliceType.ExceptionSlice ? "exception" : "object",
                typeId,
                "Slicing",
                this._instance.initializationData().logger,
            );
        }
    }
 
    get pos() {
        return this._buf.position;
    }
 
    set pos(value) {
        this._buf.position = value;
    }
 
    get size() {
        return this._buf.limit;
    }
 
    get instance() {
        return this._instance;
    }
 
    get buffer() {
        return this._buf;
    }
}