forked from pgjdbc/pgjdbc
/
ByteConverter.java
657 lines (602 loc) · 21.6 KB
/
ByteConverter.java
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
/*
* Copyright (c) 2011, PostgreSQL Global Development Group
* See the LICENSE file in the project root for more information.
*/
package org.postgresql.util;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
/**
* Helper methods to parse java base types from byte arrays.
*
* @author Mikko Tiihonen
* @author Brett Okken
*/
public class ByteConverter {
/**
* Simple stack structure for non-negative {@code short} values.
*/
private static final class PositiveShorts {
private short[] shorts = new short[8];
private int idx = 0;
PositiveShorts() {
}
public void push(short s) {
if (s < 0) {
throw new IllegalArgumentException("only non-negative values accepted: " + s);
}
if (idx == shorts.length) {
grow();
}
shorts[idx++] = s;
}
public int size() {
return idx;
}
public boolean isEmpty() {
return idx == 0;
}
public short pop() {
return idx > 0 ? shorts[--idx] : -1;
}
private void grow() {
final int newSize = shorts.length <= 1024 ? shorts.length << 1 : (int) (shorts.length * 1.5);
shorts = Arrays.copyOf(shorts, newSize);
}
}
private static final int NUMERIC_DSCALE_MASK = 0x00003FFF;
private static final short NUMERIC_POS = 0x0000;
private static final short NUMERIC_NEG = 0x4000;
private static final short NUMERIC_NAN = (short) 0xC000;
private static final int SHORT_BYTES = 2;
private static final int LONG_BYTES = 4;
private static final int[] INT_TEN_POWERS = new int[6];
private static final long[] LONG_TEN_POWERS = new long[19];
private static final BigInteger[] BI_TEN_POWERS = new BigInteger[32];
private static final BigInteger BI_TEN_THOUSAND = BigInteger.valueOf(10000);
private static final BigInteger BI_MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);
static {
for (int i = 0; i < INT_TEN_POWERS.length; ++i) {
INT_TEN_POWERS[i] = (int) Math.pow(10, i);
}
for (int i = 0; i < LONG_TEN_POWERS.length; ++i) {
LONG_TEN_POWERS[i] = (long) Math.pow(10, i);
}
for (int i = 0; i < BI_TEN_POWERS.length; ++i) {
BI_TEN_POWERS[i] = BigInteger.TEN.pow(i);
}
}
private ByteConverter() {
// prevent instantiation of static helper class
}
/**
* Convert a variable length array of bytes to an integer
* @param bytes array of bytes that can be decoded as an integer
* @return integer
*/
public static int bytesToInt(byte []bytes) {
if ( bytes.length == 1 ) {
return (int)bytes[0];
}
if ( bytes.length == SHORT_BYTES ) {
return int2(bytes, 0);
}
if ( bytes.length == LONG_BYTES ) {
return int4(bytes, 0);
} else {
throw new IllegalArgumentException("Argument bytes is empty");
}
}
/**
* Convert a variable length array of bytes to an integer
* @param bytes array of bytes that can be decoded as an integer
* @return integer
*/
public static Number numeric(byte [] bytes) {
return numeric(bytes, 0, bytes.length);
}
/**
* Convert a variable length array of bytes to a {@link Number}. The result will
* always be a {@link BigDecimal} or {@link Double#NaN}.
*
* @param bytes array of bytes to be decoded from binary numeric representation.
* @param pos index of the start position of the bytes array for number
* @param numBytes number of bytes to use, length is already encoded
* in the binary format but this is used for double checking
* @return BigDecimal representation of numeric or {@link Double#NaN}.
*/
public static Number numeric(byte [] bytes, int pos, int numBytes) {
if (numBytes < 8) {
throw new IllegalArgumentException("number of bytes should be at-least 8");
}
//number of 2-byte shorts representing 4 decimal digits
short len = ByteConverter.int2(bytes, pos);
//0 based number of 4 decimal digits (i.e. 2-byte shorts) before the decimal
//a value <= 0 indicates an absolute value < 1.
short weight = ByteConverter.int2(bytes, pos + 2);
//indicates positive, negative or NaN
short sign = ByteConverter.int2(bytes, pos + 4);
//number of digits after the decimal. This must be >= 0.
//a value of 0 indicates a whole number (integer).
short scale = ByteConverter.int2(bytes, pos + 6);
//An integer should be built from the len number of 2 byte shorts, treating each
//as 4 digits.
//The weight, if > 0, indicates how many of those 4 digit chunks should be to the
//"left" of the decimal. If the weight is 0, then all 4 digit chunks start immediately
//to the "right" of the decimal. If the weight is < 0, the absolute distance from 0
//indicates 4 leading "0" digits to the immediate "right" of the decimal, prior to the
//digits from "len".
//A weight which is positive, can be a number larger than what len defines. This means
//there are trailing 0s after the "len" integer and before the decimal.
//The scale indicates how many significant digits there are to the right of the decimal.
//A value of 0 indicates a whole number (integer).
//The combination of weight, len, and scale can result in either trimming digits provided
//by len (only to the right of the decimal) or adding significant 0 values to the right
//of len (on either side of the decimal).
if (numBytes != (len * SHORT_BYTES + 8)) {
throw new IllegalArgumentException("invalid length of bytes \"numeric\" value");
}
if (!(sign == NUMERIC_POS
|| sign == NUMERIC_NEG
|| sign == NUMERIC_NAN)) {
throw new IllegalArgumentException("invalid sign in \"numeric\" value");
}
if (sign == NUMERIC_NAN) {
return Double.NaN;
}
if ((scale & NUMERIC_DSCALE_MASK) != scale) {
throw new IllegalArgumentException("invalid scale in \"numeric\" value");
}
if (len == 0) {
return new BigDecimal(BigInteger.ZERO, scale);
}
int idx = pos + 8;
short d = ByteConverter.int2(bytes, idx);
//if the absolute value is (0, 1), then leading '0' values
//do not matter for the unscaledInt, but trailing 0s do
if (weight < 0) {
assert scale > 0;
int effectiveScale = scale;
//adjust weight to determine how many leading 0s after the decimal
//before the provided values/digits actually begin
++weight;
if (weight < 0) {
effectiveScale += (4 * weight);
}
int i = 1;
//typically there should not be leading 0 short values, as it is more
//efficient to represent that in the weight value
for ( ; i < len && d == 0; ++i) {
//each leading 0 value removes 4 from the effective scale
effectiveScale -= 4;
idx += 2;
d = ByteConverter.int2(bytes, idx);
}
assert effectiveScale > 0;
if (effectiveScale >= 4) {
effectiveScale -= 4;
} else {
//an effective scale of less than four means that the value d
//has trailing 0s which are not significant
//so we divide by the appropriate power of 10 to reduce those
d = (short) (d / INT_TEN_POWERS[4 - effectiveScale]);
effectiveScale = 0;
}
//defer moving to BigInteger as long as possible
//operations on the long are much faster
BigInteger unscaledBI = null;
long unscaledInt = d;
for ( ; i < len; ++i) {
if (i == 4 && effectiveScale > 2) {
unscaledBI = BigInteger.valueOf(unscaledInt);
}
idx += 2;
d = ByteConverter.int2(bytes, idx);
//if effective scale is at least 4, then all 4 digits should be used
//and the existing number needs to be shifted 4
if (effectiveScale >= 4) {
if (unscaledBI == null) {
unscaledInt *= 10000;
} else {
unscaledBI = unscaledBI.multiply(BI_TEN_THOUSAND);
}
effectiveScale -= 4;
} else {
//if effective scale is less than 4, then only shift left based on remaining scale
if (unscaledBI == null) {
unscaledInt *= INT_TEN_POWERS[effectiveScale];
} else {
unscaledBI = unscaledBI.multiply(tenPower(effectiveScale));
}
//and d needs to be shifted to the right to only get correct number of
//significant digits
d = (short) (d / INT_TEN_POWERS[4 - effectiveScale]);
effectiveScale = 0;
}
if (unscaledBI == null) {
unscaledInt += d;
} else {
if (d != 0) {
unscaledBI = unscaledBI.add(BigInteger.valueOf(d));
}
}
}
//now we need BigInteger to create BigDecimal
if (unscaledBI == null) {
unscaledBI = BigInteger.valueOf(unscaledInt);
}
//if there is remaining effective scale, apply it here
if (effectiveScale > 0) {
unscaledBI = unscaledBI.multiply(tenPower(effectiveScale));
}
if (sign == NUMERIC_NEG) {
unscaledBI = unscaledBI.negate();
}
return new BigDecimal(unscaledBI, scale);
}
//if there is no scale, then shorts are the unscaled int
if (scale == 0) {
//defer moving to BigInteger as long as possible
//operations on the long are much faster
BigInteger unscaledBI = null;
long unscaledInt = d;
//loop over all of the len shorts to process as the unscaled int
for (int i = 1; i < len; ++i) {
if (i == 4) {
unscaledBI = BigInteger.valueOf(unscaledInt);
}
idx += 2;
d = ByteConverter.int2(bytes, idx);
if (unscaledBI == null) {
unscaledInt *= 10000;
unscaledInt += d;
} else {
unscaledBI = unscaledBI.multiply(BI_TEN_THOUSAND);
if (d != 0) {
unscaledBI = unscaledBI.add(BigInteger.valueOf(d));
}
}
}
//now we need BigInteger to create BigDecimal
if (unscaledBI == null) {
unscaledBI = BigInteger.valueOf(unscaledInt);
}
if (sign == NUMERIC_NEG) {
unscaledBI = unscaledBI.negate();
}
//the difference between len and weight (adjusted from 0 based) becomes the scale for BigDecimal
final int bigDecScale = (len - (weight + 1)) * 4;
//string representation always results in a BigDecimal with scale of 0
//the binary representation, where weight and len can infer trailing 0s, can result in a negative scale
//to produce a consistent BigDecimal, we return the equivalent object with scale set to 0
return bigDecScale == 0 ? new BigDecimal(unscaledBI) : new BigDecimal(unscaledBI, bigDecScale).setScale(0);
}
//defer moving to BigInteger as long as possible
//operations on the long are much faster
BigInteger unscaledBI = null;
long unscaledInt = d;
//weight and scale as defined by postgresql are a bit different than how BigDecimal treats scale
//maintain the effective values to massage as we process through values
int effectiveWeight = weight;
int effectiveScale = scale;
for (int i = 1 ; i < len; ++i) {
if (i == 4) {
unscaledBI = BigInteger.valueOf(unscaledInt);
}
idx += 2;
d = ByteConverter.int2(bytes, idx);
//first process effective weight down to 0
if (effectiveWeight > 0) {
--effectiveWeight;
if (unscaledBI == null) {
unscaledInt *= 10000;
} else {
unscaledBI = unscaledBI.multiply(BI_TEN_THOUSAND);
}
} else if (effectiveScale >= 4) {
//if effective scale is at least 4, then all 4 digits should be used
//and the existing number needs to be shifted 4
effectiveScale -= 4;
if (unscaledBI == null) {
unscaledInt *= 10000;
} else {
unscaledBI = unscaledBI.multiply(BI_TEN_THOUSAND);
}
} else {
//if effective scale is less than 4, then only shift left based on remaining scale
if (unscaledBI == null) {
unscaledInt *= INT_TEN_POWERS[effectiveScale];
} else {
unscaledBI = unscaledBI.multiply(tenPower(effectiveScale));
}
//and d needs to be shifted to the right to only get correct number of
//significant digits
d = (short) (d / INT_TEN_POWERS[4 - effectiveScale]);
effectiveScale = 0;
}
if (unscaledBI == null) {
unscaledInt += d;
} else {
if (d != 0) {
unscaledBI = unscaledBI.add(BigInteger.valueOf(d));
}
}
}
//now we need BigInteger to create BigDecimal
if (unscaledBI == null) {
unscaledBI = BigInteger.valueOf(unscaledInt);
}
//if there is remaining weight, apply it here
if (effectiveWeight > 0) {
unscaledBI = unscaledBI.multiply(tenPower(effectiveWeight * 4));
}
//if there is remaining effective scale, apply it here
if (effectiveScale > 0) {
unscaledBI = unscaledBI.multiply(tenPower(effectiveScale));
}
if (sign == NUMERIC_NEG) {
unscaledBI = unscaledBI.negate();
}
return new BigDecimal(unscaledBI, scale);
}
/**
* Converts a non-null {@link BigDecimal} to binary format for {@link org.postgresql.core.Oid#NUMERIC}.
* @param nbr The instance to represent in binary.
* @return The binary representation of <i>nbr</i>.
*/
public static byte[] numeric(BigDecimal nbr) {
final PositiveShorts shorts = new PositiveShorts();
BigInteger unscaled = nbr.unscaledValue().abs();
int scale = nbr.scale();
if (unscaled.equals(BigInteger.ZERO)) {
final byte[] bytes = new byte[] {0,0,-1,-1,0,0,0,0};
ByteConverter.int2(bytes, 6, Math.max(0, scale));
return bytes;
}
int weight = -1;
if (scale <= 0) {
//this means we have an integer
//adjust unscaled and weight
if (scale < 0) {
scale = Math.abs(scale);
//weight value covers 4 digits
weight += scale / 4;
//whatever remains needs to be incorporated to the unscaled value
int mod = scale % 4;
unscaled = unscaled.multiply(tenPower(mod));
scale = 0;
}
while (unscaled.compareTo(BI_MAX_LONG) > 0) {
final BigInteger[] pair = unscaled.divideAndRemainder(BI_TEN_THOUSAND);
unscaled = pair[0];
final short shortValue = pair[1].shortValue();
if (shortValue != 0 || !shorts.isEmpty()) {
shorts.push(shortValue);
}
++weight;
}
long unscaledLong = unscaled.longValueExact();
do {
final short shortValue = (short) (unscaledLong % 10000);
if (shortValue != 0 || !shorts.isEmpty()) {
shorts.push(shortValue);
}
unscaledLong = unscaledLong / 10000L;
++weight;
} while (unscaledLong != 0);
} else {
final BigInteger[] split = unscaled.divideAndRemainder(tenPower(scale));
BigInteger decimal = split[1];
BigInteger wholes = split[0];
weight = -1;
if (!BigInteger.ZERO.equals(decimal)) {
int mod = scale % 4;
int segments = scale / 4;
if (mod != 0) {
decimal = decimal.multiply(tenPower(4 - mod));
++segments;
}
do {
final BigInteger[] pair = decimal.divideAndRemainder(BI_TEN_THOUSAND);
decimal = pair[0];
final short shortValue = pair[1].shortValue();
if (shortValue != 0 || !shorts.isEmpty()) {
shorts.push(shortValue);
}
--segments;
} while (!BigInteger.ZERO.equals(decimal));
//for the leading 0 shorts we either adjust weight (if no wholes)
// or push shorts
if (BigInteger.ZERO.equals(wholes)) {
weight -= segments;
} else {
//now add leading 0 shorts
for (int i = 0; i < segments; ++i) {
shorts.push((short) 0);
}
}
}
while (!BigInteger.ZERO.equals(wholes)) {
++weight;
final BigInteger[] pair = wholes.divideAndRemainder(BI_TEN_THOUSAND);
wholes = pair[0];
final short shortValue = pair[1].shortValue();
if (shortValue != 0 || !shorts.isEmpty()) {
shorts.push(shortValue);
}
}
}
//8 bytes for "header" and then 2 for each short
final byte[] bytes = new byte[8 + (2 * shorts.size())];
int idx = 0;
//number of 2-byte shorts representing 4 decimal digits
ByteConverter.int2(bytes, idx, shorts.size());
idx += 2;
//0 based number of 4 decimal digits (i.e. 2-byte shorts) before the decimal
ByteConverter.int2(bytes, idx, weight);
idx += 2;
//indicates positive, negative or NaN
ByteConverter.int2(bytes, idx, nbr.signum() == -1 ? NUMERIC_NEG : NUMERIC_POS);
idx += 2;
//number of digits after the decimal
ByteConverter.int2(bytes, idx, Math.max(0, scale));
idx += 2;
short s;
while ((s = shorts.pop()) != -1) {
ByteConverter.int2(bytes, idx, s);
idx += 2;
}
return bytes;
}
private static BigInteger tenPower(int exponent) {
return BI_TEN_POWERS.length > exponent ? BI_TEN_POWERS[exponent] : BigInteger.TEN.pow(exponent);
}
/**
* Parses a long value from the byte array.
*
* @param bytes The byte array to parse.
* @param idx The starting index of the parse in the byte array.
* @return parsed long value.
*/
public static long int8(byte[] bytes, int idx) {
return
((long) (bytes[idx + 0] & 255) << 56)
+ ((long) (bytes[idx + 1] & 255) << 48)
+ ((long) (bytes[idx + 2] & 255) << 40)
+ ((long) (bytes[idx + 3] & 255) << 32)
+ ((long) (bytes[idx + 4] & 255) << 24)
+ ((long) (bytes[idx + 5] & 255) << 16)
+ ((long) (bytes[idx + 6] & 255) << 8)
+ (bytes[idx + 7] & 255);
}
/**
* Parses an int value from the byte array.
*
* @param bytes The byte array to parse.
* @param idx The starting index of the parse in the byte array.
* @return parsed int value.
*/
public static int int4(byte[] bytes, int idx) {
return
((bytes[idx] & 255) << 24)
+ ((bytes[idx + 1] & 255) << 16)
+ ((bytes[idx + 2] & 255) << 8)
+ ((bytes[idx + 3] & 255));
}
/**
* Parses a short value from the byte array.
*
* @param bytes The byte array to parse.
* @param idx The starting index of the parse in the byte array.
* @return parsed short value.
*/
public static short int2(byte[] bytes, int idx) {
return (short) (((bytes[idx] & 255) << 8) + ((bytes[idx + 1] & 255)));
}
/**
* Parses a boolean value from the byte array.
*
* @param bytes
* The byte array to parse.
* @param idx
* The starting index to read from bytes.
* @return parsed boolean value.
*/
public static boolean bool(byte[] bytes, int idx) {
return bytes[idx] == 1;
}
/**
* Parses a float value from the byte array.
*
* @param bytes The byte array to parse.
* @param idx The starting index of the parse in the byte array.
* @return parsed float value.
*/
public static float float4(byte[] bytes, int idx) {
return Float.intBitsToFloat(int4(bytes, idx));
}
/**
* Parses a double value from the byte array.
*
* @param bytes The byte array to parse.
* @param idx The starting index of the parse in the byte array.
* @return parsed double value.
*/
public static double float8(byte[] bytes, int idx) {
return Double.longBitsToDouble(int8(bytes, idx));
}
/**
* Encodes a long value to the byte array.
*
* @param target The byte array to encode to.
* @param idx The starting index in the byte array.
* @param value The value to encode.
*/
public static void int8(byte[] target, int idx, long value) {
target[idx + 0] = (byte) (value >>> 56);
target[idx + 1] = (byte) (value >>> 48);
target[idx + 2] = (byte) (value >>> 40);
target[idx + 3] = (byte) (value >>> 32);
target[idx + 4] = (byte) (value >>> 24);
target[idx + 5] = (byte) (value >>> 16);
target[idx + 6] = (byte) (value >>> 8);
target[idx + 7] = (byte) value;
}
/**
* Encodes a int value to the byte array.
*
* @param target The byte array to encode to.
* @param idx The starting index in the byte array.
* @param value The value to encode.
*/
public static void int4(byte[] target, int idx, int value) {
target[idx + 0] = (byte) (value >>> 24);
target[idx + 1] = (byte) (value >>> 16);
target[idx + 2] = (byte) (value >>> 8);
target[idx + 3] = (byte) value;
}
/**
* Encodes a int value to the byte array.
*
* @param target The byte array to encode to.
* @param idx The starting index in the byte array.
* @param value The value to encode.
*/
public static void int2(byte[] target, int idx, int value) {
target[idx + 0] = (byte) (value >>> 8);
target[idx + 1] = (byte) value;
}
/**
* Encodes a boolean value to the byte array.
*
* @param target
* The byte array to encode to.
* @param idx
* The starting index in the byte array.
* @param value
* The value to encode.
*/
public static void bool(byte[] target, int idx, boolean value) {
target[idx] = value ? (byte) 1 : (byte) 0;
}
/**
* Encodes a int value to the byte array.
*
* @param target The byte array to encode to.
* @param idx The starting index in the byte array.
* @param value The value to encode.
*/
public static void float4(byte[] target, int idx, float value) {
int4(target, idx, Float.floatToRawIntBits(value));
}
/**
* Encodes a int value to the byte array.
*
* @param target The byte array to encode to.
* @param idx The starting index in the byte array.
* @param value The value to encode.
*/
public static void float8(byte[] target, int idx, double value) {
int8(target, idx, Double.doubleToRawLongBits(value));
}
}