-
-
Notifications
You must be signed in to change notification settings - Fork 938
Expand file tree
/
Copy pathPack.java
More file actions
2697 lines (2384 loc) · 99.6 KB
/
Pack.java
File metadata and controls
2697 lines (2384 loc) · 99.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***** BEGIN LICENSE BLOCK *****
* Version: EPL 2.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* 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.eclipse.org/legal/epl-v20.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2003-2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 Derek Berner <derek.berner@state.nm.us>
* Copyright (C) 2006 Evan Buswell <ebuswell@gmail.com>
* Copyright (C) 2007 Nick Sieger <nicksieger@gmail.com>
* Copyright (C) 2009 Joseph LaFata <joe@quibb.org>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.util;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.jcodings.specific.ASCIIEncoding;
import org.jcodings.specific.USASCIIEncoding;
import org.jcodings.specific.UTF8Encoding;
import org.jruby.*;
import org.jruby.platform.Platform;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.io.EncodingUtils;
import static com.headius.backport9.buffer.Buffers.markBuffer;
import static com.headius.backport9.buffer.Buffers.positionBuffer;
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Convert.asFloat;
import static org.jruby.api.Convert.toInt;
import static org.jruby.api.Convert.toLong;
import static org.jruby.api.Create.newArray;
import static org.jruby.api.Create.newString;
import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.rangeError;
import static org.jruby.api.Error.typeError;
import static org.jruby.util.RubyStringBuilder.str;
import static org.jruby.util.TypeConverter.toFloat;
public class Pack {
private static final byte[] sSp10 = " ".getBytes();
private static final byte[] sNil10 = "\000\000\000\000\000\000\000\000\000\000".getBytes();
private static final int IS_STAR = -1;
private static final ASCIIEncoding ASCII = ASCIIEncoding.INSTANCE;
private static final USASCIIEncoding USASCII = USASCIIEncoding.INSTANCE;
private static final UTF8Encoding UTF8 = UTF8Encoding.INSTANCE;
/** Native pack type.
**/
private static final String NATIVE_CODES = "sSiIlLjJ";
private static final String MAPPED_CODES = "sSiIqQjJ";
private static final char BE = '>' + 127; // 189, bumped up to avoid collisions with LE
private static final char LE = '<'; // 60
private static final String ENDIANESS_CODES = new String(new char[] {
's' + BE, 'S' + BE/*n*/, 'i' + BE, 'I' + BE, 'l' + BE, 'L' + BE/*N*/, 'q' + BE, 'Q' + BE, 'j' + BE, 'J' + BE,
's' + LE, 'S' + LE/*v*/, 'i' + LE, 'I' + LE, 'l' + LE, 'L' + LE/*V*/, 'q' + LE, 'Q' + LE, 'j' + LE, 'J' + LE});
/** Unpack modes
**/
private static final int UNPACK_ARRAY = 0;
private static final int UNPACK_BLOCK = 1;
private static final int UNPACK_1 = 2;
private static final String sTooFew = "too few arguments";
private static final byte[] uu_table;
private static final byte[] b64_table;
public static final byte[] sHexDigits;
public static final int[] b64_xtable = new int[256];
private static final Converter[] converters = new Converter[512];
private static long num2quad(ThreadContext context, IRubyObject arg) {
if (arg.isNil()) return 0L;
if (arg instanceof RubyBignum bignum) return bignum.getValue().longValue();
return toLong(context, arg);
}
private static float obj2flt(ThreadContext context, IRubyObject o) {
return (float) toFloat(context.runtime, o).asDouble(context);
}
private static double obj2dbl(ThreadContext context, IRubyObject o) {
return toFloat(context.runtime, o).asDouble(context);
}
static {
uu_table =
ByteList.plain("`!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_");
b64_table =
ByteList.plain("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
sHexDigits = ByteList.plain("0123456789abcdef0123456789ABCDEFx");
// b64_xtable for decoding Base 64
for (int i = 0; i < 256; i++) {
b64_xtable[i] = -1;
}
for (int i = 0; i < 64; i++) {
b64_xtable[(int)b64_table[i]] = i;
}
// single precision, little-endian
converters['e'] = new Converter(4) {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFloat(context, decodeFloatLittleEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeFloatLittleEndian(result, obj2flt(context, o));
}
};
// single precision, big-endian
converters['g'] = new Converter(4) {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFloat(context, decodeFloatBigEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeFloatBigEndian(result, obj2flt(context, o));
}
};
// single precision, native
Converter tmp = new Converter(4) {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFloat(context, Platform.BYTE_ORDER == Platform.BIG_ENDIAN ?
decodeFloatBigEndian(enc) : decodeFloatLittleEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result) {
var value = obj2flt(context, o);
if (Platform.BYTE_ORDER == Platform.BIG_ENDIAN) {
encodeFloatBigEndian(result, value);
} else {
encodeFloatLittleEndian(result, value);
}
}
};
converters['F'] = tmp; // single precision, native
converters['f'] = tmp; // single precision, native
// double precision, little-endian
converters['E'] = new Converter(8) {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFloat(context, decodeDoubleLittleEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeDoubleLittleEndian(result, obj2dbl(context, o));
}
};
// double precision, big-endian
converters['G'] = new Converter(8) {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFloat(context, decodeDoubleBigEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeDoubleBigEndian(result, obj2dbl(context, o));
}
};
// double precision, native
tmp = new Converter(8) {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFloat(context, Platform.BYTE_ORDER == Platform.BIG_ENDIAN ?
decodeDoubleBigEndian(enc) : decodeDoubleLittleEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeDoubleLittleEndian(result, obj2dbl(context, o));
}
};
converters['D'] = tmp; // double precision, native
converters['d'] = tmp; // double precision, native
// signed short, little-endian
tmp = new QuadConverter(2, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, decodeShortUnsignedLittleEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeShortLittleEndian(result, overflowQuad(num2quad(context, o)));
}
};
converters['v'] = tmp;
converters['S' + LE] = tmp;
// signed short, big-endian
tmp = new QuadConverter(2, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, decodeShortUnsignedBigEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result) {
encodeShortBigEndian(result, overflowQuad(num2quad(context, o)));
}
};
converters['n'] = tmp;
converters['S' + BE] = tmp;
// signed short, native
converters['s'] = new QuadConverter(2, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, Platform.BYTE_ORDER == Platform.BIG_ENDIAN ?
decodeShortBigEndian(enc) : decodeShortLittleEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result) {
encodeShortByByteOrder(result, overflowQuad(num2quad(context, o))); // XXX: 0xffff0000 on BE?
}
};
// unsigned short, native
converters['S'] = new QuadConverter(2, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, Platform.BYTE_ORDER == Platform.BIG_ENDIAN ?
decodeShortUnsignedBigEndian(enc) : decodeShortUnsignedLittleEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeShortByByteOrder(result, overflowQuad(num2quad(context, o)));
}
};
// signed short, little endian
converters['s' + LE] = new QuadConverter(2, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, decodeShortLittleEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result) {
encodeShortLittleEndian(result, overflowQuad(num2quad(context, o))); // XXX: 0xffff0000 on BE?
}
};
// signed short, big endian
converters['s' + BE] = new QuadConverter(2, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, decodeShortBigEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result) {
encodeShortBigEndian(result, overflowQuad(num2quad(context, o))); // XXX: 0xffff0000 on BE?
}
};
// signed char
converters['c'] = new Converter(1, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
int c = enc.get();
return asFixnum(context, c > (char) 127 ? c-256 : c);
}
public void encode(ThreadContext context, IRubyObject o, ByteList result) {
byte c = (byte) (num2quad(context, o) & 0xff);
result.append(c);
}
};
// unsigned char
converters['C'] = new Converter(1, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, enc.get() & 0xFF);
}
public void encode(ThreadContext context, IRubyObject o, ByteList result){
byte c = o == context.nil ? 0 : (byte) (num2quad(context, o) & 0xff);
result.append(c);
}
};
// unsigned long, little-endian
tmp = new Converter(4, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, decodeIntUnsignedLittleEndian(enc));
}
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeIntLittleEndian(result, (int) toLong(context, o));
}
};
converters['V'] = tmp;
converters['L' + LE] = tmp;
converters['I' + LE] = tmp;
if (Platform.BIT_WIDTH == 32) converters['J' + LE] = tmp;
// unsigned long, big-endian
tmp = new Converter(4, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, decodeIntUnsignedBigEndian(enc));
}
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeIntBigEndian(result, (int) toLong(context, o));
}
};
converters['N'] = tmp;
converters['L' + BE] = tmp;
converters['I' + BE] = tmp;
if (Platform.BIT_WIDTH == 32) converters['J' + BE] = tmp;
// unsigned int, native
tmp = new Converter(4, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, Platform.BYTE_ORDER == Platform.BIG_ENDIAN ?
decodeIntUnsignedBigEndian(enc) : decodeIntUnsignedLittleEndian(enc));
}
public void encode(ThreadContext context, IRubyObject o, ByteList result){
int s = o == context.nil ? 0 : (int) toLong(context, o);
packInt_i(result, s);
}
};
converters['I'] = tmp; // unsigned int, native
converters['L'] = tmp; // unsigned long, native
if (Platform.BIT_WIDTH == 32) converters['J'] = tmp; // unsigned long, native
// int, native
tmp = new Converter(4, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, unpackInt_i(enc));
}
public void encode(ThreadContext context, IRubyObject o, ByteList result){
int s = o == context.nil ? 0 : (int) toLong(context, o);
packInt_i(result, s);
}
};
converters['i'] = tmp; // int, native
converters['l'] = tmp; // long, native
if (Platform.BIT_WIDTH == 32) converters['j'] = tmp; // long, native
// int, little endian
tmp = new Converter(4, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, decodeIntLittleEndian(enc));
}
public void encode(ThreadContext context, IRubyObject o, ByteList result){
int s = o == context.nil ? 0 : (int) toLong(context, o);
encodeIntLittleEndian(result, s);
}
};
converters['i' + LE] = tmp; // int, native
converters['l' + LE] = tmp; // long, native
if (Platform.BIT_WIDTH == 32) converters['j' + LE] = tmp; // long, native
// int, big endian
tmp = new Converter(4, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, decodeIntBigEndian(enc));
}
public void encode(ThreadContext context, IRubyObject o, ByteList result){
int s = o == context.nil ? 0 : (int) toLong(context, o);
encodeIntBigEndian(result, s);
}
};
converters['i' + BE] = tmp; // int, native
converters['l' + BE] = tmp; // long, native
if (Platform.BIT_WIDTH == 32) converters['j' + BE] = tmp; // long, native
// 64-bit number, native (as bignum)
tmp = new QuadConverter(8, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
long l = Platform.BYTE_ORDER == Platform.BIG_ENDIAN ? decodeLongBigEndian(enc) : decodeLongLittleEndian(enc);
return RubyBignum.bignorm(context.runtime,BigInteger.valueOf(l).and(new BigInteger("FFFFFFFFFFFFFFFF", 16)));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeLongByByteOrder(result, num2quad(context, o));
}
};
converters['Q'] = tmp;
if (Platform.BIT_WIDTH == 64) converters['J'] = tmp;
// 64-bit number, little endian (as bignum)
tmp = new QuadConverter(8, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
long l = decodeLongLittleEndian(enc);
return RubyBignum.bignorm(context.runtime,BigInteger.valueOf(l).and(new BigInteger("FFFFFFFFFFFFFFFF", 16)));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeLongLittleEndian(result, num2quad(context, o));
}
};
converters['Q' + LE] = tmp;
if (Platform.BIT_WIDTH == 64) converters['J' + LE] = tmp;
// 64-bit number, big endian (as bignum)
tmp = new QuadConverter(8, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
long l = decodeLongBigEndian(enc);
return RubyBignum.bignorm(context.runtime,BigInteger.valueOf(l).and(new BigInteger("FFFFFFFFFFFFFFFF", 16)));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeLongBigEndian(result, num2quad(context, o));
}
};
converters['Q' + BE] = tmp;
if (Platform.BIT_WIDTH == 64) converters['J' + BE] = tmp;
// 64-bit number, native (as fixnum)
tmp = new QuadConverter(8, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, Platform.BYTE_ORDER == Platform.BIG_ENDIAN ?
decodeLongBigEndian(enc) : decodeLongLittleEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeLongByByteOrder(result, num2quad(context, o));
}
};
converters['q'] = tmp;
if (Platform.BIT_WIDTH == 64) converters['j'] = tmp;
// 64-bit number, little-endian (as fixnum)
tmp = new QuadConverter(8, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, decodeLongLittleEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeLongLittleEndian(result, num2quad(context, o));
}
};
converters['q' + LE] = tmp;
if (Platform.BIT_WIDTH == 64) converters['j' + LE] = tmp;
// 64-bit number, big-endian (as fixnum)
tmp = new QuadConverter(8, "Integer") {
public IRubyObject decode(ThreadContext context, ByteBuffer enc) {
return asFixnum(context, decodeLongBigEndian(enc));
}
@Override
public void encode(ThreadContext context, IRubyObject o, ByteList result){
encodeLongBigEndian(result, num2quad(context, o));
}
};
converters['q' + BE] = tmp;
if (Platform.BIT_WIDTH == 64) converters['j' + BE] = tmp;
// pointer; we can't provide a real pointer, so we just use identity hashcode
tmp = new QuadConverter(8) {
@Override
public IRubyObject decode(ThreadContext context, ByteBuffer format) {
return context.nil;
}
@Override
public void encode(ThreadContext context, IRubyObject from, ByteList result) {
if (from.isNil()) {
encodeLongBigEndian(result, 0);
} else {
encodeLongBigEndian(result, System.identityHashCode(from));
}
}
};
converters['p'] = tmp;
// pointer; we can't provide a real pointer, so we just use identity hashcode
tmp = new QuadConverter(8) {
@Override
public IRubyObject decode(ThreadContext context, ByteBuffer format) {
return context.nil;
}
@Override
public void encode(ThreadContext context, IRubyObject from, ByteList result) {
if (from.isNil()) {
encodeLongBigEndian(result, 0);
} else {
encodeLongBigEndian(result, System.identityHashCode(from.convertToString()));
}
}
};
converters['P'] = tmp;
}
public static int unpackInt_i(ByteBuffer enc) {
int value;
if (Platform.BYTE_ORDER == Platform.BIG_ENDIAN) {
value = decodeIntBigEndian(enc);
} else {
value = decodeIntLittleEndian(enc);
}
return value;
}
public static ByteList packInt_i(ByteList result, int s) {
if (Platform.BYTE_ORDER == Platform.BIG_ENDIAN) {
encodeIntBigEndian(result, s);
} else {
encodeIntLittleEndian(result, s);
}
return result;
}
private static void encodeUM(ThreadContext context, ByteList lCurElemString, int occurrences, boolean ignoreStar, char type, ByteList result) {
if (occurrences == 0 && type == 'm' && !ignoreStar) {
encodes(context, result, lCurElemString.getUnsafeBytes(),
lCurElemString.getBegin(), lCurElemString.length(),
lCurElemString.length(), (byte) type, false);
return;
}
occurrences = occurrences <= 2 ? 45 : occurrences / 3 * 3;
if (lCurElemString.isEmpty()) return;
byte[] charsToEncode = lCurElemString.getUnsafeBytes();
for (int i = 0; i < lCurElemString.length(); i += occurrences) {
encodes(context, result, charsToEncode,
i + lCurElemString.getBegin(), lCurElemString.length() - i,
occurrences, (byte)type, true);
}
}
/**
* encodes a String in base64 or its uuencode variant.
* appends the result of the encoding in a StringBuffer
* @param io2Append The StringBuffer which should receive the result
* @param charsToEncode The String to encode
* @param startIndex
* @param length The max number of characters to encode
* @param charCount
* @param encodingType the type of encoding required (this is the same type as used by the pack method)
* @param tailLf true if the traililng "\n" is needed
* @return the io2Append buffer
**/
private static ByteList encodes(ThreadContext context, ByteList io2Append,byte[] charsToEncode, int startIndex,
int length, int charCount, byte encodingType, boolean tailLf) {
charCount = Math.min(charCount, length);
io2Append.ensure(charCount * 4 / 3 + 6);
int i = startIndex;
byte[] lTranslationTable = encodingType == 'u' ? uu_table : b64_table;
byte lPadding;
if (encodingType == 'u') {
if (charCount >= lTranslationTable.length) {
throw argumentError(context, charCount
+ " is not a correct value for the number of bytes per line in a u directive. Correct values range from 0 to "
+ lTranslationTable.length);
}
io2Append.append(lTranslationTable[charCount]);
lPadding = '`';
} else {
lPadding = '=';
}
while (charCount >= 3) {
byte lCurChar = charsToEncode[i++];
byte lNextChar = charsToEncode[i++];
byte lNextNextChar = charsToEncode[i++];
io2Append.append(lTranslationTable[077 & (lCurChar >>> 2)]);
io2Append.append(lTranslationTable[077 & (((lCurChar << 4) & 060) | ((lNextChar >>> 4) & 017))]);
io2Append.append(lTranslationTable[077 & (((lNextChar << 2) & 074) | ((lNextNextChar >>> 6) & 03))]);
io2Append.append(lTranslationTable[077 & lNextNextChar]);
charCount -= 3;
}
if (charCount == 2) {
byte lCurChar = charsToEncode[i++];
byte lNextChar = charsToEncode[i++];
io2Append.append(lTranslationTable[077 & (lCurChar >>> 2)]);
io2Append.append(lTranslationTable[077 & (((lCurChar << 4) & 060) | ((lNextChar >> 4) & 017))]);
io2Append.append(lTranslationTable[077 & (((lNextChar << 2) & 074) | (('\0' >> 6) & 03))]);
io2Append.append(lPadding);
} else if (charCount == 1) {
byte lCurChar = charsToEncode[i++];
io2Append.append(lTranslationTable[077 & (lCurChar >>> 2)]);
io2Append.append(lTranslationTable[077 & (((lCurChar << 4) & 060) | (('\0' >>> 4) & 017))]);
io2Append.append(lPadding);
io2Append.append(lPadding);
}
if (tailLf) {
io2Append.append('\n');
}
return io2Append;
}
public static RubyArray unpack(ThreadContext context, ByteList encodedString, ByteList formatString) {
return unpackWithBlock(context, RubyString.newStringLight(context.runtime, encodedString), formatString, Block.NULL_BLOCK);
}
/**
* @see Pack#unpackWithBlock(ThreadContext, RubyString, ByteList, Block)
* @param context
* @param encoded
* @param formatString
* @return unpacked array
*/
public static RubyArray unpack(ThreadContext context, RubyString encoded, ByteList formatString) {
return unpackWithBlock(context, encoded, formatString, Block.NULL_BLOCK);
}
/**
* Decodes <i>str</i> (which may contain binary data) according to the format
* string, returning an array of each value extracted.
* The format string consists of a sequence of single-character directives.<br>
* Each directive may be followed by a number, indicating the number of times to repeat with this directive. An asterisk (``<code>*</code>'') will use up all
* remaining elements. <br>
* Note that if passed a block, this method will return null and instead yield results to the block.
* The directives <code>sSiIlL</code> may each be followed by an underscore (``<code>_</code>'') to use the underlying platform's native size for the specified type; otherwise, it uses a platform-independent consistent size. <br>
* Spaces are ignored in the format string.
*
* <table border="1"><caption style="display:none">layout table</caption>
* <tr>
* <td>
* <P></P>
* <b>Directives for <a href="ref_c_string.html#String.unpack">
* <code>String#unpack</code>
* </a>
* </b> <table class="codebox"><caption style="display:none">layout table</caption>
* <tr>
* <td>
* <b>Format</b>
* </td>
* <td>
* <b>Function</b>
* </td>
* <td>
* <b>Returns</b>
* </td>
* </tr>
* <tr>
* <td>A</td>
* <td>String with trailing nulls and spaces removed.</td>
* <td>String</td>
* </tr>
* <tr>
* <td>a</td>
* <td>String.</td>
* <td>String</td>
* </tr>
* <tr>
* <td>B</td>
* <td>Extract bits from each character (msb first).</td>
* <td>String</td>
* </tr>
* <tr>
* <td>b</td>
* <td>Extract bits from each character (lsb first).</td>
* <td>String</td>
* </tr>
* <tr>
* <td>C</td>
* <td>Extract a character as an unsigned integer.</td>
* <td>Fixnum</td>
* </tr>
* <tr>
* <td>c</td>
* <td>Extract a character as an integer.</td>
* <td>Fixnum</td>
* </tr>
* <tr>
* <td>d</td>
* <td>Treat <em>sizeof(double)</em> characters as a native
* double.</td>
* <td>Float</td>
* </tr>
* <tr>
* <td>E</td>
* <td>Treat <em>sizeof(double)</em> characters as a double in
* little-endian byte order.</td>
* <td>Float</td>
* </tr>
* <tr>
* <td>e</td>
* <td>Treat <em>sizeof(float)</em> characters as a float in
* little-endian byte order.</td>
* <td>Float</td>
* </tr>
* <tr>
* <td>f</td>
* <td>Treat <em>sizeof(float)</em> characters as a native float.</td>
* <td>Float</td>
* </tr>
* <tr>
* <td>G</td>
* <td>Treat <em>sizeof(double)</em> characters as a double in
* network byte order.</td>
* <td>Float</td>
* </tr>
* <tr>
* <td>g</td>
* <td>Treat <em>sizeof(float)</em> characters as a float in
* network byte order.</td>
* <td>Float</td>
* </tr>
* <tr>
* <td>H</td>
* <td>Extract hex nibbles from each character (most
* significant first).</td>
* <td>String</td>
* </tr>
* <tr>
* <td>h</td>
* <td>Extract hex nibbles from each character (least
* significant first).</td>
* <td>String</td>
* </tr>
* <tr>
* <td>I</td>
* <td>Treat <em>sizeof(int)</em>
* <sup>1</sup> successive
* characters as an unsigned native integer.</td>
* <td>Integer</td>
* </tr>
* <tr>
* <td>i</td>
* <td>Treat <em>sizeof(int)</em>
* <sup>1</sup> successive
* characters as a signed native integer.</td>
* <td>Integer</td>
* </tr>
* <tr>
* <td>L</td>
* <td>Treat four<sup>1</sup> successive
* characters as an unsigned native
* long integer.</td>
* <td>Integer</td>
* </tr>
* <tr>
* <td>l</td>
* <td>Treat four<sup>1</sup> successive
* characters as a signed native
* long integer.</td>
* <td>Integer</td>
* </tr>
* <tr>
* <td>M</td>
* <td>Extract a quoted-printable string.</td>
* <td>String</td>
* </tr>
* <tr>
* <td>m</td>
* <td>Extract a base64 encoded string.</td>
* <td>String</td>
* </tr>
* <tr>
* <td>N</td>
* <td>Treat four characters as an unsigned long in network
* byte order.</td>
* <td>Fixnum</td>
* </tr>
* <tr>
* <td>n</td>
* <td>Treat two characters as an unsigned short in network
* byte order.</td>
* <td>Fixnum</td>
* </tr>
* <tr>
* <td>P</td>
* <td>Treat <em>sizeof(char *)</em> characters as a pointer, and
* return <em>len</em> characters from the referenced location.</td>
* <td>String</td>
* </tr>
* <tr>
* <td>p</td>
* <td>Treat <em>sizeof(char *)</em> characters as a pointer to a
* null-terminated string.</td>
* <td>String</td>
* </tr>
* <tr>
* <td>S</td>
* <td>Treat two<sup>1</sup> successive characters as an unsigned
* short in
* native byte order.</td>
* <td>Fixnum</td>
* </tr>
* <tr>
* <td>s</td>
* <td>Treat two<sup>1</sup> successive
* characters as a signed short in
* native byte order.</td>
* <td>Fixnum</td>
* </tr>
* <tr>
* <td>U</td>
* <td>Extract UTF-8 characters as unsigned integers.</td>
* <td>Integer</td>
* </tr>
* <tr>
* <td>u</td>
* <td>Extract a UU-encoded string.</td>
* <td>String</td>
* </tr>
* <tr>
* <td>V</td>
* <td>Treat four characters as an unsigned long in little-endian
* byte order.</td>
* <td>Fixnum</td>
* </tr>
* <tr>
* <td>v</td>
* <td>Treat two characters as an unsigned short in little-endian
* byte order.</td>
* <td>Fixnum</td>
* </tr>
* <tr>
* <td>X</td>
* <td>Skip backward one character.</td>
* <td>---</td>
* </tr>
* <tr>
* <td>x</td>
* <td>Skip forward one character.</td>
* <td>---</td>
* </tr>
* <tr>
* <td>Z</td>
* <td>String with trailing nulls removed.</td>
* <td>String</td>
* </tr>
* <tr>
* <td>@</td>
* <td>Skip to the offset given by the length argument.</td>
* <td>---</td>
* </tr>
* <tr>
* <td colspan="9"><img alt="bullet" src="dot.gif" width="1" height="1"></td>
* </tr>
* </table>
* <P></P>
* <sup>1</sup> May be modified by appending ``_'' to the directive.
* <P></P>
* </td>
* </tr>
* </table>
*
* @see RubyArray#pack
**/
public static RubyArray unpackWithBlock(ThreadContext context, RubyString encoded, ByteList formatString, Block block) {
return (RubyArray) unpackInternal(context, encoded, formatString, block.isGiven() ? UNPACK_BLOCK : UNPACK_ARRAY, 0, block);
}
public static RubyArray unpackWithBlock(ThreadContext context, RubyString encoded, ByteList formatString, long offset, Block block) {
return (RubyArray) unpackInternal(context, encoded, formatString, block.isGiven() ? UNPACK_BLOCK : UNPACK_ARRAY, offset, block);
}
private static RubyString unpackBase46Strict(ThreadContext context, ByteList input) {
int index = 0; // current index of out
int s = -1;
int a = -1;
int b = -1;
int c = 0;
byte[] buf = input.unsafeBytes();
int begin = input.begin();
int length = input.realSize();
int end = begin + length;
if (length % 4 != 0) throw argumentError(context, "invalid base64");
int p = begin;
byte[] out = new byte[3 * ((length + 3) / 4)];
while (p < end && s != '=') {
// obtain a
s = buf[p++];
a = b64_xtable[s];
if (a == -1) throw argumentError(context, "invalid base64");
// obtain b
s = buf[p++];
b = b64_xtable[s];
if (b == -1) throw argumentError(context, "invalid base64");
// obtain c
s = buf[p++];
c = b64_xtable[s];
if (s == '=') {
if (buf[p++] != '=') throw argumentError(context, "invalid base64");
break;
}
if (c == -1) throw argumentError(context, "invalid base64");
// obtain d
s = buf[p++];
int d = b64_xtable[s];
if (s == '=') break;
if (d == -1) throw argumentError(context, "invalid base64");
// calculate based on a, b, c and d
out[index++] = (byte) (a << 2 | b >> 4);
out[index++] = (byte) (b << 4 | c >> 2);
out[index++] = (byte) (c << 6 | d);
}
if (p < end) throw argumentError(context, "invalid base64");
if (a != -1 && b != -1) {
if (c == -1 && s == '=') {
if ((b & 15) > 0) throw argumentError(context, "invalid base64");
out[index++] = (byte)((a << 2 | b >> 4) & 255);
} else if(c != -1 && s == '=') {
if ((c & 3) > 0) throw argumentError(context, "invalid base64");
out[index++] = (byte)((a << 2 | b >> 4) & 255);
out[index++] = (byte)((b << 4 | c >> 2) & 255);
}
}
return newString(context, new ByteList(out, 0, index));
}
public static IRubyObject unpack1WithBlock(ThreadContext context, RubyString encoded, ByteList formatString, Block block) {
return unpack1WithBlock(context, encoded, formatString, 0, block);
}
public static IRubyObject unpack1WithBlock(ThreadContext context, RubyString encoded, ByteList formatString, long offset, Block block) {
int formatLength = formatString.realSize();
// Strict m0 is commmonly used in cookie handling so it has a fast path.
if (formatLength >= 1) {
byte first = (byte) (formatString.get(0) & 0xff);
if (first == 'm') {
if (formatLength == 2) {
byte second = (byte) (formatString.get(1) & 0xff);
if (second == '0') return unpackBase46Strict(context, encoded.getByteList());
}
}
}
return unpackInternal(context, encoded, formatString, UNPACK_1, offset, block);
}
private static IRubyObject unpackInternal(ThreadContext context, RubyString encoded, ByteList formatString, int mode, long offset, Block block) {
final var result = mode == UNPACK_BLOCK || mode == UNPACK_1 ? null : newArray(context);
final ByteList encodedString = encoded.getByteList();
int len = encodedString.realSize();
int beg = encodedString.begin();
if (offset < 0) throw argumentError(context, "offset can't be negative");
if (offset > 0) {
if (offset > len) throw argumentError(context, "offset outside of string");
beg += offset;
len -= offset;
}
// FIXME: potentially could just use ByteList here?
ByteBuffer format = ByteBuffer.wrap(formatString.getUnsafeBytes(), formatString.begin(), formatString.length());
ByteBuffer encode = ByteBuffer.wrap(encodedString.getUnsafeBytes(), beg, len);
int next = getDirective(context, "unpack", formatString, format);
IRubyObject value = null; // UNPACK_1
mainLoop: while (next != 0) {
int type = next;
next = getDirective(context, "unpack", formatString, format);
if (isSpace(type)) continue;
if (type == '#') {
type = skipToEOL(format);
if (type == 0) break; // exit on EOF
next = getDirective(context, "unpack", formatString, format);
continue; // continue after newline
}
// Next indicates to decode using native encoding format
if (next == '_' || next == '!') {
int index = NATIVE_CODES.indexOf(type);
if (index == -1) {
throw argumentError(context, "'" + next + "' allowed only after types " + NATIVE_CODES);