summaryrefslogtreecommitdiff
path: root/src/main/java/com/amazon/carbonado/raw/GenericEncodingStrategy.java
blob: c22881eb9a3e9347d901f2f26c3c6859d185e8eb (plain)
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
/*
 * Copyright 2006 Amazon Technologies, Inc. or its affiliates.
 * Amazon, Amazon.com and Carbonado are trademarks or registered trademarks
 * of Amazon Technologies, Inc. or its affiliates.  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.
 */

package com.amazon.carbonado.raw;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;

import org.cojen.classfile.CodeAssembler;
import org.cojen.classfile.Label;
import org.cojen.classfile.LocalVariable;
import org.cojen.classfile.Opcode;
import org.cojen.classfile.TypeDesc;
import org.cojen.util.BeanIntrospector;
import org.cojen.util.BeanProperty;

import com.amazon.carbonado.CorruptEncodingException;
import com.amazon.carbonado.Storable;
import com.amazon.carbonado.SupportException;

import com.amazon.carbonado.lob.Blob;
import com.amazon.carbonado.lob.Clob;
import com.amazon.carbonado.lob.Lob;

import com.amazon.carbonado.spi.StorableGenerator;
import com.amazon.carbonado.spi.TriggerSupport;

import com.amazon.carbonado.info.ChainedProperty;
import com.amazon.carbonado.info.Direction;
import com.amazon.carbonado.info.OrderedProperty;
import com.amazon.carbonado.info.StorableIndex;
import com.amazon.carbonado.info.StorableIntrospector;
import com.amazon.carbonado.info.StorableProperty;
import com.amazon.carbonado.info.StorablePropertyAdapter;

/**
 * Generates bytecode instructions for encoding/decoding Storable properties
 * to/from raw bytes.
 *
 * <p>Note: subclasses must override and specialize the hashCode and equals
 * methods. Failure to do so interferes with {@link StorableCodecFactory}'s
 * generated code cache.
 *
 * @author Brian S O'Neill
 */
public class GenericEncodingStrategy<S extends Storable> {
    private final Class<S> mType;
    private final StorableIndex<S> mPkIndex;

    private final int mKeyPrefixPadding;
    private final int mKeySuffixPadding;
    private final int mDataPrefixPadding;
    private final int mDataSuffixPadding;

    /**
     * @param type type of Storable to generate code for
     * @param pkIndex specifies sequence and ordering of key properties (optional)
     */
    public GenericEncodingStrategy(Class<S> type, StorableIndex<S> pkIndex) {
        this(type, pkIndex, 0, 0, 0, 0);
    }

    /**
     * @param type type of Storable to generate code for
     * @param pkIndex specifies sequence and ordering of key properties (optional)
     * @param keyPrefixPadding amount of padding bytes at start of keys
     * @param keySuffixPadding amount of padding bytes at end of keys
     * @param dataPrefixPadding amount of padding bytes at start of data values
     * @param dataSuffixPadding amount of padding bytes at end of data values
     */
    @SuppressWarnings("unchecked")
    public GenericEncodingStrategy(Class<S> type, StorableIndex<S> pkIndex,
                                   int keyPrefixPadding, int keySuffixPadding,
                                   int dataPrefixPadding, int dataSuffixPadding) {
        mType = type;

        if (keyPrefixPadding < 0 || keySuffixPadding < 0 ||
            dataPrefixPadding < 0 || dataSuffixPadding < 0) {
            throw new IllegalArgumentException();
        }
        mKeyPrefixPadding = keyPrefixPadding;
        mKeySuffixPadding = keySuffixPadding;
        mDataPrefixPadding = dataPrefixPadding;
        mDataSuffixPadding = dataSuffixPadding;

        if (pkIndex == null) {
            Map<String, ? extends StorableProperty<S>> map =
                StorableIntrospector.examine(mType).getPrimaryKeyProperties();

            StorableProperty<S>[] properties = new StorableProperty[map.size()];
            map.values().toArray(properties);

            Direction[] directions = new Direction[map.size()];
            Arrays.fill(directions, Direction.UNSPECIFIED);

            pkIndex = new StorableIndex<S>(properties, directions, true);
        }

        mPkIndex = pkIndex;
    }

    /**
     * Generates bytecode instructions to encode properties. The encoding is
     * suitable for "key" encoding, which means it is correctly comparable.
     *
     * <p>Note: if a partialStartVar is provided and this strategy has a key
     * prefix, the prefix is allocated only if the runtime value of
     * partialStartVar is zero. Likewise, if a partialEndVar is provided and
     * this strategy has a key suffix, the suffix is allocated only of the
     * runtime value of partialEndVar is one less than the property count.
     *
     * @param assembler code assembler to receive bytecode instructions
     * @param properties specific properties to encode, defaults to all key
     * properties if null
     * @param instanceVar local variable referencing Storable instance,
     * defaults to "this" if null. If variable type is an Object array, then
     * property values are read from the runtime value of this array instead
     * of a Storable instance.
     * @param adapterInstanceClass class containing static references to
     * adapter instances - defaults to instanceVar
     * @param useReadMethods when true, access properties by public read
     * methods instead of protected fields - should be used if class being
     * generated doesn't have access to these fields
     * @param partialStartVar optional variable for supporting partial key
     * generation. It must be an int, whose runtime value must be less than the
     * properties array length. It marks the range start of the partial
     * property range.
     * @param partialEndVar optional variable for supporting partial key
     * generation. It must be an int, whose runtime value must be less than or
     * equal to the properties array length. It marks the range end (exclusive)
     * of the partial property range.
     *
     * @return local variable referencing a byte array with encoded key
     *
     * @throws SupportException if any property type is not supported
     * @throws IllegalArgumentException if assembler is null, or if instanceVar
     * is not the correct instance type, or if partial variable types are not
     * ints
     */
    public LocalVariable buildKeyEncoding(CodeAssembler assembler,
                                          OrderedProperty<S>[] properties,
                                          LocalVariable instanceVar,
                                          Class<?> adapterInstanceClass,
                                          boolean useReadMethods,
                                          LocalVariable partialStartVar,
                                          LocalVariable partialEndVar)
        throws SupportException
    {
        properties = ensureKeyProperties(properties);
        return buildEncoding(true, assembler,
                             extractProperties(properties), extractDirections(properties),
                             instanceVar, adapterInstanceClass,
                             useReadMethods,
                             -1, // no generation support
                             partialStartVar, partialEndVar);
    }

    /**
     * Generates bytecode instructions to decode properties. A
     * CorruptEncodingException may be thrown from generated code.
     *
     * @param assembler code assembler to receive bytecode instructions
     * @param properties specific properties to decode, defaults to all key
     * properties if null
     * @param instanceVar local variable referencing Storable instance,
     * defaults to "this" if null. If variable type is an Object array, then
     * property values are placed into the runtime value of this array instead
     * of a Storable instance.
     * @param adapterInstanceClass class containing static references to
     * adapter instances - defaults to instanceVar
     * @param useWriteMethods when true, set properties by public write
     * methods instead of protected fields - should be used if class being
     * generated doesn't have access to these fields
     * @param encodedVar required variable, which must be a byte array. At
     * runtime, it references an encoded key.
     *
     * @throws SupportException if any property type is not supported
     * @throws IllegalArgumentException if assembler is null, or if instanceVar
     * is not the correct instance type, or if encodedVar is not a byte array
     */
    public void buildKeyDecoding(CodeAssembler assembler,
                                 OrderedProperty<S>[] properties,
                                 LocalVariable instanceVar,
                                 Class<?> adapterInstanceClass,
                                 boolean useWriteMethods,
                                 LocalVariable encodedVar)
        throws SupportException
    {
        properties = ensureKeyProperties(properties);
        buildDecoding(true, assembler,
                      extractProperties(properties), extractDirections(properties),
                      instanceVar, adapterInstanceClass, useWriteMethods,
                      -1, null, // no generation support
                      encodedVar);
    }

