-
-
Notifications
You must be signed in to change notification settings - Fork 938
Expand file tree
/
Copy pathRubyIOBuffer.java
More file actions
2247 lines (1743 loc) · 80 KB
/
RubyIOBuffer.java
File metadata and controls
2247 lines (1743 loc) · 80 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
package org.jruby;
import jnr.ffi.NativeType;
import jnr.ffi.Platform;
import jnr.ffi.Runtime;
import jnr.ffi.Type;
import org.jcodings.Encoding;
import org.jcodings.specific.ASCIIEncoding;
import org.jruby.anno.JRubyConstant;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.io.ChannelFD;
import org.jruby.util.io.OpenFile;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import static org.jruby.api.Access.encodingService;
import static org.jruby.api.Convert.*;
import static org.jruby.api.Create.*;
import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.api.Warn.warnExperimental;
public class RubyIOBuffer extends RubyObject {
private static final BigInteger MIN_S128 = BigInteger.ONE.shiftLeft(127).negate();
private static final BigInteger MAX_S128 = BigInteger.ONE.shiftLeft(127).subtract(BigInteger.ONE);
public static RubyClass createIOBufferClass(ThreadContext context, RubyClass Object, RubyModule Comparable, RubyClass IO) {
RubyClass IOBuffer = IO.defineClassUnder(context, "Buffer", Object, RubyIOBuffer::new).
include(context, Comparable).
defineMethods(context, RubyIOBuffer.class).
defineConstants(context, RubyIOBuffer.class);
return IOBuffer;
}
@JRubyConstant
public static final int PAGE_SIZE = 8196;
@JRubyConstant
public static final int DEFAULT_SIZE = 8196;
@JRubyConstant
public static final int EXTERNAL = 1;
@JRubyConstant
public static final int INTERNAL = 2;
@JRubyConstant
public static final int MAPPED = 4;
@JRubyConstant
public static final int SHARED = 8;
@JRubyConstant
public static final int LOCKED = 32;
@JRubyConstant
public static final int PRIVATE = 64;
@JRubyConstant
public static final int READONLY = 128;
@JRubyConstant
public static final int LITTLE_ENDIAN = 4;
@JRubyConstant
public static final int BIG_ENDIAN = 8;
@JRubyConstant
public static final int HOST_ENDIAN = Platform.getNativePlatform().isBigEndian() ? BIG_ENDIAN : LITTLE_ENDIAN;
@JRubyConstant
public static final int NETWORK_ENDIAN = BIG_ENDIAN;
public static RubyIOBuffer newBuffer(ThreadContext context, ByteBuffer base, int size, int flags) {
if (base == null) return newBuffer(context.runtime, size, flags);
return new RubyIOBuffer(context.runtime, context.runtime.getIOBuffer(), base, size, flags);
}
public static RubyIOBuffer newBuffer(Ruby runtime, ByteBuffer base, int size, int flags) {
if (base == null) return newBuffer(runtime, size, flags);
return new RubyIOBuffer(runtime, runtime.getIOBuffer(), base, size, flags);
}
public static RubyIOBuffer newBuffer(Ruby runtime, int size, int flags) {
return new RubyIOBuffer(runtime, runtime.getIOBuffer(), newBufferBase(runtime, size, flags), size, flags);
}
public static RubyIOBuffer newBuffer(ThreadContext context, RubyString string, int flags) {
ByteList bytes = string.getByteList();
int size = bytes.realSize();
return newBuffer(context, ByteBuffer.wrap(bytes.unsafeBytes(), bytes.begin(), size), size, flags);
}
public RubyIOBuffer(Ruby runtime, RubyClass metaClass) {
super(runtime, metaClass);
}
public RubyIOBuffer(Ruby runtime, RubyClass metaClass, ByteBuffer base, int size, int flags) {
super(runtime, metaClass);
this.base = base;
this.size = size;
this.flags = flags;
}
@JRubyMethod(name = "for", meta = true)
public static IRubyObject rbFor(ThreadContext context, IRubyObject self, IRubyObject _string, Block block) {
RubyString string = _string.convertToString();
int flags = string.isFrozen() ? READONLY : 0;
// If the string is frozen, both code paths are okay.
// If the string is not frozen, if a block is not given, it must be frozen.
if (!block.isGiven()) {
// This internally returns the source string if it's already frozen.
string = string.newFrozen();
flags = READONLY;
} else {
if ((flags & READONLY) != READONLY) {
string.modify();
}
}
RubyIOBuffer buffer = newBuffer(context, string, flags);
if (block.isGiven()) {
return block.yieldSpecific(context, buffer);
}
return buffer;
}
@JRubyMethod(meta = true)
public static IRubyObject string(ThreadContext context, IRubyObject self, IRubyObject _length, Block block) {
int size = toInt(context, _length);
if (size < 0) throw argumentError(context, "negative string size (or size too big)");
RubyString string = newString(context, new byte[size]);
ByteList bytes = string.getByteList();
ByteBuffer wrap = ByteBuffer.wrap(bytes.unsafeBytes(), bytes.begin(), size);
RubyIOBuffer buffer = newBuffer(context, wrap, size, 0);
block.yieldSpecific(context, buffer);
return string;
}
@JRubyMethod(name = "map", meta = true)
public static IRubyObject map(ThreadContext context, IRubyObject self, IRubyObject _file) {
RubyFile file = checkFile(context, _file);
int size = getSizeFromFile(context, file);
return map(context, file, size, 0, 0);
}
private static RubyFile checkFile(ThreadContext context, IRubyObject _file) {
RubyIO io = RubyIO.convertToIO(context, _file);
if (!(io instanceof RubyFile)) throw typeError(context, _file, "File");
return (RubyFile) io;
}
@JRubyMethod(name = "map", meta = true)
public static IRubyObject map(ThreadContext context, IRubyObject self, IRubyObject _file, IRubyObject _size) {
RubyFile file = checkFile(context, _file);
int size = getSizeForMap(context, file, _size);
return map(context, file, size, 0, 0);
}
@JRubyMethod(name = "map", meta = true)
public static IRubyObject map(ThreadContext context, IRubyObject self, IRubyObject _file, IRubyObject _size, IRubyObject _offset) {
RubyFile file = checkFile(context, _file);
int size = getSizeForMap(context, file, _size);
// This is the file offset, not the buffer offset:
int offset = toInt(context, _offset);
return map(context, file, size, offset, 0);
}
private static int getSizeForMap(ThreadContext context, RubyFile file, IRubyObject _size) {
int size;
if (!_size.isNil()) {
size = extractSize(context, _size);
} else {
size = getSizeFromFile(context, file);
}
return size;
}
private static int getSizeFromFile(ThreadContext context, RubyFile _file) {
long file_size = _file.getSize(context);
if (file_size < 0) throw argumentError(context, "Invalid negative file size!");
// Here, we assume that file_size is positive:
if (file_size > Integer.MAX_VALUE) throw argumentError(context, "File larger than address space!");
// This conversion should be safe:
return (int) file_size;
}
@JRubyMethod(name = "map", required = 1, optional = 3, meta = true)
public static IRubyObject map(ThreadContext context, IRubyObject self, IRubyObject[] args) {
ioBufferExperimental(context);
switch (args.length) {
case 1:
return map(context, self, args[0]);
case 2:
return map(context, self, args[0], args[1]);
case 3:
return map(context, self, args[0], args[1], args[2]);
case 4:
return map(context, self, args[0], args[1], args[2], args[3]);
}
return context.nil;
}
public static IRubyObject map(ThreadContext context, IRubyObject self, IRubyObject _file, IRubyObject _size, IRubyObject _offset, IRubyObject _flags) {
RubyFile file = checkFile(context, _file);
int size = getSizeForMap(context, file, _size);
// This is the file offset, not the buffer offset:
int offset = toInt(context, _offset);
int flags = toInt(context, _flags);
return map(context, file, size, offset, flags);
}
private static RubyIOBuffer map(ThreadContext context, RubyFile file, int size, int offset, int flags) {
RubyIOBuffer buffer = new RubyIOBuffer(context.runtime, context.runtime.getIOBuffer());
ChannelFD descriptor = file.getOpenFileChecked().fd();
mapFile(context, buffer, descriptor, size, offset, flags);
return buffer;
}
private static void mapFile(ThreadContext context, RubyIOBuffer buffer, ChannelFD descriptor, int size, int offset, int flags) {
FileChannel.MapMode protect = FileChannel.MapMode.READ_ONLY;
int access = 0;
if ((flags & READONLY) == READONLY) {
buffer.flags |= READONLY;
} else {
protect = FileChannel.MapMode.READ_WRITE;
}
if ((flags & PRIVATE) == PRIVATE) {
buffer.flags |= PRIVATE;
protect = FileChannel.MapMode.PRIVATE;
} else {
// This buffer refers to external buffer.
buffer.flags |= EXTERNAL;
buffer.flags |= SHARED;
}
if (descriptor.chFile == null) throw typeError(context, "Cannot map non-file resource: " + descriptor.ch);
ByteBuffer base;
try {
base = descriptor.chFile.map(protect, offset, size);
} catch (IOException ioe) {
throw Helpers.newIOErrorFromException(context.runtime, ioe);
}
buffer.base = base;
buffer.size = size;
buffer.flags |= MAPPED;
}
public static IRubyObject map(ThreadContext context, IRubyObject self, RubyFile _file, int _size, int _offset, int _flags) {
return context.nil;
}
@JRubyMethod(name = "initialize")
public IRubyObject initialize(ThreadContext context) {
return initialize(context, DEFAULT_SIZE);
}
@JRubyMethod(name = "initialize")
public IRubyObject initialize(ThreadContext context, IRubyObject size) {
return initialize(context, toInt(context, size));
}
@JRubyMethod(name = "initialize")
public IRubyObject initialize(ThreadContext context, IRubyObject _size, IRubyObject flags) {
int size = toInt(context, _size);
initialize(context, new byte[size], size, toInt(context, flags), context.nil);
return context.nil;
}
public IRubyObject initialize(ThreadContext context, int size) {
initialize(context, new byte[size], size, flagsForSize(size), context.nil);
return context.nil;
}
// MRI: io_buffer_initialize
public void initialize(ThreadContext context, byte[] baseBytes, int size, int flags, IRubyObject source) {
ioBufferExperimental(context);
ByteBuffer base = null;
if (baseBytes != null) {
// If we are provided a pointer, we use it.
base = ByteBuffer.wrap(baseBytes);
} else if (size != 0) {
base = newBufferBase(context.runtime, size, flags);
} else {
// Otherwise we don't do anything.
return;
}
this.base = base;
this.size = size;
this.flags = flags;
this.source = source.isNil() ? null : source;
}
static boolean warned = false;
private static void ioBufferExperimental(ThreadContext context) {
if (warned) return;
warned = true;
warnExperimental(context, "IO::Buffer is experimental and both the Ruby and native interface may change in the future!");
}
private static ByteBuffer newBufferBase(Ruby runtime, int size, int flags) {
ByteBuffer base;
// If we are provided a non-zero size, we allocate it:
if ((flags & INTERNAL) == INTERNAL) {
base = ByteBuffer.allocate(size);
} else if ((flags & MAPPED) == MAPPED) {
// no support for SHARED, PRIVATE yet
base = ByteBuffer.allocateDirect(size);
} else {
throw runtime.newBufferAllocationError("Could not allocate buffer!");
}
return base;
}
// MRI: io_flags_for_size
private static int flagsForSize(int size) {
if (size >= PAGE_SIZE) {
return MAPPED;
}
return INTERNAL;
}
@JRubyMethod(name = "initialize_copy")
public IRubyObject initialize_copy(ThreadContext context, IRubyObject other) {
RubyIOBuffer otherBuffer = (RubyIOBuffer) other;
ByteBuffer sourceBase = otherBuffer.getBufferForReading(context);
int sourceSize = otherBuffer.size;
initialize(context, null, sourceSize, flagsForSize(size), context.nil);
return copy(context, otherBuffer, 0, sourceSize, 0);
}
@JRubyMethod(name = "inspect")
public IRubyObject inspect(ThreadContext context) {
RubyString result = to_s(context);
if (validate()) {
// Limit the maximum size genearted by inspect.
if (size <= 256) {
hexdump(context, result, 16, base, size, false);
}
}
return result;
}
private boolean validate() {
if (source != null) {
return validateSlice(source, base, size);
}
return true;
}
private boolean validateSlice(IRubyObject source, ByteBuffer base, int size) {
ByteBuffer sourceBase = null;
int sourceSize = 0;
if (source instanceof RubyString) {
ByteList sourceBytes = ((RubyString) source).getByteList();
sourceSize = sourceBytes.getRealSize();
sourceBase = ByteBuffer.wrap(sourceBytes.getUnsafeBytes(), sourceBytes.begin(), sourceSize);
} else {
RubyIOBuffer sourceBuffer = (RubyIOBuffer) source;
sourceBase = sourceBuffer.base;
sourceSize = sourceBuffer.size;
}
// Source is invalid:
if (sourceBase == null) return false;
// Base is out of range:
if (base.hasArray() && sourceBase.hasArray() && base.array() != sourceBase.array()) return false;
int sourceEnd = sourceSize;
int end = size;
// End is out of range:
if (end > sourceEnd) return false;
// It seems okay:
return true;
}
@JRubyMethod(name = "hexdump")
public IRubyObject hexdump(ThreadContext context) {
ByteBuffer base = this.base;
int size = this.size;
if (validate() && base != null) {
RubyString result = RubyString.newStringLight(context.runtime, size * 3 + (size / 16) * 12 + 1);
hexdump(context, result, 16, base, size, true);
return result;
}
return context.nil;
}
private static RubyString hexdump(ThreadContext context, RubyString string, int width, ByteBuffer base, int size, boolean first) {
byte[] text = new byte[width+1];
text[width] = '\0';
for (int offset = 0; offset < size; offset += width) {
Arrays.fill(text, (byte) 0);
if (first) {
string.cat("0x".getBytes());
String hex = String.format("0x%08x ", offset);
string.cat(hex.getBytes());
first = false;
} else {
string.cat(String.format("\n0x%08x ", offset).getBytes());
}
for (int i = 0; i < width; i += 1) {
if (offset+i < size) {
int value = Byte.toUnsignedInt(base.get(offset+i));
if (value < 127 && value >= 32) {
text[i] = (byte)value;
}
else {
text[i] = '.';
}
string.cat(String.format("%02x", value).getBytes());
}
else {
string.cat(" ".getBytes());
}
}
string.cat(' ');
string.cat(text);
}
return string;
}
@JRubyMethod(name = "to_s")
public RubyString to_s(ThreadContext context) {
RubyString result = newString(context, "#<");
result.append(getMetaClass().name(context));
result.cat(String.format(" %d+%d", System.identityHashCode(base), size).getBytes());
if (base == null) result.cat(" NULL".getBytes());
if (isExternal()) result.cat(" EXTERNAL".getBytes());
if (isInternal()) result.cat(" INTERNAL".getBytes());
if (isMapped()) result.cat(" MAPPED".getBytes());
if (isShared()) result.cat(" SHARED".getBytes());
if (isLocked()) result.cat(" LOCKED".getBytes());
if (isReadonly()) result.cat(" READONLY".getBytes());
if (source != null) result.cat(" SLICE".getBytes());
if (!validate()) result.cat(" INVALID".getBytes());
return result.cat(">".getBytes());
}
@JRubyMethod(name = "size")
public IRubyObject size(ThreadContext context) {
return asFixnum(context, size);
}
@JRubyMethod(name = "valid?")
public IRubyObject valid_p(ThreadContext context) {
return asBoolean(context, validate());
}
@JRubyMethod(name = "transfer")
public IRubyObject transfer(ThreadContext context) {
if (isLocked()) {
throw context.runtime.newBufferLockedError("Cannot transfer ownership of locked buffer!");
}
RubyIOBuffer instance = new RubyIOBuffer(context.runtime, getMetaClass());
instance.base = base;
instance.size = size;
instance.flags = flags;
instance.source = source;
zero(context);
return instance;
}
private void zero(ThreadContext context) {
base = null;
size = 0;
source = null;
}
@JRubyMethod(name = "null?")
public IRubyObject null_p(ThreadContext context) {
return asBoolean(context, base == null);
}
@JRubyMethod(name = "empty?")
public IRubyObject empty_p(ThreadContext context) {
return asBoolean(context, size == 0);
}
@JRubyMethod(name = "external?")
public IRubyObject external_p(ThreadContext context) {
return asBoolean(context, isExternal());
}
private boolean isExternal() {
return (flags & EXTERNAL) == EXTERNAL;
}
@JRubyMethod(name = "internal?")
public IRubyObject internal_p(ThreadContext context) {
return asBoolean(context, isInternal());
}
private boolean isInternal() {
return (flags & INTERNAL) == INTERNAL;
}
@JRubyMethod(name = "mapped?")
public IRubyObject mapped_p(ThreadContext context) {
return asBoolean(context, isMapped());
}
private boolean isMapped() {
return (flags & MAPPED) == MAPPED;
}
@JRubyMethod(name = "shared?")
public IRubyObject shared_p(ThreadContext context) {
// no support for shared yet
return asBoolean(context, false);
}
private boolean isShared() {
return (flags & SHARED) == SHARED;
}
@JRubyMethod(name = "locked?")
public IRubyObject locked_p(ThreadContext context) {
return asBoolean(context, isLocked());
}
private boolean isLocked() {
return (flags & LOCKED) == LOCKED;
}
@JRubyMethod(name = "readonly?")
public IRubyObject readonly_p(ThreadContext context) {
return asBoolean(context, isReadonly());
}
private boolean isReadonly() {
return (flags & READONLY) == READONLY;
}
@JRubyMethod(name = "locked")
public IRubyObject locked(ThreadContext context, Block block) {
checkLocked(context);
flags |= LOCKED;
IRubyObject result = block.yield(context, this);
flags &= ~LOCKED;
return result;
}
private void checkLocked(ThreadContext context) {
if (isLocked()) {
throw context.runtime.newBufferLockedError("Buffer already locked!");
}
}
public IRubyObject lock(ThreadContext context) {
checkLocked(context);
flags |= LOCKED;
return this;
}
public IRubyObject unlock(ThreadContext context) {
if ((flags & LOCKED) == 0) {
throw context.runtime.newBufferLockedError("Buffer not locked!");
}
flags &= ~LOCKED;
return this;
}
private boolean tryUnlock() {
if (isLocked()) {
flags &= ~LOCKED;
return true;
}
return false;
}
@JRubyMethod(name = "slice")
public IRubyObject slice(ThreadContext context) {
return slice(context, 0, size);
}
@JRubyMethod(name = "slice")
public IRubyObject slice(ThreadContext context, IRubyObject _offset) {
int offset = toInt(context, _offset);
if (offset < 0) throw argumentError(context, "Offset can't be negative!");
return slice(context, offset, size - offset);
}
@JRubyMethod(name = "slice")
public IRubyObject slice(ThreadContext context, IRubyObject _offset, IRubyObject _length) {
int offset = toInt(context, _offset);
if (offset < 0) throw argumentError(context, "Offset can't be negative!");
int length = toInt(context, _length);
if (length < 0) throw argumentError(context, "Length can't be negative!");
return slice(context, offset, length);
}
// MRI: rb_io_buffer_slice
public IRubyObject slice(ThreadContext context, int offset, int length) {
validateRange(context, offset, length);
// gross, but slice(int, int) is 13+
base.position(offset);
base.limit(offset + length);
ByteBuffer slice = base.slice();
base.clear();
return newBuffer(context, slice, length, flags);
}
// MRI: io_buffer_validate_range
private void validateRange(ThreadContext context, int offset, int length) {
if (offset + length > size) throw argumentError(context, "Specified offset+length is bigger than the buffer size!");
}
@JRubyMethod(name = "<=>")
public IRubyObject op_cmp(ThreadContext context, IRubyObject other) {
return asFixnum(context, base.compareTo(((RubyIOBuffer) other).base));
}
@JRubyMethod(name = "resize")
public IRubyObject resize(ThreadContext context, IRubyObject size) {
resize(context, toInt(context, size));
return this;
}
// MRI: rb_io_buffer_resize
public void resize(ThreadContext context, int size) {
if (isLocked()) {
throw context.runtime.newBufferLockedError("Cannot resize locked buffer!");
}
if (this.base == null) {
initialize(context, null, size, flagsForSize(size), context.nil);
return;
}
if (isExternal()) {
throw context.runtime.newBufferAccessError("Cannot resize external buffer!");
}
// no special behavior for isInternal=true since we do not control the internals of ByteBuffers.
ByteBuffer newBase = this.base.isDirect() ? ByteBuffer.allocateDirect(size) : ByteBuffer.allocate(size);
this.base.limit(Math.min(size, this.base.capacity()));
newBase.put(this.base);
newBase.clear();
this.base = newBase;
this.size = size;
}
// MRI: io_buffer_clear
@JRubyMethod(name = "clear")
public IRubyObject clear(ThreadContext context) {
return clear(context, 0, 0, size);
}
@JRubyMethod(name = "clear")
public IRubyObject clear(ThreadContext context, IRubyObject value) {
return clear(context, toInt(context, value), 0, size);
}
@JRubyMethod(name = "clear")
public IRubyObject clear(ThreadContext context, IRubyObject _value, IRubyObject _offset) {
int value = toInt(context, _value);
int offset = toInt(context, _offset);
if (offset > size) throw argumentError(context, "The given offset is bigger than the buffer size!");
return clear(context, value, offset, size - offset);
}
@JRubyMethod(name = "clear")
public IRubyObject clear(ThreadContext context, IRubyObject _value, IRubyObject _offset, IRubyObject _length) {
int value = toInt(context, _value);
int offset = toInt(context, _offset);
int length = toInt(context, _length);
return clear(context, value, offset, length);
}
// MRI: rb_io_buffer_clear
private IRubyObject clear(ThreadContext context, int value, int offset, int length) {
ByteBuffer buffer = getBufferForWriting(context);
if (size - length < offset) throw argumentError(context, "The given offset + length out of bounds!");
if (buffer.hasArray()) Arrays.fill(buffer.array(), offset, offset + length, (byte) value);
return this;
}
private ByteBuffer getBufferForWriting(ThreadContext context) {
if (isReadonly()) {
throw context.runtime.newBufferAccessError("Buffer is not writable!");
}
// TODO: validate our buffer
if (base != null) {
return base;
}
throw context.runtime.newBufferAllocationError("The buffer is not allocated!");
}
private ByteBuffer getBufferForReading(ThreadContext context) {
// TODO: validate our buffer
if (base != null) {
return base;
}
throw context.runtime.newBufferAllocationError("The buffer is not allocated!");
}
@JRubyMethod(name = "free")
public IRubyObject free(ThreadContext context) {
if (isLocked()) {
throw context.runtime.newBufferLockedError("Buffer is locked!");
}
freeInternal(context);
return this;
}
private boolean freeInternal(ThreadContext context) {
if (this.base != null) {
// No special handling for internal yet
// No special handling for mapped yet
// We can only dereference and allow GC to clean it up
this.base = null;
this.size = 0;
this.flags = 0;
this.source = null;
return true;
}
return false;
}
@JRubyMethod(name = "size_of", meta = true)
public static IRubyObject size_of(ThreadContext context, IRubyObject self, IRubyObject dataType) {
long total;
if (dataType instanceof RubyArray array) {
total = 0;
int size = array.size();
for (int i = 0; i < size; i++) {
IRubyObject elt = array.eltOk(i);
total += getDataType(elt).size;
}
} else {
total = getDataType(dataType).size;
}
return asFixnum(context, total);
}
private boolean isBigEndian() {
return (flags & BIG_ENDIAN) == BIG_ENDIAN;
}
private boolean isLittleEndian() {
return (flags & LITTLE_ENDIAN) == LITTLE_ENDIAN;
}
private boolean isHostEndian() {
return (flags & (BIG_ENDIAN | LITTLE_ENDIAN)) == HOST_ENDIAN;
}
private static DataType getDataType(IRubyObject dataType) {
return DataType.valueOf(RubySymbol.objectToSymbolString(dataType));
}
private static byte readByte(ThreadContext context, ByteBuffer buffer, int offset) {
return buffer.get(offset);
}
private static int readUnsignedByte(ThreadContext context, ByteBuffer buffer, int offset) {
return Byte.toUnsignedInt(buffer.get(offset));
}
private static void writeByte(ThreadContext context, ByteBuffer buffer, int offset, byte value) {
buffer.put(offset, (byte) value);
}
private static void writeUnsignedByte(ThreadContext context, ByteBuffer buffer, int offset, int value) {
buffer.put(offset, (byte) value);
}
private static short readShort(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order) {
short s = buffer.getShort(offset);
if (order == ByteOrder.BIG_ENDIAN) return s;
return Short.reverseBytes(s);
}
private static int readUnsignedShort(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order) {
return Short.toUnsignedInt(readShort(context, buffer, offset, order));
}
private static void writeShort(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order, short value) {
if (order == ByteOrder.BIG_ENDIAN) {
buffer.putShort(offset, value);
return;
}
buffer.putShort(offset, Short.reverseBytes(value));
}
private static void writeUnsignedShort(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order, int value) {
writeShort(context, buffer, offset, order, (short) value);
}
private static int readInt(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order) {
int i = buffer.getInt(offset);
if (order == ByteOrder.BIG_ENDIAN) return i;
return Integer.reverseBytes(i);
}
private static long readUnsignedInt(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order) {
return Integer.toUnsignedLong(readInt(context, buffer, offset, order));
}
private static void writeInt(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order, int value) {
if (order == ByteOrder.BIG_ENDIAN) {
buffer.putInt(offset, value);
return;
}
buffer.putInt(offset, Integer.reverseBytes(value));
}
private static void writeUnsignedInt(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order, long value) {
writeInt(context, buffer, offset, order, (int) value);
}
private static long readLong(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order) {
long l = buffer.getLong(offset);
if (order == ByteOrder.BIG_ENDIAN) return l;
return Long.reverseBytes(l);
}
private static BigInteger readUnsignedLong(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order) {
long l = readLong(context, buffer, offset, order);
if (l > 0L) return BigInteger.valueOf(l);
byte[] bytes = new byte[8];
for (int i = 7; i >= 0; i--) {
bytes[i] = (byte)(l & 0xFF);
l >>= 8;
}
return new BigInteger(1, bytes);
}
private static void writeLong(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order, long value) {
if (order == ByteOrder.BIG_ENDIAN) {
buffer.putLong(offset, value);
return;
}
buffer.putLong(offset, Long.reverseBytes(value));
}
private static BigInteger readLongLong(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order) {
if (order == ByteOrder.BIG_ENDIAN) {
// Read 16 bytes (big-endian)
byte[] bytes = new byte[16];
for (int i = 0; i < 16; i++) {
bytes[i] = buffer.get(offset + i);
}
return new BigInteger(bytes);
}
byte[] bytes = new byte[16];
for (int i = 0; i < 16; i++) {
bytes[15 - i] = buffer.get(offset + i);
}
return new BigInteger(bytes);
}
private static BigInteger readUnsignedLongLong(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order) {
// Read 16 bytes (big-endian)
byte[] bytes = new byte[16];
buffer.get(offset, bytes);
if (order == ByteOrder.LITTLE_ENDIAN) {
reverseBytes(bytes);
}
return new BigInteger(1, bytes);
}
private static byte[] reverseBytes(byte[] bytes) {
for (int i = 0; i < bytes.length / 2; i++) {
byte tmp = bytes[i];
bytes[i] = bytes[bytes.length - i - 1];
bytes[bytes.length - i - 1] = tmp;
}
return bytes;
}
private static void writeUnsignedLongLong(ThreadContext context, ByteBuffer buffer, int offset, ByteOrder order, BigInteger value) {
if (value.signum() < 0) {
throw argumentError(context, "Value must be non-negative");
}
if (value.bitLength() > 128) {
throw argumentError(context, "Value exceeds 128 bits");
}