-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio_buffer.c
3786 lines (3196 loc) · 112 KB
/
io_buffer.c
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
/**********************************************************************
io_buffer.c
Copyright (C) 2021 Samuel Grant Dawson Williams
**********************************************************************/
#include "ruby/io.h"
#include "ruby/io/buffer.h"
#include "ruby/fiber/scheduler.h"
#include "internal.h"
#include "internal/array.h"
#include "internal/bits.h"
#include "internal/error.h"
#include "internal/numeric.h"
#include "internal/string.h"
#include "internal/thread.h"
VALUE rb_cIOBuffer;
VALUE rb_eIOBufferLockedError;
VALUE rb_eIOBufferAllocationError;
VALUE rb_eIOBufferAccessError;
VALUE rb_eIOBufferInvalidatedError;
VALUE rb_eIOBufferMaskError;
size_t RUBY_IO_BUFFER_PAGE_SIZE;
size_t RUBY_IO_BUFFER_DEFAULT_SIZE;
#ifdef _WIN32
#else
#include <unistd.h>
#include <sys/mman.h>
#endif
enum {
RB_IO_BUFFER_HEXDUMP_DEFAULT_WIDTH = 16,
RB_IO_BUFFER_INSPECT_HEXDUMP_MAXIMUM_SIZE = 256,
RB_IO_BUFFER_INSPECT_HEXDUMP_WIDTH = 16,
// This is used to validate the flags given by the user.
RB_IO_BUFFER_FLAGS_MASK = RB_IO_BUFFER_EXTERNAL | RB_IO_BUFFER_INTERNAL | RB_IO_BUFFER_MAPPED | RB_IO_BUFFER_SHARED | RB_IO_BUFFER_LOCKED | RB_IO_BUFFER_PRIVATE | RB_IO_BUFFER_READONLY,
RB_IO_BUFFER_DEBUG = 0,
};
struct rb_io_buffer {
void *base;
size_t size;
enum rb_io_buffer_flags flags;
#if defined(_WIN32)
HANDLE mapping;
#endif
VALUE source;
};
static inline void *
io_buffer_map_memory(size_t size, int flags)
{
#if defined(_WIN32)
void * base = VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE);
if (!base) {
rb_sys_fail("io_buffer_map_memory:VirtualAlloc");
}
#else
int mmap_flags = MAP_ANONYMOUS;
if (flags & RB_IO_BUFFER_SHARED) {
mmap_flags |= MAP_SHARED;
}
else {
mmap_flags |= MAP_PRIVATE;
}
void * base = mmap(NULL, size, PROT_READ | PROT_WRITE, mmap_flags, -1, 0);
if (base == MAP_FAILED) {
rb_sys_fail("io_buffer_map_memory:mmap");
}
#endif
return base;
}
static void
io_buffer_map_file(struct rb_io_buffer *buffer, int descriptor, size_t size, rb_off_t offset, enum rb_io_buffer_flags flags)
{
#if defined(_WIN32)
HANDLE file = (HANDLE)_get_osfhandle(descriptor);
if (!file) rb_sys_fail("io_buffer_map_descriptor:_get_osfhandle");
DWORD protect = PAGE_READONLY, access = FILE_MAP_READ;
if (flags & RB_IO_BUFFER_READONLY) {
buffer->flags |= RB_IO_BUFFER_READONLY;
}
else {
protect = PAGE_READWRITE;
access = FILE_MAP_WRITE;
}
if (flags & RB_IO_BUFFER_PRIVATE) {
protect = PAGE_WRITECOPY;
access = FILE_MAP_COPY;
buffer->flags |= RB_IO_BUFFER_PRIVATE;
}
else {
// This buffer refers to external buffer.
buffer->flags |= RB_IO_BUFFER_EXTERNAL;
buffer->flags |= RB_IO_BUFFER_SHARED;
}
HANDLE mapping = CreateFileMapping(file, NULL, protect, 0, 0, NULL);
if (RB_IO_BUFFER_DEBUG) fprintf(stderr, "io_buffer_map_file:CreateFileMapping -> %p\n", mapping);
if (!mapping) rb_sys_fail("io_buffer_map_descriptor:CreateFileMapping");
void *base = MapViewOfFile(mapping, access, (DWORD)(offset >> 32), (DWORD)(offset & 0xFFFFFFFF), size);
if (!base) {
CloseHandle(mapping);
rb_sys_fail("io_buffer_map_file:MapViewOfFile");
}
buffer->mapping = mapping;
#else
int protect = PROT_READ, access = 0;
if (flags & RB_IO_BUFFER_READONLY) {
buffer->flags |= RB_IO_BUFFER_READONLY;
}
else {
protect |= PROT_WRITE;
}
if (flags & RB_IO_BUFFER_PRIVATE) {
buffer->flags |= RB_IO_BUFFER_PRIVATE;
access |= MAP_PRIVATE;
}
else {
// This buffer refers to external buffer.
buffer->flags |= RB_IO_BUFFER_EXTERNAL;
buffer->flags |= RB_IO_BUFFER_SHARED;
access |= MAP_SHARED;
}
void *base = mmap(NULL, size, protect, access, descriptor, offset);
if (base == MAP_FAILED) {
rb_sys_fail("io_buffer_map_file:mmap");
}
#endif
buffer->base = base;
buffer->size = size;
buffer->flags |= RB_IO_BUFFER_MAPPED;
buffer->flags |= RB_IO_BUFFER_FILE;
}
static void
io_buffer_experimental(void)
{
static int warned = 0;
if (warned) return;
warned = 1;
if (rb_warning_category_enabled_p(RB_WARN_CATEGORY_EXPERIMENTAL)) {
rb_category_warn(RB_WARN_CATEGORY_EXPERIMENTAL,
"IO::Buffer is experimental and both the Ruby and C interface may change in the future!"
);
}
}
static void
io_buffer_zero(struct rb_io_buffer *buffer)
{
buffer->base = NULL;
buffer->size = 0;
#if defined(_WIN32)
buffer->mapping = NULL;
#endif
buffer->source = Qnil;
}
static void
io_buffer_initialize(VALUE self, struct rb_io_buffer *buffer, void *base, size_t size, enum rb_io_buffer_flags flags, VALUE source)
{
if (base) {
// If we are provided a pointer, we use it.
}
else if (size) {
// If we are provided a non-zero size, we allocate it:
if (flags & RB_IO_BUFFER_INTERNAL) {
base = calloc(size, 1);
}
else if (flags & RB_IO_BUFFER_MAPPED) {
base = io_buffer_map_memory(size, flags);
}
if (!base) {
rb_raise(rb_eIOBufferAllocationError, "Could not allocate buffer!");
}
}
else {
// Otherwise we don't do anything.
return;
}
buffer->base = base;
buffer->size = size;
buffer->flags = flags;
RB_OBJ_WRITE(self, &buffer->source, source);
#if defined(_WIN32)
buffer->mapping = NULL;
#endif
}
static void
io_buffer_free(struct rb_io_buffer *buffer)
{
if (buffer->base) {
if (buffer->flags & RB_IO_BUFFER_INTERNAL) {
free(buffer->base);
}
if (buffer->flags & RB_IO_BUFFER_MAPPED) {
#ifdef _WIN32
if (buffer->flags & RB_IO_BUFFER_FILE) {
UnmapViewOfFile(buffer->base);
}
else {
VirtualFree(buffer->base, 0, MEM_RELEASE);
}
#else
munmap(buffer->base, buffer->size);
#endif
}
// Previously we had this, but we found out due to the way GC works, we
// can't refer to any other Ruby objects here.
// if (RB_TYPE_P(buffer->source, T_STRING)) {
// rb_str_unlocktmp(buffer->source);
// }
buffer->base = NULL;
buffer->size = 0;
buffer->flags = 0;
buffer->source = Qnil;
}
#if defined(_WIN32)
if (buffer->mapping) {
if (RB_IO_BUFFER_DEBUG) fprintf(stderr, "io_buffer_free:CloseHandle -> %p\n", buffer->mapping);
if (!CloseHandle(buffer->mapping)) {
fprintf(stderr, "io_buffer_free:GetLastError -> %lu\n", GetLastError());
}
buffer->mapping = NULL;
}
#endif
}
void
rb_io_buffer_type_mark(void *_buffer)
{
struct rb_io_buffer *buffer = _buffer;
rb_gc_mark(buffer->source);
}
void
rb_io_buffer_type_free(void *_buffer)
{
struct rb_io_buffer *buffer = _buffer;
io_buffer_free(buffer);
}
size_t
rb_io_buffer_type_size(const void *_buffer)
{
const struct rb_io_buffer *buffer = _buffer;
size_t total = sizeof(struct rb_io_buffer);
if (buffer->flags) {
total += buffer->size;
}
return total;
}
static const rb_data_type_t rb_io_buffer_type = {
.wrap_struct_name = "IO::Buffer",
.function = {
.dmark = rb_io_buffer_type_mark,
.dfree = rb_io_buffer_type_free,
.dsize = rb_io_buffer_type_size,
},
.data = NULL,
.flags = RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE,
};
static inline enum rb_io_buffer_flags
io_buffer_extract_flags(VALUE argument)
{
if (rb_int_negative_p(argument)) {
rb_raise(rb_eArgError, "Flags can't be negative!");
}
enum rb_io_buffer_flags flags = RB_NUM2UINT(argument);
// We deliberately ignore unknown flags. Any future flags which are exposed this way should be safe to ignore.
return flags & RB_IO_BUFFER_FLAGS_MASK;
}
// Extract an offset argument, which must be a non-negative integer.
static inline size_t
io_buffer_extract_offset(VALUE argument)
{
if (rb_int_negative_p(argument)) {
rb_raise(rb_eArgError, "Offset can't be negative!");
}
return NUM2SIZET(argument);
}
// Extract a length argument, which must be a non-negative integer.
// Length is generally considered a mutable property of an object and
// semantically should be considered a subset of "size" as a concept.
static inline size_t
io_buffer_extract_length(VALUE argument)
{
if (rb_int_negative_p(argument)) {
rb_raise(rb_eArgError, "Length can't be negative!");
}
return NUM2SIZET(argument);
}
// Extract a size argument, which must be a non-negative integer.
// Size is generally considered an immutable property of an object.
static inline size_t
io_buffer_extract_size(VALUE argument)
{
if (rb_int_negative_p(argument)) {
rb_raise(rb_eArgError, "Size can't be negative!");
}
return NUM2SIZET(argument);
}
// Extract a width argument, which must be a non-negative integer, and must be
// at least the given minimum.
static inline size_t
io_buffer_extract_width(VALUE argument, size_t minimum)
{
if (rb_int_negative_p(argument)) {
rb_raise(rb_eArgError, "Width can't be negative!");
}
size_t width = NUM2SIZET(argument);
if (width < minimum) {
rb_raise(rb_eArgError, "Width must be at least %" PRIuSIZE "!", minimum);
}
return width;
}
// Compute the default length for a buffer, given an offset into that buffer.
// The default length is the size of the buffer minus the offset. The offset
// must be less than the size of the buffer otherwise the length will be
// invalid; in that case, an ArgumentError exception will be raised.
static inline size_t
io_buffer_default_length(const struct rb_io_buffer *buffer, size_t offset)
{
if (offset > buffer->size) {
rb_raise(rb_eArgError, "The given offset is bigger than the buffer size!");
}
// Note that the "length" is computed by the size the offset.
return buffer->size - offset;
}
// Extract the optional length and offset arguments, returning the buffer.
// The length and offset are optional, but if they are provided, they must be
// positive integers. If the length is not provided, the default length is
// computed from the buffer size and offset. If the offset is not provided, it
// defaults to zero.
static inline struct rb_io_buffer *
io_buffer_extract_length_offset(VALUE self, int argc, VALUE argv[], size_t *length, size_t *offset)
{
struct rb_io_buffer *buffer = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, buffer);
if (argc >= 2 && !NIL_P(argv[1])) {
*offset = io_buffer_extract_offset(argv[1]);
}
else {
*offset = 0;
}
if (argc >= 1 && !NIL_P(argv[0])) {
*length = io_buffer_extract_length(argv[0]);
}
else {
*length = io_buffer_default_length(buffer, *offset);
}
return buffer;
}
// Extract the optional offset and length arguments, returning the buffer.
// Similar to `io_buffer_extract_length_offset` but with the order of arguments
// reversed.
//
// After much consideration, I decided to accept both forms.
// The `(offset, length)` order is more natural when referring about data,
// while the `(length, offset)` order is more natural when referring to
// read/write operations. In many cases, with the latter form, `offset`
// is usually not supplied.
static inline struct rb_io_buffer *
io_buffer_extract_offset_length(VALUE self, int argc, VALUE argv[], size_t *offset, size_t *length)
{
struct rb_io_buffer *buffer = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, buffer);
if (argc >= 1 && !NIL_P(argv[0])) {
*offset = io_buffer_extract_offset(argv[0]);
}
else {
*offset = 0;
}
if (argc >= 2 && !NIL_P(argv[1])) {
*length = io_buffer_extract_length(argv[1]);
}
else {
*length = io_buffer_default_length(buffer, *offset);
}
return buffer;
}
VALUE
rb_io_buffer_type_allocate(VALUE self)
{
struct rb_io_buffer *buffer = NULL;
VALUE instance = TypedData_Make_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, buffer);
io_buffer_zero(buffer);
return instance;
}
static VALUE io_buffer_for_make_instance(VALUE klass, VALUE string, enum rb_io_buffer_flags flags)
{
VALUE instance = rb_io_buffer_type_allocate(klass);
struct rb_io_buffer *buffer = NULL;
TypedData_Get_Struct(instance, struct rb_io_buffer, &rb_io_buffer_type, buffer);
flags |= RB_IO_BUFFER_EXTERNAL;
if (RB_OBJ_FROZEN(string))
flags |= RB_IO_BUFFER_READONLY;
if (!(flags & RB_IO_BUFFER_READONLY))
rb_str_modify(string);
io_buffer_initialize(instance, buffer, RSTRING_PTR(string), RSTRING_LEN(string), flags, string);
return instance;
}
struct io_buffer_for_yield_instance_arguments {
VALUE klass;
VALUE string;
VALUE instance;
enum rb_io_buffer_flags flags;
};
static VALUE
io_buffer_for_yield_instance(VALUE _arguments)
{
struct io_buffer_for_yield_instance_arguments *arguments = (struct io_buffer_for_yield_instance_arguments *)_arguments;
arguments->instance = io_buffer_for_make_instance(arguments->klass, arguments->string, arguments->flags);
rb_str_locktmp(arguments->string);
return rb_yield(arguments->instance);
}
static VALUE
io_buffer_for_yield_instance_ensure(VALUE _arguments)
{
struct io_buffer_for_yield_instance_arguments *arguments = (struct io_buffer_for_yield_instance_arguments *)_arguments;
if (arguments->instance != Qnil) {
rb_io_buffer_free(arguments->instance);
}
rb_str_unlocktmp(arguments->string);
return Qnil;
}
/*
* call-seq:
* IO::Buffer.for(string) -> readonly io_buffer
* IO::Buffer.for(string) {|io_buffer| ... read/write io_buffer ...}
*
* Creates a zero-copy IO::Buffer from the given string's memory. Without a
* block a frozen internal copy of the string is created efficiently and used
* as the buffer source. When a block is provided, the buffer is associated
* directly with the string's internal buffer and updating the buffer will
* update the string.
*
* Until #free is invoked on the buffer, either explicitly or via the garbage
* collector, the source string will be locked and cannot be modified.
*
* If the string is frozen, it will create a read-only buffer which cannot be
* modified. If the string is shared, it may trigger a copy-on-write when
* using the block form.
*
* string = 'test'
* buffer = IO::Buffer.for(string)
* buffer.external? #=> true
*
* buffer.get_string(0, 1)
* # => "t"
* string
* # => "best"
*
* buffer.resize(100)
* # in `resize': Cannot resize external buffer! (IO::Buffer::AccessError)
*
* IO::Buffer.for(string) do |buffer|
* buffer.set_string("T")
* string
* # => "Test"
* end
*/
VALUE
rb_io_buffer_type_for(VALUE klass, VALUE string)
{
StringValue(string);
// 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 (rb_block_given_p()) {
struct io_buffer_for_yield_instance_arguments arguments = {
.klass = klass,
.string = string,
.instance = Qnil,
.flags = 0,
};
return rb_ensure(io_buffer_for_yield_instance, (VALUE)&arguments, io_buffer_for_yield_instance_ensure, (VALUE)&arguments);
}
else {
// This internally returns the source string if it's already frozen.
string = rb_str_tmp_frozen_acquire(string);
return io_buffer_for_make_instance(klass, string, RB_IO_BUFFER_READONLY);
}
}
/*
* call-seq:
* IO::Buffer.string(length) {|io_buffer| ... read/write io_buffer ...} -> string
*
* Creates a new string of the given length and yields a zero-copy IO::Buffer
* instance to the block which uses the string as a source. The block is
* expected to write to the buffer and the string will be returned.
*
* IO::Buffer.string(4) do |buffer|
* buffer.set_string("Ruby")
* end
* # => "Ruby"
*/
VALUE
rb_io_buffer_type_string(VALUE klass, VALUE length)
{
VALUE string = rb_str_new(NULL, RB_NUM2LONG(length));
struct io_buffer_for_yield_instance_arguments arguments = {
.klass = klass,
.string = string,
.instance = Qnil,
};
rb_ensure(io_buffer_for_yield_instance, (VALUE)&arguments, io_buffer_for_yield_instance_ensure, (VALUE)&arguments);
return string;
}
VALUE
rb_io_buffer_new(void *base, size_t size, enum rb_io_buffer_flags flags)
{
VALUE instance = rb_io_buffer_type_allocate(rb_cIOBuffer);
struct rb_io_buffer *buffer = NULL;
TypedData_Get_Struct(instance, struct rb_io_buffer, &rb_io_buffer_type, buffer);
io_buffer_initialize(instance, buffer, base, size, flags, Qnil);
return instance;
}
VALUE
rb_io_buffer_map(VALUE io, size_t size, rb_off_t offset, enum rb_io_buffer_flags flags)
{
io_buffer_experimental();
VALUE instance = rb_io_buffer_type_allocate(rb_cIOBuffer);
struct rb_io_buffer *buffer = NULL;
TypedData_Get_Struct(instance, struct rb_io_buffer, &rb_io_buffer_type, buffer);
int descriptor = rb_io_descriptor(io);
io_buffer_map_file(buffer, descriptor, size, offset, flags);
return instance;
}
/*
* call-seq: IO::Buffer.map(file, [size, [offset, [flags]]]) -> io_buffer
*
* Create an IO::Buffer for reading from +file+ by memory-mapping the file.
* +file_io+ should be a +File+ instance, opened for reading.
*
* Optional +size+ and +offset+ of mapping can be specified.
*
* By default, the buffer would be immutable (read only); to create a writable
* mapping, you need to open a file in read-write mode, and explicitly pass
* +flags+ argument without IO::Buffer::IMMUTABLE.
*
* File.write('test.txt', 'test')
*
* buffer = IO::Buffer.map(File.open('test.txt'), nil, 0, IO::Buffer::READONLY)
* # => #<IO::Buffer 0x00000001014a0000+4 MAPPED READONLY>
*
* buffer.readonly? # => true
*
* buffer.get_string
* # => "test"
*
* buffer.set_string('b', 0)
* # `set_string': Buffer is not writable! (IO::Buffer::AccessError)
*
* # create read/write mapping: length 4 bytes, offset 0, flags 0
* buffer = IO::Buffer.map(File.open('test.txt', 'r+'), 4, 0)
* buffer.set_string('b', 0)
* # => 1
*
* # Check it
* File.read('test.txt')
* # => "best"
*
* Note that some operating systems may not have cache coherency between mapped
* buffers and file reads.
*/
static VALUE
io_buffer_map(int argc, VALUE *argv, VALUE klass)
{
rb_check_arity(argc, 1, 4);
// We might like to handle a string path?
VALUE io = argv[0];
size_t size;
if (argc >= 2 && !RB_NIL_P(argv[1])) {
size = io_buffer_extract_size(argv[1]);
}
else {
rb_off_t file_size = rb_file_size(io);
// Compiler can confirm that we handled file_size < 0 case:
if (file_size < 0) {
rb_raise(rb_eArgError, "Invalid negative file size!");
}
// Here, we assume that file_size is positive:
else if ((uintmax_t)file_size > SIZE_MAX) {
rb_raise(rb_eArgError, "File larger than address space!");
}
else {
// This conversion should be safe:
size = (size_t)file_size;
}
}
// This is the file offset, not the buffer offset:
rb_off_t offset = 0;
if (argc >= 3) {
offset = NUM2OFFT(argv[2]);
}
enum rb_io_buffer_flags flags = 0;
if (argc >= 4) {
flags = io_buffer_extract_flags(argv[3]);
}
return rb_io_buffer_map(io, size, offset, flags);
}
// Compute the optimal allocation flags for a buffer of the given size.
static inline enum rb_io_buffer_flags
io_flags_for_size(size_t size)
{
if (size >= RUBY_IO_BUFFER_PAGE_SIZE) {
return RB_IO_BUFFER_MAPPED;
}
return RB_IO_BUFFER_INTERNAL;
}
/*
* call-seq: IO::Buffer.new([size = DEFAULT_SIZE, [flags = 0]]) -> io_buffer
*
* Create a new zero-filled IO::Buffer of +size+ bytes.
* By default, the buffer will be _internal_: directly allocated chunk
* of the memory. But if the requested +size+ is more than OS-specific
* IO::Buffer::PAGE_SIZE, the buffer would be allocated using the
* virtual memory mechanism (anonymous +mmap+ on Unix, +VirtualAlloc+
* on Windows). The behavior can be forced by passing IO::Buffer::MAPPED
* as a second parameter.
*
* buffer = IO::Buffer.new(4)
* # =>
* # #<IO::Buffer 0x000055b34497ea10+4 INTERNAL>
* # 0x00000000 00 00 00 00 ....
*
* buffer.get_string(0, 1) # => "\x00"
*
* buffer.set_string("test")
* buffer
* # =>
* # #<IO::Buffer 0x000055b34497ea10+4 INTERNAL>
* # 0x00000000 74 65 73 74 test
*/
VALUE
rb_io_buffer_initialize(int argc, VALUE *argv, VALUE self)
{
io_buffer_experimental();
rb_check_arity(argc, 0, 2);
struct rb_io_buffer *buffer = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, buffer);
size_t size;
if (argc > 0) {
size = io_buffer_extract_size(argv[0]);
}
else {
size = RUBY_IO_BUFFER_DEFAULT_SIZE;
}
enum rb_io_buffer_flags flags = 0;
if (argc >= 2) {
flags = io_buffer_extract_flags(argv[1]);
}
else {
flags |= io_flags_for_size(size);
}
io_buffer_initialize(self, buffer, NULL, size, flags, Qnil);
return self;
}
static int
io_buffer_validate_slice(VALUE source, void *base, size_t size)
{
void *source_base = NULL;
size_t source_size = 0;
if (RB_TYPE_P(source, T_STRING)) {
RSTRING_GETMEM(source, source_base, source_size);
}
else {
rb_io_buffer_get_bytes(source, &source_base, &source_size);
}
// Source is invalid:
if (source_base == NULL) return 0;
// Base is out of range:
if (base < source_base) return 0;
const void *source_end = (char*)source_base + source_size;
const void *end = (char*)base + size;
// End is out of range:
if (end > source_end) return 0;
// It seems okay:
return 1;
}
static int
io_buffer_validate(struct rb_io_buffer *buffer)
{
if (buffer->source != Qnil) {
// Only slices incur this overhead, unfortunately... better safe than sorry!
return io_buffer_validate_slice(buffer->source, buffer->base, buffer->size);
}
else {
return 1;
}
}
enum rb_io_buffer_flags
rb_io_buffer_get_bytes(VALUE self, void **base, size_t *size)
{
struct rb_io_buffer *buffer = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, buffer);
if (io_buffer_validate(buffer)) {
if (buffer->base) {
*base = buffer->base;
*size = buffer->size;
return buffer->flags;
}
}
*base = NULL;
*size = 0;
return 0;
}
// Internal function for accessing bytes for writing, wil
static inline void
io_buffer_get_bytes_for_writing(struct rb_io_buffer *buffer, void **base, size_t *size)
{
if (buffer->flags & RB_IO_BUFFER_READONLY) {
rb_raise(rb_eIOBufferAccessError, "Buffer is not writable!");
}
if (!io_buffer_validate(buffer)) {
rb_raise(rb_eIOBufferInvalidatedError, "Buffer is invalid!");
}
if (buffer->base) {
*base = buffer->base;
*size = buffer->size;
} else {
*base = NULL;
*size = 0;
}
}
void
rb_io_buffer_get_bytes_for_writing(VALUE self, void **base, size_t *size)
{
struct rb_io_buffer *buffer = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, buffer);
io_buffer_get_bytes_for_writing(buffer, base, size);
}
static void
io_buffer_get_bytes_for_reading(struct rb_io_buffer *buffer, const void **base, size_t *size)
{
if (!io_buffer_validate(buffer)) {
rb_raise(rb_eIOBufferInvalidatedError, "Buffer has been invalidated!");
}
if (buffer->base) {
*base = buffer->base;
*size = buffer->size;
} else {
*base = NULL;
*size = 0;
}
}
void
rb_io_buffer_get_bytes_for_reading(VALUE self, const void **base, size_t *size)
{
struct rb_io_buffer *buffer = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, buffer);
io_buffer_get_bytes_for_reading(buffer, base, size);
}
/*
* call-seq: to_s -> string
*
* Short representation of the buffer. It includes the address, size and
* symbolic flags. This format is subject to change.
*
* puts IO::Buffer.new(4) # uses to_s internally
* # #<IO::Buffer 0x000055769f41b1a0+4 INTERNAL>
*/
VALUE
rb_io_buffer_to_s(VALUE self)
{
struct rb_io_buffer *buffer = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, buffer);
VALUE result = rb_str_new_cstr("#<");
rb_str_append(result, rb_class_name(CLASS_OF(self)));
rb_str_catf(result, " %p+%"PRIdSIZE, buffer->base, buffer->size);
if (buffer->base == NULL) {
rb_str_cat2(result, " NULL");
}
if (buffer->flags & RB_IO_BUFFER_EXTERNAL) {
rb_str_cat2(result, " EXTERNAL");
}
if (buffer->flags & RB_IO_BUFFER_INTERNAL) {
rb_str_cat2(result, " INTERNAL");
}
if (buffer->flags & RB_IO_BUFFER_MAPPED) {
rb_str_cat2(result, " MAPPED");
}
if (buffer->flags & RB_IO_BUFFER_FILE) {
rb_str_cat2(result, " FILE");
}
if (buffer->flags & RB_IO_BUFFER_SHARED) {
rb_str_cat2(result, " SHARED");
}
if (buffer->flags & RB_IO_BUFFER_LOCKED) {
rb_str_cat2(result, " LOCKED");
}
if (buffer->flags & RB_IO_BUFFER_PRIVATE) {
rb_str_cat2(result, " PRIVATE");
}
if (buffer->flags & RB_IO_BUFFER_READONLY) {
rb_str_cat2(result, " READONLY");
}
if (buffer->source != Qnil) {
rb_str_cat2(result, " SLICE");
}
if (!io_buffer_validate(buffer)) {
rb_str_cat2(result, " INVALID");
}
return rb_str_cat2(result, ">");
}
// Compute the output size of a hexdump of the given width (bytes per line), total size, and whether it is the first line in the output.
// This is used to preallocate the output string.
inline static size_t
io_buffer_hexdump_output_size(size_t width, size_t size, int first)
{
// The preview on the right hand side is 1:1:
size_t total = size;
size_t whole_lines = (size / width);
size_t partial_line = (size % width) ? 1 : 0;
// For each line:
// 1 byte 10 bytes 1 byte width*3 bytes 1 byte size bytes
// (newline) (address) (space) (hexdump ) (space) (preview)
total += (whole_lines + partial_line) * (1 + 10 + width*3 + 1 + 1);
// If the hexdump is the first line, one less newline will be emitted:
if (size && first) total -= 1;
return total;
}
// Append a hexdump of the given width (bytes per line), base address, size, and whether it is the first line in the output.
// If the hexdump is not the first line, it will prepend a newline if there is any output at all.
// If formatting here is adjusted, please update io_buffer_hexdump_output_size accordingly.
static VALUE
io_buffer_hexdump(VALUE string, size_t width, const char *base, size_t length, size_t offset, int first)
{
char *text = alloca(width+1);
text[width] = '\0';
for (; offset < length; offset += width) {
memset(text, '\0', width);
if (first) {
rb_str_catf(string, "0x%08" PRIxSIZE " ", offset);
first = 0;
}