    /**
     * Generates bytecode instructions to encode properties. The encoding is
     * suitable for "data" encoding, which means it is not correctly
     * comparable, but it is more efficient than key encoding. Partial encoding
     * is not supported.
     *
     * @param assembler code assembler to receive bytecode instructions
     * @param properties specific properties to encode, defaults to all non-key
     * properties if null
     * @param instanceVar local variable referencing Storable instance,
     * defaults to "this" if null. If variable type is an Object array, then
     * property values are read from the runtime value of this array instead
     * of a Storable instance.
     * @param adapterInstanceClass class containing static references to
     * adapter instances - defaults to instanceVar
     * @param useReadMethods when true, access properties by public read
     * methods instead of protected fields
     * @param generation when non-negative, write a storable layout generation
     * value in one or four bytes. Generation 0..127 is encoded in one byte, and
     * 128..max is encoded in four bytes, with the most significant bit set.
     *
     * @return local variable referencing a byte array with encoded data
     *
     * @throws SupportException if any property type is not supported
     * @throws IllegalArgumentException if assembler is null, or if instanceVar
     * is not the correct instance type
     */
    public LocalVariable buildDataEncoding(CodeAssembler assembler,
                                           StorableProperty<S>[] properties,
                                           LocalVariable instanceVar,
                                           Class<?> adapterInstanceClass,
                                           boolean useReadMethods,
                                           int generation)
        throws SupportException
    {
        properties = ensureDataProperties(properties);
        return buildEncoding(false, assembler,
                             properties, null,
                             instanceVar, adapterInstanceClass,
                             useReadMethods, generation, null, null);
    }

    /**
     * Generates bytecode instructions to decode properties. A
     * CorruptEncodingException may be thrown from generated code.
     *
     * @param assembler code assembler to receive bytecode instructions
     * @param properties specific properties to decode, defaults to all non-key
     * properties if null
     * @param instanceVar local variable referencing Storable instance,
     * defaults to "this" if null. If variable type is an Object array, then
     * property values are placed into the runtime value of this array instead
     * of a Storable instance.
     * @param adapterInstanceClass class containing static references to
     * adapter instances - defaults to instanceVar
     * @param useWriteMethods when true, set properties by public write
     * methods instead of protected fields - should be used if class being
     * generated doesn't have access to these fields
     * @param generation when non-negative, decoder expects a storable layout
     * generation value to match this value. Otherwise, it throws a
     * CorruptEncodingException.
     * @param altGenerationHandler if non-null and a generation is provided,
     * this label defines an alternate generation handler. It is executed
     * instead of throwing a CorruptEncodingException if the generation doesn't
     * match. The actual generation is available on the top of the stack for
     * the handler to consume.
     * @param encodedVar required variable, which must be a byte array. At
     * runtime, it references encoded data.
     *
     * @throws SupportException if any property type is not supported
     * @throws IllegalArgumentException if assembler is null, or if instanceVar
     * is not the correct instance type, or if encodedVar is not a byte array
     */
    public void buildDataDecoding(CodeAssembler assembler,
                                  StorableProperty<S>[] properties,
                                  LocalVariable instanceVar,
                                  Class<?> adapterInstanceClass,
                                  boolean useWriteMethods,
                                  int generation,
                                  Label altGenerationHandler,
                                  LocalVariable encodedVar)
        throws SupportException
    {
        properties = ensureDataProperties(properties);
        buildDecoding(false, assembler, properties, null,
                      instanceVar, adapterInstanceClass, useWriteMethods,
                      generation, altGenerationHandler, encodedVar);
    }

    /**
     * Returns the type of Storable that code is generated for.
     */
    public final Class<S> getType() {
        return mType;
    }

    /**
     * Returns true if the type of the given property type is supported. The
     * types currently supported are primitives, primitive wrapper objects,
     * Strings, and byte arrays.
     */
    public boolean isSupported(Class<?> propertyType) {
        return isSupported(TypeDesc.forClass(propertyType));
    }

    /**
     * Returns true if the type of the given property type is supported. The
     * types currently supported are primitives, primitive wrapper objects,
     * Strings, byte arrays and Lobs.
     */
    public boolean isSupported(TypeDesc propertyType) {
        if (propertyType.toPrimitiveType() != null) {
            return true;
        }
        return propertyType == TypeDesc.STRING ||
            propertyType == TypeDesc.forClass(byte[].class) ||
            propertyType.toClass() != null && Lob.class.isAssignableFrom(propertyType.toClass());
    }

    public int getKeyPrefixPadding() {
        return mKeyPrefixPadding;
    }

    public int getKeySuffixPadding() {
        return mKeySuffixPadding;
    }

    public int getDataPrefixPadding() {
        return mDataPrefixPadding;
    }

    public int getDataSuffixPadding() {
        return mDataSuffixPadding;
    }

    /**
     * Returns amount of prefix key bytes that encoding strategy instance
     * produces which are always the same. Default implementation returns 0.
     */
    public int getConstantKeyPrefixLength() {
        return 0;
    }

