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
package Torello.Java.Additional;

import Torello.Java.ReadOnly.ROArrayListBuilder;
import Torello.Java.ReadOnly.ReadOnlyArrayList;
import Torello.Java.ReadOnly.ReadOnlyList;

import java.util.ArrayList;
import java.util.function.Function;

class ConstPoolCtorHelper
{
    static final byte NUM_TAGS = 21;

    // This is a little bit for efficiency, and a little bit for Readability
    static final ReadOnlyList<Integer> EMPTY_LIST = ReadOnlyArrayList.emptyROAL();

    // Sort of the same... Easier to read - yes.   Efficiency?  No improvement
    static final Function<ROArrayListBuilder<Integer>, ReadOnlyList<Integer>> f =

            (ROArrayListBuilder<Integer> roalb) -> (roalb == null)
                ? EMPTY_LIST 
                : roalb.build();

    static Ret6<
            ReadOnlyList<Byte>,                     // ConstantPool.tags
            ReadOnlyList<Object>,                   // ConstantPool.values
            ReadOnlyList<Object>,                   // ConstantPool.dereferencedValues
            ReadOnlyList<Integer>,                  // ConstantPool.indices
            ReadOnlyList<ReadOnlyList<Integer>>,    // ConstantPool.indicesGroupBy
            Integer                                 // ConstantPool.tableSizeBytes
        >
        construct(byte[] bArr)
    {
        // The constant pool starts at byte 10
        int SIZE = ((bArr[8] & 0xFF) << 8) | (bArr[9] & 0xFF);

        final ROArrayListBuilder<Byte>      tagsROALB       = new ROArrayListBuilder<>(SIZE);
        final ROArrayListBuilder<Object>    valuesROALB     = new ROArrayListBuilder<>(SIZE);
        final ROArrayListBuilder<Integer>   indicesROALB    = new ROArrayListBuilder<>(SIZE);

        tagsROALB.add       (Byte.valueOf((byte) 0));
        valuesROALB.add     (Integer.valueOf(SIZE));
        indicesROALB.add    (8);

        final ArrayList<ROArrayListBuilder<Integer>> groupByData = new ArrayList<>(NUM_TAGS);

        for (byte b=0; b < NUM_TAGS; b++) groupByData.add(null);

        int bArrIndex = 10;

        // System.out.println("ConstantPool SIZE: " + SIZE);


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Main Constant-Reader Loop
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // 
        // This loop starts at 1, because the first constant in the pool is the SIZE itself
        // For class 'HTMLNode', the number stored there is 97, but according to the `javap`
        // output, the last actual constant is number 96.  I'm going to presume that the
        // off-by-one error is that the Constant-Pool Length, counts as part of the size...

        for (int i=1; i < SIZE; i++)
        {
            final byte tag = bArr[bArrIndex++];

            /*
            System.out.println(
                StringParse.zeroPad(i+1) + ", Tag: " +
                ((tag < tagNames.size())
                    ? tagNames.get(tag)
                    : "OUT OF BOUNDS FOR SIZE")
            );
            */


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Parse the next constant found in the table
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            Object o = ReadConstant.read(bArr, tag, bArrIndex);

            tagsROALB.add(tag);
            valuesROALB.add(o);
            indicesROALB.add(bArrIndex - 1); // The '-1' is because it was incremented above!


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Update the "Group-By" Table-Builder - add the constant to the correct table!
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            ROArrayListBuilder<Integer> roalb = groupByData.get(tag);

            if (roalb == null)
            {
                roalb = new ROArrayListBuilder<>(SIZE);
                groupByData.set(tag, roalb);
            }

            roalb.add(i);


            // Truly Awful, but...  I have talked to Chat-GPT at length why these *FORCE* the
            // Constant-Number to increment by TWO instead of ONE.  These two Types/Kinds of
            // Constants occupy 8-Bytes in total.  The JVM / JDK Developers seemed to think it
            // necessary that "Skipping a beat" for Doubles and Longs is important enough because
            // they are larger than the other entries in the Constant Pool.
            // 
            // Note that for type UTF8 (a.k.a. a String, but not actually called String), the
            // Constant-Pool Index is still, indeed, only incrmented by 1 (not 2).

            if ((o instanceof Double) || (o instanceof Long))
            {
                tagsROALB.add(null);
                valuesROALB.add(null);
                indicesROALB.add(null);
                i++; // Don't forget!!!
            }

            /*
            System.out.print(
                "     Val: " +
                ((o instanceof Ret2)
                    ? StrIndent.indentAfter2ndLine(o.toString(), 10, true, true)
                    : (o.toString() + '\n'))
            );
            */


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Increment the Table-Index Pointer
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // 
            // "bytesToSkip" tells exactly how many more byte-array indices need to be skipped
            // for the given Constant!

            bArrIndex += (tag == 1)
                ? numBytesWideUTF8(bArr, bArrIndex)
                : ConstantPool.tagWidthBytes.get(tag);
        }


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // The two main Lookup Tables
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // 
        // The EXACT-SIZE of the Constant-Pool table, but measure in bytes.
        // 
        // Remember, the first 10 BYTES OF THE FILE contain:
        //      MAGIC_NUMBER, Major-Version-Number, Minor-Version-Number & Const-Pool Size
        // This is why '-10' is subtracted from the actual current byte[]-array index pointer.
        // 
        // Finally, one diagnostic to check is whether:
        // bArr[cp.tableSizeBytes + 10] actually contains the Access-Flags 2-Byte Unsigned-Integer

        final int tableSizeBytes = bArrIndex - 10;


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // The two main Lookup Tables
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        ReadOnlyList<Byte>      tags    = tagsROALB.build();
        ReadOnlyList<Object>    values  = valuesROALB.build();
        ReadOnlyList<Integer>   indices = indicesROALB.build();


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Group-By Lookup Table
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        //
        // Using Torello.Java.ReadOnly's Constructor's have some problems due to Java's
        // Generic Type-Erasure.  Because i had a "byte" (NUM_TAGS is declared as a "byte"),
        // It was simply unable to figure out which constructor I wanted. 
        // 
        // NOTE: This constructor accepts a Boxed "java.lang.Integer" - **NOT** an "int"
        //       There is a standard, common "Auto-Boxing" feature in Java.
        //
        // HOWEVER: When the value being passed to a "java.lang.Integer" is a Java "byte" primitive
        //          It just decides not to Auto-Box the "byte => Integer", and eventually says that
        //          it cannot match this constructor to any of the listed constructors.

        final ReadOnlyList<ReadOnlyList<Integer>> indicesGroupBy =
            new ReadOnlyArrayList<ReadOnlyList<Integer>>(groupByData, f, 0 + NUM_TAGS);


        // 0 + NUM_TAGS  ==> REALLY **REALLY OBNOXOIUS** !!!
        // 
        // NUM_TAGS is type "byte".  As such, you must cast it to "int"
        // If you don't you will **NEVER** find the bug.  Never!  YOU NEVER WILL
        //
        // I wrote the damned thing, and it got me (again).
        // The only problem with Package ReadOnly is its heavy use of Constructors with
        // Generic-Type Parameters.  Java's Generics have bugs => Generic-Erasure + Raw-Types
        // is a BUG!
        // 
        // Casting "byte" to "int" by using the expression "0 + NUM_TAGS" SOLVES / ELIMINATES 
        // a problem that is a combination of: 
        // 
        //      Java-Auto-Boxing 
        //      Generics-Erasure
        //      Type-Inference


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Validate: Throws Exceptions if Invalid
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        Validate.run(tags, values);


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // De-Referenced Values - It is much WISER to run this AFTER 'Validate'
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // 
        // All this loop is doing is "Building the Instances", so that the user (if he so wishes)
        // does not need to rely on a bunch of "Ret2's" or "Integers".  This will convert the
        // Table-Index Pointers into the actual data-classes that hold the constant's values.

        final ROArrayListBuilder<Object> derefROALB = new ROArrayListBuilder<>(SIZE);

        derefROALB.add(values.get(0));

        for (int i=1; i < SIZE; i++)
        {
            // All of the Ret2<Integer, Integer> are converted into actual instances of:
            // ConstantPool.Reference, ConstantPool.MethodHandle & ConstantPool.Dynamic
            //
            // Also, all of the java.lang.Integer's which say "Table-Index Pointer" are 
            // "looked up" in the table, and replaced by the actual value-Object to which they
            // point!

            final Byte tag = tags.get(i);


            // Remember, the obnoxious quality.  For 8-Byte Valued Constants, there is - well - a
            // "skip" in the Constant-Pool Table's Constant...

            if (tag == null)
            {
                derefROALB.add(null);
                continue;
            }

            final Object derefVal = DereferencedValue.get(tags, values, tag, i);
            derefROALB.add(derefVal);
        }

        final ReadOnlyList<Object> dereferencedValues = derefROALB.build();


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Return & Exit
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        return new Ret6<
                ReadOnlyList<Byte>,
                ReadOnlyList<Object>,
                ReadOnlyList<Object>,
                ReadOnlyList<Integer>,
                ReadOnlyList<ReadOnlyList<Integer>>,
                Integer
            >
        (tags, values, dereferencedValues, indices, indicesGroupBy, tableSizeBytes);
    }

    // Small, private, static, Constructor-Helper
    private static int numBytesWideUTF8(final byte[] bArr, int index)
    {
        // First 2 bytes at the given index store the length of the UTF-8 string.
        int utf8Length = ((bArr[index] & 0xFF) << 8) | (bArr[index + 1] & 0xFF);

        // Skip 2 bytes for the length + the actual length of the UTF-8 string.
        return 2 + utf8Length;
    }

}