    @Override
    public int hashCode() {
        return mType.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof GenericEncodingStrategy) {
            GenericEncodingStrategy other = (GenericEncodingStrategy) obj;
            return mType == other.mType
                && mKeyPrefixPadding == other.mKeyPrefixPadding
                && mKeySuffixPadding == other.mKeySuffixPadding
                && mDataPrefixPadding == other.mDataPrefixPadding
                && mDataSuffixPadding == other.mDataSuffixPadding;
        }
        return false;
    }

    /**
     * Returns all key properties in the form of an index.
     */
    protected StorableIndex<S> getPrimaryKeyIndex() {
        return mPkIndex;
    }

    /**
     * Returns all key properties as ordered properties, possibly with
     * unspecified directions.
     */
    protected OrderedProperty<S>[] gatherAllKeyProperties() {
        return mPkIndex.getOrderedProperties();
    }

    /**
     * Returns all data properties for storable.
     */
    @SuppressWarnings("unchecked")
    protected StorableProperty<S>[] gatherAllDataProperties() {
        Map<String, ? extends StorableProperty<S>> map =
            StorableIntrospector.examine(mType).getDataProperties();

        StorableProperty<S>[] properties = new StorableProperty[map.size()];

        int ordinal = 0;
        for (StorableProperty<S> property : map.values()) {
            properties[ordinal++] = property;
        }

        return properties;
    }

    protected StorablePropertyInfo checkSupport(StorableProperty<S> property)
        throws SupportException
    {
        if (isSupported(property.getType())) {
            return new StorablePropertyInfo(property);
        }

        // Look for an adapter that will allow this property to be supported.
        if (property.getAdapter() != null) {
            StorablePropertyAdapter adapter = property.getAdapter();
            for (Class<?> storageType : adapter.getStorageTypePreferences()) {
                if (!isSupported(storageType)) {
                    continue;
                }

                if (property.isNullable() && storageType.isPrimitive()) {
                    continue;
                }

                Method fromStorage, toStorage;
                fromStorage = adapter.findAdaptMethod(storageType, property.getType());
                if (fromStorage == null) {
                    continue;
                }
                toStorage = adapter.findAdaptMethod(property.getType(), storageType);
                if (toStorage != null) {
                    return new StorablePropertyInfo(property, storageType, fromStorage, toStorage);
                }
            }
        }

        throw notSupported(property);
    }

    @SuppressWarnings("unchecked")
    protected StorablePropertyInfo[] checkSupport(StorableProperty<S>[] properties)
        throws SupportException
    {
        int length = properties.length;
        StorablePropertyInfo[] infos = new StorablePropertyInfo[length];
        for (int i=0; i<length; i++) {
            infos[i] = checkSupport(properties[i]);
        }
        return infos;
    }

    private SupportException notSupported(StorableProperty<S> property) {
        return notSupported(property.getName(), property.getType().getName());
    }

    private SupportException notSupported(String propertyName, String typeName) {
        return new SupportException
            ("Type \"" + typeName +
             "\" not supported for property \"" + propertyName + '"');
    }

    private OrderedProperty<S>[] ensureKeyProperties(OrderedProperty<S>[] properties) {
        if (properties == null) {
            properties = gatherAllKeyProperties();
        } else {
            for (Object prop : properties) {
                if (prop == null) {
                    throw new IllegalArgumentException();
                }
            }
        }
        return properties;
    }

    @SuppressWarnings("unchecked")
    private StorableProperty<S>[] extractProperties(OrderedProperty<S>[] ordered) {
        StorableProperty<S>[] properties = new StorableProperty[ordered.length];
        for (int i=0; i<ordered.length; i++) {
            ChainedProperty chained = ordered[i].getChainedProperty();
            if (chained.getChainCount() > 0) {
                throw new IllegalArgumentException();
            }
            properties[i] = chained.getPrimeProperty();
        }
        return properties;
    }

    private Direction[] extractDirections(OrderedProperty<S>[] ordered) {
        Direction[] directions = new Direction[ordered.length];
        for (int i=0; i<ordered.length; i++) {
            directions[i] = ordered[i].getDirection();
        }
        return directions;
    }

    private StorableProperty<S>[] ensureDataProperties(StorableProperty<S>[] properties) {
        if (properties == null) {
            properties = gatherAllDataProperties();
        } else {
            for (Object prop : properties) {
                if (prop == null) {
                    throw new IllegalArgumentException();
                }
            }
        }
        return properties;
    }

    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////

    private LocalVariable buildEncoding(boolean forKey,
                                        CodeAssembler a,
                                        StorableProperty<S>[] properties,
                                        Direction[] directions,
                                        LocalVariable instanceVar,
                                        Class<?> adapterInstanceClass,
                                        boolean useReadMethods,
                                        int generation,
                                        LocalVariable partialStartVar,
                                        LocalVariable partialEndVar)
        throws SupportException
    {
        if (a == null) {
            throw new IllegalArgumentException();
        }
        if (partialStartVar != null && partialStartVar.getType() != TypeDesc.INT) {
            throw new IllegalArgumentException();
        }
        if (partialEndVar != null && partialEndVar.getType() != TypeDesc.INT) {
            throw new IllegalArgumentException();
        }

        // Encoding order is:
        //
        // 1. Prefix
        // 2. Generation prefix
        // 3. Properties
        // 4. Suffix

        final int prefix = forKey ? mKeyPrefixPadding : mDataPrefixPadding;

        final int generationPrefix;
        if (generation < 0) {
            generationPrefix = 0;
        } else if (generation < 128) {
            generationPrefix = 1;
        } else {
            generationPrefix = 4;
        }

        final int suffix = forKey ? mKeySuffixPadding : mDataSuffixPadding;

        final TypeDesc byteArrayType = TypeDesc.forClass(byte[].class);
        final LocalVariable encodedVar = a.createLocalVariable(null, byteArrayType);

        StorablePropertyInfo[] infos = checkSupport(properties);

        if (properties.length == 1) {
            // Ignore partial key encoding variables, since there can't be a
            // partial of one property.
            partialStartVar = null;
            partialEndVar = null;

            StorableProperty<S> property = properties[0];
            StorablePropertyInfo info = infos[0];

            if (info.getStorageType().toClass() == byte[].class) {
                // Since there is only one property, and it is just a byte
                // array, optimize by not doing any fancy encoding. If the
                // property is optional, then a byte prefix is needed to
                // identify a null reference.

                loadPropertyValue(a, info, 0, useReadMethods,
                                  instanceVar, adapterInstanceClass, partialStartVar);

                boolean descending =
                    forKey && directions != null && directions[0] == Direction.DESCENDING;

                TypeDesc[] params;
                if (prefix > 0 || generationPrefix > 0 || suffix > 0) {
                    a.loadConstant(prefix + generationPrefix);
                    a.loadConstant(suffix);
                    params = new TypeDesc[] {byteArrayType, TypeDesc.INT, TypeDesc.INT};
                } else {
                    params = new TypeDesc[] {byteArrayType};
                }

                if (property.isNullable()) {
                    if (descending) {
                        a.invokeStatic(KeyEncoder.class.getName(), "encodeSingleNullableDesc",
                                       byteArrayType, params);
                    } else {
                        a.invokeStatic(DataEncoder.class.getName(), "encodeSingleNullable",
                                       byteArrayType, params);
                    }
                } else if (descending) {
                    a.invokeStatic(KeyEncoder.class.getName(), "encodeSingleDesc",
                                   byteArrayType, params);
                } else if (prefix > 0 || generationPrefix > 0 || suffix > 0) {
                    a.invokeStatic(DataEncoder.class.getName(), "encodeSingle",
                                   byteArrayType, params);
                } else {
                    // Just return raw property value - no need to cache it either.
                }

                a.storeLocal(encodedVar);

                encodeGeneration(a, encodedVar, prefix, generation);

                return encodedVar;
            }
        }

        boolean doPartial = forKey && (partialStartVar != null || partialEndVar != null);

        // Calculate exactly how many bytes are needed to encode. The length
        // is composed of a static and a variable amount. The variable amount
        // is determined at runtime.

        int staticLength = 0;
        if (!forKey || partialStartVar == null) {
            // Only include prefix as static if no runtime check is needed
            // against runtime partial start value.
            staticLength += prefix + generationPrefix;
        }
        if (!forKey || partialEndVar == null) {
            // Only include suffix as static if no runtime check is needed
            // against runtime partial end value.
            staticLength += suffix;
        }

        boolean hasVariableLength;
        if (doPartial) {
            hasVariableLength = true;
        } else {
            hasVariableLength = false;
            for (GenericPropertyInfo info : infos) {
                int len = staticEncodingLength(info);
                if (len >= 0) {
                    staticLength += len;
                } else {
                    staticLength += ~len;
                    hasVariableLength = true;
                }
            }
        }

        // Generate code that loops over all the properties that have a
        // variable length. Load each property and perform the necessary
        // tests to determine the exact encoding length.

        boolean hasStackVar = false;
        if (hasVariableLength) {
            Label[] entryPoints = null;

            if (partialStartVar != null) {
                // Will jump into an arbitrary location, so always have a stack
                // variable available.
                a.loadConstant(0);
                hasStackVar = true;

                entryPoints = jumpToPartialEntryPoints(a, partialStartVar, properties.length);
            }

            Label exitPoint = a.createLabel();

            for (int i=0; i<properties.length; i++) {
                StorableProperty<S> property = properties[i];
                StorablePropertyInfo info = infos[i];

                if (doPartial) {
                    if (entryPoints != null) {
                        entryPoints[i].setLocation();
                    }
                    if (partialEndVar != null) {
                        // Add code to jump out of partial.
                        a.loadConstant(i);
                        a.loadLocal(partialEndVar);
                        a.ifComparisonBranch(exitPoint, ">=");
                    }
                } else if (staticEncodingLength(info) >= 0) {
                    continue;
                }

                TypeDesc propType = info.getStorageType();

                if (propType.isPrimitive()) {
                    // This should only ever get executed if implementing
                    // partial support. Otherwise, the static encoding length
                    // would have been already calculated.
                    a.loadConstant(staticEncodingLength(info));
                    if (hasStackVar) {
                        a.math(Opcode.IADD);
                    } else {
                        hasStackVar = true;
                    }
                } else if (propType.toPrimitiveType() != null) {
                    int amt = 0;
                    switch (propType.toPrimitiveType().getTypeCode()) {
                    case TypeDesc.BYTE_CODE:
                    case TypeDesc.BOOLEAN_CODE:
                        amt = 1;
                        break;
                    case TypeDesc.SHORT_CODE:
                    case TypeDesc.CHAR_CODE:
                        amt = 2;
                        break;
                    case TypeDesc.INT_CODE:
                    case TypeDesc.FLOAT_CODE:
                        amt = 4;
                        break;
                    case TypeDesc.LONG_CODE:
                    case TypeDesc.DOUBLE_CODE:
                        amt = 8;
                        break;
                    }

                    int extra = 0;
                    if (doPartial) {
                        // If value is null, then there may be a one byte size
                        // adjust for the null value. Otherwise it is the extra
                        // amount plus the size to encode the raw primitive
                        // value. If doPartial is false, then this extra amount
                        // was already accounted for in the static encoding
                        // length.

                        switch (propType.toPrimitiveType().getTypeCode()) {
                        case TypeDesc.BYTE_CODE:
                        case TypeDesc.SHORT_CODE:
                        case TypeDesc.CHAR_CODE:
                        case TypeDesc.INT_CODE:
                        case TypeDesc.LONG_CODE:
                            extra = 1;
                        }
                    }

                    if (!property.isNullable() || (doPartial && extra == 0)) {
                        a.loadConstant(amt);
                        if (hasStackVar) {
                            a.math(Opcode.IADD);
                        }
                        hasStackVar = true;
                    } else {
                        // Load property to test for null.
                        loadPropertyValue(a, info, i, useReadMethods,
                                          instanceVar, adapterInstanceClass, partialStartVar);

                        Label isNull = a.createLabel();
                        a.ifNullBranch(isNull, true);

                        a.loadConstant(amt);

                        if (hasStackVar) {
                            a.math(Opcode.IADD);
                            isNull.setLocation();
                            if (extra > 0) {
                                a.loadConstant(extra);
                                a.math(Opcode.IADD);
                            }
                        } else {
                            hasStackVar = true;
                            // Make sure that there is a zero (or extra) value on
                            // the stack if the isNull branch is taken.
                            Label notNull = a.createLabel();
                            a.branch(notNull);
                            isNull.setLocation();
                            a.loadConstant(extra);
                            notNull.setLocation();
                        }
                    }
                } else if (propType == TypeDesc.STRING) {
                    // Load property to test for null.
                    loadPropertyValue(a, info, i, useReadMethods,
                                      instanceVar, adapterInstanceClass, partialStartVar);

                    String className =
                        (forKey ? KeyEncoder.class : DataEncoder.class).getName();
                    a.invokeStatic(className, "calculateEncodedStringLength",
                                   TypeDesc.INT, new TypeDesc[] {TypeDesc.STRING});
                    if (hasStackVar) {
                        a.math(Opcode.IADD);
                    } else {
                        hasStackVar = true;
                    }
                } else if (propType.toClass() == byte[].class) {
                    // Load property to test for null.
                    loadPropertyValue(a, info, i, useReadMethods,
                                      instanceVar, adapterInstanceClass, partialStartVar);

                    String className =
                        (forKey ? KeyEncoder.class : DataEncoder.class).getName();
                    a.invokeStatic(className, "calculateEncodedLength",
                                   TypeDesc.INT, new TypeDesc[] {byteArrayType});
                    if (hasStackVar) {
                        a.math(Opcode.IADD);
                    } else {
                        hasStackVar = true;
                    }
                } else if (info.isLob()) {
                    // Lob locator is a long, or 8 bytes.
                    a.loadConstant(8);
                    if (hasStackVar) {
                        a.math(Opcode.IADD);
                    } else {
                        hasStackVar = true;
                    }
                } else {
                    throw notSupported(property);
                }
            }

            exitPoint.setLocation();

            if (forKey && partialStartVar != null && (prefix > 0 || generationPrefix > 0)) {
                // Prefix must be allocated only if runtime value of
                // partialStartVar is zero.
                a.loadLocal(partialStartVar);
                Label noPrefix = a.createLabel();
                a.ifZeroComparisonBranch(noPrefix, "!=");
                a.loadConstant(prefix + generationPrefix);
                if (hasStackVar) {
                    a.math(Opcode.IADD);
                } else {
                    hasStackVar = true;
                }
                noPrefix.setLocation();
            }

            if (forKey && partialEndVar != null && suffix > 0) {
                // Suffix must be allocated only if runtime value of
                // partialEndVar is equal to property count.
                a.loadLocal(partialEndVar);
                Label noSuffix = a.createLabel();
                a.loadConstant(properties.length);
                a.ifComparisonBranch(noSuffix, "!=");
                a.loadConstant(suffix);
                if (hasStackVar) {
                    a.math(Opcode.IADD);
                } else {
                    hasStackVar = true;
                }
                noSuffix.setLocation();
            }
        }

        // Allocate a byte array of the exact size.
        if (hasStackVar) {
            if (staticLength > 0) {
                a.loadConstant(staticLength);
                a.math(Opcode.IADD);
            }
        } else {
            a.loadConstant(staticLength);
        }
        a.newObject(byteArrayType);
        a.storeLocal(encodedVar);

        // Now encode into the byte array.

        int constantOffset = 0;
        LocalVariable offset = null;

        if (!forKey || partialStartVar == null) {
            // Only include prefix as constant offset if no runtime check is
            // needed against runtime partial start value.
            constantOffset += prefix + generationPrefix;
            encodeGeneration(a, encodedVar, prefix, generation);
        }

        Label[] entryPoints = null;

        if (forKey && partialStartVar != null) {
            // Will jump into an arbitrary location, so put an initial value
            // into offset variable.

            offset = a.createLocalVariable(null, TypeDesc.INT);
            a.loadConstant(0);
            if (prefix > 0) {
                // Prefix is allocated only if partial start is zero. Check if
                // offset should be adjusted to skip over it.
                a.loadLocal(partialStartVar);
                Label noPrefix = a.createLabel();
                a.ifZeroComparisonBranch(noPrefix, "!=");
                a.loadConstant(prefix + generationPrefix);
                a.math(Opcode.IADD);
                encodeGeneration(a, encodedVar, prefix, generation);
                noPrefix.setLocation();
            }
            a.storeLocal(offset);

            entryPoints = jumpToPartialEntryPoints(a, partialStartVar, properties.length);
        }

        Label exitPoint = a.createLabel();

        for (int i=0; i<properties.length; i++) {
            StorableProperty<S> property = properties[i];
            StorablePropertyInfo info = infos[i];

            if (doPartial) {
                if (entryPoints != null) {
                    entryPoints[i].setLocation();
                }
                if (partialEndVar != null) {
                    // Add code to jump out of partial.
                    a.loadConstant(i);
                    a.loadLocal(partialEndVar);
                    a.ifComparisonBranch(exitPoint, ">=");
                }
            }

            if (info.isLob()) {
                // Need RawSupport instance for getting locator from Lob.
                pushRawSupport(a, instanceVar);
            }

            boolean fromInstance = loadPropertyValue
                (a, info, i, useReadMethods, instanceVar, adapterInstanceClass, partialStartVar);

            TypeDesc propType = info.getStorageType();
            if (!property.isNullable() && propType.toPrimitiveType() != null) {
                // Since property type is a required primitive wrapper, convert
                // to a primitive rather than encoding using the form that
                // distinguishes null.

                // Property value that was passed in may be null, which is not
                // allowed.
                if (!fromInstance && !propType.isPrimitive()) {
                    a.dup();
                    Label notNull = a.createLabel();
                    a.ifNullBranch(notNull, false);

                    TypeDesc errorType = TypeDesc.forClass(IllegalArgumentException.class);
                    a.newObject(errorType);
                    a.dup();
                    a.loadConstant("Value for property \"" + property.getName() +
                                   "\" cannot be null");
                    a.invokeConstructor(errorType, new TypeDesc[] {TypeDesc.STRING});
                    a.throwObject();

                    notNull.setLocation();
                }

                a.convert(propType, propType.toPrimitiveType());
                propType = propType.toPrimitiveType();
            }

            if (info.isLob()) {
                // Extract locator from RawSupport.
                getLobLocator(a, info);

                // Locator is a long, so switch the type to be encoded properly.
                propType = TypeDesc.LONG;
            }

            // Fill out remaining parameters before calling specific method
            // to encode property value.
            a.loadLocal(encodedVar);
            if (offset == null) {
                a.loadConstant(constantOffset);
            } else {
                a.loadLocal(offset);
            }

            boolean descending =
                forKey && directions != null && directions[i] == Direction.DESCENDING;

            int amt = encodeProperty(a, propType, forKey, descending);

            if (amt > 0) {
                if (i + 1 < properties.length) {
                    // Only adjust offset if there are more properties.

                    if (offset == null) {
                        constantOffset += amt;
                    } else {
                        a.loadConstant(amt);
                        a.loadLocal(offset);
                        a.math(Opcode.IADD);
                        a.storeLocal(offset);
                    }
                }
            } else {
                if (i + 1 >= properties.length) {
                    // Don't need to keep track of offset anymore.
                    a.pop();
                } else {
                    // Only adjust offset if there are more properties.
                    if (offset == null) {
                        if (constantOffset > 0) {
                            a.loadConstant(constantOffset);
                            a.math(Opcode.IADD);
                        }
                        offset = a.createLocalVariable(null, TypeDesc.INT);
                    } else {
                        a.loadLocal(offset);
                        a.math(Opcode.IADD);
                    }
                    a.storeLocal(offset);
                }
            }
        }

        exitPoint.setLocation();

        return encodedVar;
    }

    /**
     * Generates code to load a property value onto the operand stack.
     *
     * @param info info for property to load
     * @param ordinal zero-based property ordinal, used only if instanceVar
     * refers to an object array.
     * @param useReadMethod when true, access property by public read method
     * instead of protected field
     * @param instanceVar local variable referencing Storable instance,
     * defaults to "this" if null. If variable type is an Object array, then
     * property values are read from the runtime value of this array instead
     * of a Storable instance.
     * @param adapterInstanceClass class containing static references to
     * adapter instances - defaults to instanceVar
     * @param partialStartVar optional variable for supporting partial key
     * generation. It must be an int, whose runtime value must be less than the
     * properties array length. It marks the range start of the partial
     * property range.
     * @return true if property was loaded from instance, false if loaded from
     * value array
     */
    protected boolean loadPropertyValue(CodeAssembler a,
                                        StorablePropertyInfo info, int ordinal,
                                        boolean useReadMethod,
                                        LocalVariable instanceVar,
                                        Class<?> adapterInstanceClass,
                                        LocalVariable partialStartVar)
    {
        TypeDesc type = info.getPropertyType();
        TypeDesc storageType = info.getStorageType();

        boolean isObjectArrayInstanceVar = instanceVar != null
            && instanceVar.getType() == TypeDesc.forClass(Object[].class);

        boolean useAdapterInstance = adapterInstanceClass != null
            && info.getToStorageAdapter() != null
            && (useReadMethod || isObjectArrayInstanceVar);

        if (useAdapterInstance) {
            // Push adapter instance to stack to be used later.
            String fieldName =
                info.getPropertyName() + StorableGenerator.ADAPTER_FIELD_ELEMENT + 0;
            TypeDesc adapterType = TypeDesc.forClass
                (info.getToStorageAdapter().getDeclaringClass());
            a.loadStaticField
                (TypeDesc.forClass(adapterInstanceClass), fieldName, adapterType);
        }

        if (instanceVar == null) {
            a.loadThis();
            if (useReadMethod) {
                info.addInvokeReadMethod(a);
            } else {
                // Access property value directly from protected field of "this".
                if (info.getToStorageAdapter() == null) {
                    a.loadField(info.getPropertyName(), type);
                } else {
                    // Invoke adapter method.
                    a.invokeVirtual(info.getReadMethodName() + '$', storageType, null);
                }
            }
        } else if (!isObjectArrayInstanceVar) {
            a.loadLocal(instanceVar);
            if (useReadMethod) {
                info.addInvokeReadMethod(a, instanceVar.getType());
            } else {
                // Access property value directly from protected field of
                // referenced instance. Assumes code is being defined in the
                // same package or a subclass.
                if (info.getToStorageAdapter() == null) {
                    a.loadField(instanceVar.getType(), info.getPropertyName(), type);
                } else {
                    // Invoke adapter method.
                    a.invokeVirtual(instanceVar.getType(),
                                    info.getReadMethodName() + '$', storageType, null);
                }
            }
        } else {
            // Access property value from object array.

            a.loadLocal(instanceVar);
            a.loadConstant(ordinal);
            if (ordinal > 0 && partialStartVar != null) {
                a.loadLocal(partialStartVar);
                a.math(Opcode.ISUB);
            }

            a.loadFromArray(TypeDesc.OBJECT);
            a.checkCast(type.toObjectType());
            if (type.isPrimitive()) {
                a.convert(type.toObjectType(), type);
            }
        }

        if (useAdapterInstance) {
            // Invoke adapter method on instance pushed earlier.
            a.invoke(info.getToStorageAdapter());
        }

        return !isObjectArrayInstanceVar;
    }

    /**
     * Returns a negative value if encoding is variable. The minimum static
     * amount is computed from the one's compliment. Of the types with variable
     * encoding lengths, only for primitives is the minimum static amount
     * returned more than zero.
     */
    private int staticEncodingLength(GenericPropertyInfo info) {
        TypeDesc type = info.getStorageType();
        TypeDesc primType = type.toPrimitiveType();

        if (primType == null) {
            if (info.isLob()) {
                // Lob locator is stored as a long.
                return 8;
            }
        } else {
            if (info.isNullable()) {
                // Type is a primitive wrapper.
                switch (primType.getTypeCode()) {
                case TypeDesc.BYTE_CODE:
                    return ~1;
                case TypeDesc.BOOLEAN_CODE:
                    return 1;
                case TypeDesc.SHORT_CODE:
                case TypeDesc.CHAR_CODE:
                    return ~1;
                case TypeDesc.INT_CODE:
                    return ~1;
                case TypeDesc.FLOAT_CODE:
                    return 4;
                case TypeDesc.LONG_CODE:
                    return ~1;
                case TypeDesc.DOUBLE_CODE:
                    return 8;
                }
            } else {
                // Type is primitive or a required primitive wrapper.
                switch (type.getTypeCode()) {
                case TypeDesc.BYTE_CODE:
                case TypeDesc.BOOLEAN_CODE:
                    return 1;
                case TypeDesc.SHORT_CODE:
                case TypeDesc.CHAR_CODE:
                    return 2;
                case TypeDesc.INT_CODE:
                case TypeDesc.FLOAT_CODE:
                    return 4;
                case TypeDesc.LONG_CODE:
                case TypeDesc.DOUBLE_CODE:
                    return 8;
                }
            }
        }

        return ~0;
    }

    /**
     * @param partialStartVar must not be null
     */
    private Label[] jumpToPartialEntryPoints(CodeAssembler a, LocalVariable partialStartVar,
                                             int propertyCount) {
        // Create all the entry points for offset var, whose locations will be
        // set later.
        int[] cases = new int[propertyCount];
        Label[] entryPoints = new Label[propertyCount];
        for (int i=0; i<propertyCount; i++) {
            cases[i] = i;
            entryPoints[i] = a.createLabel();
        }

        // Now jump in!
        Label errorLoc = a.createLabel();
        a.loadLocal(partialStartVar);
        a.switchBranch(cases, entryPoints, errorLoc);

        errorLoc.setLocation();
        TypeDesc errorType = TypeDesc.forClass(IllegalArgumentException.class);
        a.newObject(errorType);
        a.dup();
        a.loadConstant("Illegal partial start offset");
        a.invokeConstructor(errorType, new TypeDesc[] {TypeDesc.STRING});
        a.throwObject();

        return entryPoints;
    }

    /**
     * Generates code that calls an encoding method in DataEncoder or
     * KeyEncoder. Parameters must already be on the stack.
     *
     * @return 0 if an int amount is pushed onto the stack, or a positive value
     * if offset adjust amount is constant
     */
    private int encodeProperty(CodeAssembler a, TypeDesc type,
                               boolean forKey, boolean descending) {
        TypeDesc[] params = new TypeDesc[] {
            type, TypeDesc.forClass(byte[].class), TypeDesc.INT
        };

        if (type.isPrimitive()) {
            if (forKey && descending) {
                a.invokeStatic(KeyEncoder.class.getName(), "encodeDesc", null, params);
            } else {
                a.invokeStatic(DataEncoder.class.getName(), "encode", null, params);
            }

            switch (type.getTypeCode()) {
            case TypeDesc.BYTE_CODE:
            case TypeDesc.BOOLEAN_CODE:
                return 1;
            case TypeDesc.SHORT_CODE:
            case TypeDesc.CHAR_CODE:
                return 2;
            default:
            case TypeDesc.INT_CODE:
            case TypeDesc.FLOAT_CODE:
                return 4;
            case TypeDesc.LONG_CODE:
            case TypeDesc.DOUBLE_CODE:
                return 8;
            }
        } else if (type.toPrimitiveType() != null) {
            // Type is a primitive wrapper.

            int adjust;
            TypeDesc retType;

            switch (type.toPrimitiveType().getTypeCode()) {
            case TypeDesc.BOOLEAN_CODE:
                adjust = 1;
                retType = null;
                break;
            case TypeDesc.FLOAT_CODE:
                adjust = 4;
                retType = null;
                break;
            case TypeDesc.DOUBLE_CODE:
                adjust = 8;
                retType = null;
                break;
            default:
                adjust = 0;
                retType = TypeDesc.INT;
            }

            if (forKey && descending) {
                a.invokeStatic(KeyEncoder.class.getName(), "encodeDesc", retType, params);
            } else {
                a.invokeStatic(DataEncoder.class.getName(), "encode", retType, params);
            }

            return adjust;
        } else {
            // Type is a String or byte array.
            if (forKey) {
                if (descending) {
                    a.invokeStatic
                        (KeyEncoder.class.getName(), "encodeDesc", TypeDesc.INT, params);
                } else {
                    a.invokeStatic(KeyEncoder.class.getName(), "encode", TypeDesc.INT, params);
                }
            } else {
                a.invokeStatic(DataEncoder.class.getName(), "encode", TypeDesc.INT, params);
            }
            return 0;
        }
    }

    /**
     * Generates code that stores a one or four byte generation value into a
     * byte array referenced by the local variable.
     *
     * @param generation if less than zero, no code is generated
     */
    private void encodeGeneration(CodeAssembler a, LocalVariable encodedVar,
                                  int offset, int generation)
    {
        if (offset < 0) {
            throw new IllegalArgumentException();
        }
        if (generation < 0) {
            return;
        }
        if (generation < 128) {
            a.loadLocal(encodedVar);
            a.loadConstant(offset);
            a.loadConstant((byte) generation);
            a.storeToArray(TypeDesc.BYTE);
        } else {
            generation |= 0x80000000;
            for (int i=0; i<4; i++) {
                a.loadLocal(encodedVar);
                a.loadConstant(offset + i);
                a.loadConstant((byte) (generation >> (8 * (3 - i))));
                a.storeToArray(TypeDesc.BYTE);
            }
        }
    }

    /**
     * Generates code to push RawSupport instance to the stack.  RawSupport is
     * available only in Storable instances. If instanceVar is an Object[], a
     * SupportException is thrown.
     *
     * @param instanceVar Storable instance or array of property values. Null
     * is storable instance of "this".
     */
    protected void pushRawSupport(CodeAssembler a, LocalVariable instanceVar)
        throws SupportException
    {
        boolean isObjectArrayInstanceVar = instanceVar != null
            && instanceVar.getType() == TypeDesc.forClass(Object[].class);

        if (isObjectArrayInstanceVar) {
            throw new SupportException("Lob properties not supported");
        }

        if (instanceVar == null) {
            a.loadThis();
        } else {
            a.loadLocal(instanceVar);
        }

        a.loadField(StorableGenerator.SUPPORT_FIELD_NAME,
                    TypeDesc.forClass(TriggerSupport.class));
        a.checkCast(TypeDesc.forClass(RawSupport.class));
    }

    /**
     * Generates code to get a Lob locator value from RawSupport. RawSupport
     * instance and Lob instance must be on the stack. Result is a long locator
     * value on the stack.
     */
    private void getLobLocator(CodeAssembler a, StorablePropertyInfo info) {
        if (!info.isLob()) {
            throw new IllegalArgumentException();
        }
        a.invokeInterface(TypeDesc.forClass(RawSupport.class), "getLocator",
                          TypeDesc.LONG, new TypeDesc[] {info.getStorageType()});
    }

    /**
     * Generates code to get a Lob from a locator from RawSupport. RawSupport
     * instance and long locator must be on the stack. Result is a Lob on the
     * stack, which may be null.
     */
    private void getLobFromLocator(CodeAssembler a, StorablePropertyInfo info) {
        if (!info.isLob()) {
            throw new IllegalArgumentException();
        }

        TypeDesc type = info.getStorageType();
        String name;
        if (Blob.class.isAssignableFrom(type.toClass())) {
            name = "getBlob";
        } else if (Clob.class.isAssignableFrom(type.toClass())) {
            name = "getClob";
        } else {
            throw new IllegalArgumentException();
        }

        a.invokeInterface(TypeDesc.forClass(RawSupport.class), name,
                          type, new TypeDesc[] {TypeDesc.LONG});
    }

    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////

    private void buildDecoding(boolean forKey,
                               CodeAssembler a,
                               StorableProperty<S>[] properties,
                               Direction[] directions,
                               LocalVariable instanceVar,
                               Class<?> adapterInstanceClass,
                               boolean useWriteMethods,
                               int generation,
                               Label altGenerationHandler,
                               LocalVariable encodedVar)
        throws SupportException
    {
        if (a == null) {
            throw new IllegalArgumentException();
        }
        if (encodedVar == null || encodedVar.getType() != TypeDesc.forClass(byte[].class)) {
            throw new IllegalArgumentException();
        }

        // Decoding order is:
        //
        // 1. Prefix
        // 2. Generation prefix
        // 3. Properties
        // 4. Suffix

        final int prefix = forKey ? mKeyPrefixPadding : mDataPrefixPadding;

        final int generationPrefix;
        if (generation < 0) {
            generationPrefix = 0;
        } else if (generation < 128) {
            generationPrefix = 1;
        } else {
            generationPrefix = 4;
        }

        final int suffix = forKey ? mKeySuffixPadding : mDataSuffixPadding;

        final TypeDesc byteArrayType = TypeDesc.forClass(byte[].class);

        StorablePropertyInfo[] infos = checkSupport(properties);

        decodeGeneration(a, encodedVar, prefix, generation, altGenerationHandler);

        if (properties.length == 1) {
            StorableProperty<S> property = properties[0];
            StorablePropertyInfo info = infos[0];

            if (info.getStorageType().toClass() == byte[].class) {
                // Since there is only one property, and it is just a byte
                // array, it doesn't have any fancy encoding.

                // Push to stack in preparation for storing a property.
                pushDecodingInstanceVar(a, 0, instanceVar);

                a.loadLocal(encodedVar);

                boolean descending =
                    forKey && directions != null && directions[0] == Direction.DESCENDING;

                TypeDesc[] params;
                if (prefix > 0 || generationPrefix > 0 || suffix > 0) {
                    a.loadConstant(prefix + generationPrefix);
                    a.loadConstant(suffix);
                    params = new TypeDesc[] {byteArrayType, TypeDesc.INT, TypeDesc.INT};
                } else {
                    params = new TypeDesc[] {byteArrayType};
                }

                if (property.isNullable()) {
                    if (descending) {
                        a.invokeStatic(KeyDecoder.class.getName(), "decodeSingleNullableDesc",
                                       byteArrayType, params);
                    } else {
                        a.invokeStatic(DataDecoder.class.getName(), "decodeSingleNullable",
                                       byteArrayType, params);
                    }
                } else if (descending) {
                    a.invokeStatic(KeyDecoder.class.getName(), "decodeSingleDesc",
                                   byteArrayType, params);
                } else if (prefix > 0 || generationPrefix > 0 || suffix > 0) {
                    a.invokeStatic(DataDecoder.class.getName(), "decodeSingle",
                                   byteArrayType, params);
                } else {
                    // Just store raw property value.
                }

                storePropertyValue(a, info, useWriteMethods, instanceVar, adapterInstanceClass);
                return;
            }
        }

        // Now decode from the byte array.

        int constantOffset = prefix + generationPrefix;
        LocalVariable offset = null;
        // References to local variables which will hold references.
        LocalVariable[] stringRef = new LocalVariable[1];
        LocalVariable[] byteArrayRef = new LocalVariable[1];
        LocalVariable[] valueRefRef = new LocalVariable[1];

        for (int i=0; i<infos.length; i++) {
            StorablePropertyInfo info = infos[i];

            // Push to stack in preparation for storing a property.
            pushDecodingInstanceVar(a, i, instanceVar);

            TypeDesc storageType = info.getStorageType();

            if (info.isLob()) {
                // Need RawSupport instance for getting Lob from locator.
                pushRawSupport(a, instanceVar);
                // Locator is encoded as a long.
                storageType = TypeDesc.LONG;
            }

            a.loadLocal(encodedVar);
            if (offset == null) {
                a.loadConstant(constantOffset);
            } else {
                a.loadLocal(offset);
            }

            boolean descending =
                forKey && directions != null && directions[i] == Direction.DESCENDING;

            int amt = decodeProperty(a, info, storageType, forKey, descending,
                                     stringRef, byteArrayRef, valueRefRef);

            if (info.isLob()) {
                getLobFromLocator(a, info);
            }

            if (amt != 0) {
                if (i + 1 < properties.length) {
                    // Only adjust offset if there are more properties.

                    if (amt > 0) {
                        if (offset == null) {
                            constantOffset += amt;
                        } else {
                            a.loadConstant(amt);
                            a.loadLocal(offset);
                            a.math(Opcode.IADD);
                            a.storeLocal(offset);
                        }
                    } else {
                        // Offset adjust is one if returned object is null.
                        a.dup();
                        Label notNull = a.createLabel();
                        a.ifNullBranch(notNull, false);
                        a.loadConstant(1 + (offset == null ? constantOffset : 0));
                        Label cont = a.createLabel();
                        a.branch(cont);
                        notNull.setLocation();
                        a.loadConstant(~amt + (offset == null ? constantOffset : 0));
                        cont.setLocation();

                        if (offset == null) {
                            offset = a.createLocalVariable(null, TypeDesc.INT);
                        } else {
                            a.loadLocal(offset);
                            a.math(Opcode.IADD);
                        }
                        a.storeLocal(offset);
                    }
                }
            } else {
                if (i + 1 >= properties.length) {
                    // Don't need to keep track of offset anymore.
                    a.pop();
                } else {
                    // Only adjust offset if there are more properties.
                    if (offset == null) {
                        if (constantOffset > 0) {
                            a.loadConstant(constantOffset);
                            a.math(Opcode.IADD);
                        }
                        offset = a.createLocalVariable(null, TypeDesc.INT);
                    } else {
                        a.loadLocal(offset);
                        a.math(Opcode.IADD);
                    }
                    a.storeLocal(offset);
                }

                // Get the value out of the ref array so that it can be stored.
                a.loadLocal(valueRefRef[0]);
                a.loadConstant(0);
                a.loadFromArray(valueRefRef[0].getType());
            }

            storePropertyValue(a, info, useWriteMethods, instanceVar, adapterInstanceClass);
        }
    }

    /**
     * Generates code that calls a decoding method in DataDecoder or
     * KeyDecoder. Parameters must already be on the stack.
     *
     * @return 0 if an int amount is pushed onto the stack, or a positive value
     * if offset adjust amount is constant, or a negative value if offset
     * adjust is constant or one more
     */
    private int decodeProperty(CodeAssembler a,
                               GenericPropertyInfo info, TypeDesc storageType,
                               boolean forKey, boolean descending,
                               LocalVariable[] stringRefRef, LocalVariable[] byteArrayRefRef,
                               LocalVariable[] valueRefRef)
        throws SupportException
    {
        TypeDesc primType = storageType.toPrimitiveType();

        if (primType != null) {
            String methodName;
            TypeDesc returnType;
            int adjust;

            if (primType != storageType && info.isNullable()) {
                // Property type is a nullable boxed primitive.
                returnType = storageType;

                switch (primType.getTypeCode()) {
                case TypeDesc.BYTE_CODE:
                    methodName = "decodeByteObj";
                    adjust = ~2;
                    break;
                case TypeDesc.BOOLEAN_CODE:
                    methodName = "decodeBooleanObj";
                    adjust = 1;
                    break;
                case TypeDesc.SHORT_CODE:
                    methodName = "decodeShortObj";
                    adjust = ~3;
                    break;
                case TypeDesc.CHAR_CODE:
                    methodName = "decodeCharacterObj";
                    adjust = ~3;
                    break;
                default:
                case TypeDesc.INT_CODE:
                    methodName = "decodeIntegerObj";
                    adjust = ~5;
                    break;
                case TypeDesc.FLOAT_CODE:
                    methodName = "decodeFloatObj";
                    adjust = 4;
                    break;
                case TypeDesc.LONG_CODE:
                    methodName = "decodeLongObj";
                    adjust = ~9;
                    break;
                case TypeDesc.DOUBLE_CODE:
                    methodName = "decodeDoubleObj";
                    adjust = 8;
                    break;
                }
            } else {
                // Property type is a primitive or a boxed primitive.
                returnType = primType;

                switch (primType.getTypeCode()) {
                case TypeDesc.BYTE_CODE:
                    methodName = "decodeByte";
                    adjust = 1;
                    break;
                case TypeDesc.BOOLEAN_CODE:
                    methodName = "decodeBoolean";
                    adjust = 1;
                    break;
                case TypeDesc.SHORT_CODE:
                    methodName = "decodeShort";
                    adjust = 2;
                    break;
                case TypeDesc.CHAR_CODE:
                    methodName = "decodeChar";
                    adjust = 2;
                    break;
                default:
                case TypeDesc.INT_CODE:
                    methodName = "decodeInt";
                    adjust = 4;
                    break;
                case TypeDesc.FLOAT_CODE:
                    methodName = "decodeFloat";
                    adjust = 4;
                    break;
                case TypeDesc.LONG_CODE:
                    methodName = "decodeLong";
                    adjust = 8;
                    break;
                case TypeDesc.DOUBLE_CODE:
                    methodName = "decodeDouble";
                    adjust = 8;
                    break;
                }
            }

            TypeDesc[] params = {TypeDesc.forClass(byte[].class), TypeDesc.INT};
            if (forKey && descending) {
                a.invokeStatic
                    (KeyDecoder.class.getName(), methodName + "Desc", returnType, params);
            } else {
                a.invokeStatic
                    (DataDecoder.class.getName(), methodName, returnType, params);
            }

            if (returnType.isPrimitive()) {
                if (!storageType.isPrimitive()) {
                    // Wrap it.
                    a.convert(returnType, storageType);
                }
            }

            return adjust;
        } else {
            String className = (forKey ? KeyDecoder.class : DataDecoder.class).getName();
            String methodName;
            TypeDesc refType;

            if (storageType == TypeDesc.STRING) {
                methodName = (forKey && descending) ? "decodeStringDesc" : "decodeString";
                refType = TypeDesc.forClass(String[].class);
                if (stringRefRef[0] == null) {
                    stringRefRef[0] = a.createLocalVariable(null, refType);
                    a.loadConstant(1);
                    a.newObject(refType);
                    a.storeLocal(stringRefRef[0]);
                }
                a.loadLocal(stringRefRef[0]);
                valueRefRef[0] = stringRefRef[0];
            } else if (storageType.toClass() == byte[].class) {
                methodName = (forKey && descending) ? "decodeDesc" : "decode";
                refType = TypeDesc.forClass(byte[][].class);
                if (byteArrayRefRef[0] == null) {
                    byteArrayRefRef[0] = a.createLocalVariable(null, refType);
                    a.loadConstant(1);
                    a.newObject(refType);
                    a.storeLocal(byteArrayRefRef[0]);
                }
                a.loadLocal(byteArrayRefRef[0]);
                valueRefRef[0] = byteArrayRefRef[0];
            } else {
                throw notSupported(info.getPropertyName(), storageType.getFullName());
            }

            TypeDesc[] params = {TypeDesc.forClass(byte[].class), TypeDesc.INT, refType};
            a.invokeStatic(className, methodName, TypeDesc.INT, params);

            return 0;
        }
    }

    /**
     * Push decoding instanceVar to stack in preparation to calling
     * storePropertyValue.
     *
     * @param ordinal zero-based property ordinal, used only if instanceVar
     * refers to an object array.
     * @param instanceVar local variable referencing Storable instance,
     * defaults to "this" if null. If variable type is an Object array, then
     * property values are written to the runtime value of this array instead
     * of a Storable instance.
     * @see #storePropertyValue storePropertyValue
     */
    protected void pushDecodingInstanceVar(CodeAssembler a, int ordinal,
                                           LocalVariable instanceVar) {
        if (instanceVar == null) {
            // Push this to stack in preparation for storing a property.
            a.loadThis();
        } else if (instanceVar.getType() != TypeDesc.forClass(Object[].class)) {
            // Push reference to stack in preparation for storing a property.
            a.loadLocal(instanceVar);
        } else {
            // Push array and index to stack in preparation for storing a property.
            a.loadLocal(instanceVar);
            a.loadConstant(ordinal);
        }
    }

    /**
     * Generates code to store a property value into an instance which is
     * already on the operand stack. If instance is an Object array, index into
     * array must also be on the operand stack.
     *
     * @param info info for property to store to
     * @param useWriteMethod when true, set property by public write method
     * instead of protected field
     * @param instanceVar local variable referencing Storable instance,
     * defaults to "this" if null. If variable type is an Object array, then
     * property values are written to the runtime value of this array instead
     * of a Storable instance.
     * @param adapterInstanceClass class containing static references to
     * adapter instances - defaults to instanceVar
     * @see #pushDecodingInstanceVar pushDecodingInstanceVar
     */
    protected void storePropertyValue(CodeAssembler a, StorablePropertyInfo info,
                                      boolean useWriteMethod,
                                      LocalVariable instanceVar,
                                      Class<?> adapterInstanceClass) {
        TypeDesc type = info.getPropertyType();
        TypeDesc storageType = info.getStorageType();

        boolean isObjectArrayInstanceVar = instanceVar != null
            && instanceVar.getType() == TypeDesc.forClass(Object[].class);

        boolean useAdapterInstance = adapterInstanceClass != null
            && info.getToStorageAdapter() != null
            && (useWriteMethod || isObjectArrayInstanceVar);

        if (useAdapterInstance) {
            // Push adapter instance to adapt property value. It must be on the
            // stack before the property value, so swap.

            // Store unadapted property to temp var in order to be swapped.
            LocalVariable temp = a.createLocalVariable(null, storageType);
            a.storeLocal(temp);

            String fieldName =
                info.getPropertyName() + StorableGenerator.ADAPTER_FIELD_ELEMENT + 0;
            TypeDesc adapterType = TypeDesc.forClass
                (info.getToStorageAdapter().getDeclaringClass());
            a.loadStaticField
                (TypeDesc.forClass(adapterInstanceClass), fieldName, adapterType);

            a.loadLocal(temp);
            a.invoke(info.getFromStorageAdapter());

            // Stack now contains property adapted to its publicly declared type.
        }

        if (instanceVar == null) {
            if (useWriteMethod) {
                info.addInvokeWriteMethod(a);
            } else {
                // Set property value directly to protected field of instance.
                if (info.getToStorageAdapter() == null) {
                    a.storeField(info.getPropertyName(), type);
                } else {
                    // Invoke adapter method.
                    a.invokeVirtual(info.getWriteMethodName() + '$',
                                    null, new TypeDesc[] {storageType});
                }
            }
        } else if (!isObjectArrayInstanceVar) {
            TypeDesc instanceVarType = instanceVar.getType();

            // Drop properties that are missing or whose types are incompatible.
            doDrop: {
                Class instanceVarClass = instanceVarType.toClass();
                if (instanceVarClass != null) {
                    Map<String, BeanProperty> props =
                        BeanIntrospector.getAllProperties(instanceVarClass);
                    BeanProperty prop = props.get(info.getPropertyName());
                    if (prop != null) {
                        if (prop.getType() == type.toClass()) {
                            break doDrop;
                        }

                        // Types differ, but if primitive types, perform conversion.
                        TypeDesc primType = type.toPrimitiveType();
                        if (primType != null) {
                            TypeDesc propType = TypeDesc.forClass(prop.getType());
                            TypeDesc primPropType = propType.toPrimitiveType();
                            if (primPropType != null) {
                                // Apply conversion and store property.

                                Label convertLabel = a.createLabel();
                                Label convertedLabel = a.createLabel();

                                if (!type.isPrimitive() && propType.isPrimitive()) {
                                    // Might attempt to unbox null, which
                                    // throws NullPointerException. Instead,
                                    // convert null to zero or false.

                                    a.dup();
                                    a.ifNullBranch(convertLabel, false);
                                    a.pop(); // pop null off stack

                                    switch (propType.getTypeCode()) {
                                    default:
                                        a.loadConstant(0);
                                        break;
                                    case TypeDesc.LONG_CODE:
                                        a.loadConstant(0L);
                                        break;
                                    case TypeDesc.FLOAT_CODE:
                                        a.loadConstant(0.0f);
                                        break;
                                    case TypeDesc.DOUBLE_CODE:
                                        a.loadConstant(0.0d);
                                        break;
                                    }

                                    a.branch(convertedLabel);
                                }

                                convertLabel.setLocation();
                                a.convert(type, propType);

                                convertedLabel.setLocation();

                                type = propType;
                                break doDrop;
                            }
                        }
                    }
                }

                // Drop missing or incompatible property.
                if (storageType.isDoubleWord()) {
                    a.pop2();
                } else {
                    a.pop();
                }
                return;
            }

            if (useWriteMethod) {
                info.addInvokeWriteMethod(a, instanceVarType);
            } else {
                // Set property value directly to protected field of referenced
                // instance. Assumes code is being defined in the same package
                // or a subclass.
                if (info.getToStorageAdapter() == null) {
                    a.storeField(instanceVarType, info.getPropertyName(), type);
                } else {
                    // Invoke adapter method.
                    a.invokeVirtual(instanceVarType, info.getWriteMethodName() + '$',
                                    null, new TypeDesc[] {storageType});
                }
            }
        } else {
            // Set property value to object array. No need to check if we
            // should call a write method because arrays don't have write
            // methods.
            if (type.isPrimitive()) {
                a.convert(type, type.toObjectType());
            }
            a.storeToArray(TypeDesc.OBJECT);
        }
    }

    /**
     * Generates code that ensures a matching generation value exists in the
     * byte array referenced by the local variable, throwing a
     * CorruptEncodingException otherwise.
     *
     * @param generation if less than zero, no code is generated
     */
    private void decodeGeneration(CodeAssembler a, LocalVariable encodedVar,
                                  int offset, int generation, Label altGenerationHandler)
    {
        if (offset < 0) {
            throw new IllegalArgumentException();
        }
        if (generation < 0) {
            return;
        }

        LocalVariable actualGeneration = a.createLocalVariable(null, TypeDesc.INT);
        a.loadLocal(encodedVar);
        a.loadConstant(offset);
        a.loadFromArray(TypeDesc.BYTE);
        a.storeLocal(actualGeneration);
        a.loadLocal(actualGeneration);
        Label compareGeneration = a.createLabel();
        a.ifZeroComparisonBranch(compareGeneration, ">=");

        // Decode four byte generation format.
        a.loadLocal(actualGeneration);
        a.loadConstant(24);
        a.math(Opcode.ISHL);
        a.loadConstant(0x7fffffff);
        a.math(Opcode.IAND);
        for (int i=1; i<4; i++) {
            a.loadLocal(encodedVar);
            a.loadConstant(offset + i);
            a.loadFromArray(TypeDesc.BYTE);
            a.loadConstant(0xff);
            a.math(Opcode.IAND);
            int shift = 8 * (3 - i);
            if (shift > 0) {
                a.loadConstant(shift);
                a.math(Opcode.ISHL);
            }
            a.math(Opcode.IOR);
        }
        a.storeLocal(actualGeneration);

        compareGeneration.setLocation();

        a.loadConstant(generation);
        a.loadLocal(actualGeneration);
        Label generationMatches = a.createLabel();
        a.ifComparisonBranch(generationMatches, "==");

        if (altGenerationHandler != null) {
            a.loadLocal(actualGeneration);
            a.branch(altGenerationHandler);
        } else {
            // Throw CorruptEncodingException.

            TypeDesc corruptEncodingEx = TypeDesc.forClass(CorruptEncodingException.class);
            a.newObject(corruptEncodingEx);
            a.dup();
            a.loadConstant(generation);    // expected generation
            a.loadLocal(actualGeneration); // actual generation
            a.invokeConstructor(corruptEncodingEx, new TypeDesc[] {TypeDesc.INT, TypeDesc.INT});
            a.throwObject();
        }

        generationMatches.setLocation();
    }
}