Ruby 4.1.0dev (2026-11-26 revision 7402606da42ddf74ce3bec5a699c63d864faa040)
io_buffer.c (7402606da42ddf74ce3bec5a699c63d864faa040)
1/**********************************************************************
2
3 io_buffer.c
4
5 Copyright (C) 2021 Samuel Grant Dawson Williams
6
7**********************************************************************/
8
9#include "ruby/io/buffer.h"
11#include "ruby/memory_view.h"
12
13// For `rb_nogvl`.
14#include "ruby/thread.h"
15
16#include "internal.h"
17#include "internal/array.h"
18#include "internal/bits.h"
19#include "internal/error.h"
20#include "internal/gc.h"
21#include "internal/numeric.h"
22#include "internal/string.h"
23#include "internal/io.h"
24#include "internal/io_buffer.h"
25
26VALUE rb_cIOBuffer;
27VALUE rb_cIOBufferStorage;
28VALUE rb_cIOBufferSlice;
29VALUE rb_eIOBufferLockedError;
30VALUE rb_eIOBufferAllocationError;
31VALUE rb_eIOBufferAccessError;
32VALUE rb_eIOBufferInvalidatedError;
33VALUE rb_eIOBufferMaskError;
34
35size_t RUBY_IO_BUFFER_PAGE_SIZE;
36size_t RUBY_IO_BUFFER_MAP_ALIGNMENT;
37size_t RUBY_IO_BUFFER_DEFAULT_SIZE;
38
39#ifdef _WIN32
40#else
41#include <unistd.h>
42#include <sys/mman.h>
43#endif
44
45enum {
46 RB_IO_BUFFER_HEXDUMP_DEFAULT_WIDTH = 16,
47 RB_IO_BUFFER_HEXDUMP_MAXIMUM_WIDTH = 1024,
48
49 RB_IO_BUFFER_INSPECT_HEXDUMP_MAXIMUM_SIZE = 256,
50 RB_IO_BUFFER_INSPECT_HEXDUMP_WIDTH = 16,
51
52 // This is used to validate the flags given by the user.
53 RB_IO_BUFFER_FLAGS_MASK = RB_IO_BUFFER_EXTERNAL | RB_IO_BUFFER_INTERNAL | RB_IO_BUFFER_MAPPED | RB_IO_BUFFER_SHARED | RB_IO_BUFFER_PRIVATE | RB_IO_BUFFER_READONLY,
54
55 RB_IO_BUFFER_ALLOCATION_FLAGS = RB_IO_BUFFER_INTERNAL | RB_IO_BUFFER_MAPPED,
56 RB_IO_BUFFER_MAPPING_FLAGS = RB_IO_BUFFER_SHARED | RB_IO_BUFFER_PRIVATE,
57
58 // Private representation tag, never accepted or returned as a public flag.
59 IO_BUFFER_SLICE = 1 << 9,
60
61 RB_IO_BUFFER_DEBUG = 0,
62};
63
65 // Without a source (source == Qnil), this is an absolute pointer to owned
66 // or borrowed memory. Ownership is determined by the flags, not by the
67 // presence of a source.
68 //
69 // With a source (String or IO::Buffer), this is a byte offset into it.
70 // The absolute pointer is resolved as `source_base + offset` on demand
71 // (see io_buffer_try_get_bytes), so source relocation preserves the
72 // logical range. Use io_buffer_slice_offset() to read the offset.
73 void *base;
74 size_t size;
75
76 enum rb_io_buffer_flags flags;
77 VALUE source;
78};
79
81 struct rb_io_buffer_view view;
82 // Only Storage objects carry allocation-lifetime state, even for borrowed
83 // storage. Slice objects contain only the common view header above.
84 size_t lock_count;
85#ifdef _WIN32
86 HANDLE mapping;
87#endif
88};
89
90static bool
91io_buffer_slice_p(const struct rb_io_buffer_view *buffer)
92{
93 return (buffer->flags & IO_BUFFER_SLICE) != 0;
94}
95
96// Checked downcast of this view; unlike io_buffer_lock_owner, it does not
97// traverse sources. Only Storage objects contain the storage-management tail.
98static struct rb_io_buffer_storage *
99io_buffer_storage_from_view(struct rb_io_buffer_view *view)
100{
101 if (io_buffer_slice_p(view)) {
102 rb_raise(rb_eIOBufferAccessError, "Slice does not manage an allocation!");
103 }
104 return (struct rb_io_buffer_storage *)view;
105}
106
107static inline void *
108io_buffer_map_memory(size_t size, int flags)
109{
110#if defined(_WIN32)
111 void * base = VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE);
112
113 if (!base) {
114 rb_sys_fail("io_buffer_map_memory:VirtualAlloc");
115 }
116#else
117 int mmap_flags = MAP_ANONYMOUS;
118 if (flags & RB_IO_BUFFER_SHARED) {
119 mmap_flags |= MAP_SHARED;
120 }
121 else {
122 mmap_flags |= MAP_PRIVATE;
123 }
124
125 void * base = mmap(NULL, size, PROT_READ | PROT_WRITE, mmap_flags, -1, 0);
126
127 if (base == MAP_FAILED) {
128 rb_sys_fail("io_buffer_map_memory:mmap");
129 }
130
131 ruby_annotate_mmap(base, size, "Ruby:io_buffer_map_memory");
132#endif
133
134 return base;
135}
136
137static void
138io_buffer_storage_map_file(struct rb_io_buffer_storage *storage, int descriptor, size_t size, rb_off_t offset, enum rb_io_buffer_flags flags)
139{
140 struct rb_io_buffer_view *buffer = &storage->view;
141#if defined(_WIN32)
142 HANDLE file = (HANDLE)_get_osfhandle(descriptor);
143 if (!file) rb_sys_fail("io_buffer_map_descriptor:_get_osfhandle");
144
145 DWORD protect = PAGE_READONLY, access = FILE_MAP_READ;
146
147 if (flags & RB_IO_BUFFER_READONLY) {
148 buffer->flags |= RB_IO_BUFFER_READONLY;
149 }
150 else {
151 protect = PAGE_READWRITE;
152 access = FILE_MAP_WRITE;
153 }
154
155 if (flags & RB_IO_BUFFER_PRIVATE) {
156 if (!(flags & RB_IO_BUFFER_READONLY)) {
157 // A copy-on-write view reserves commit for every page.
158 protect = PAGE_WRITECOPY;
159 access = FILE_MAP_COPY;
160 }
161 buffer->flags |= RB_IO_BUFFER_PRIVATE;
162 }
163 else {
164 // This buffer refers to external buffer.
165 buffer->flags |= RB_IO_BUFFER_EXTERNAL;
166 buffer->flags |= RB_IO_BUFFER_SHARED;
167 }
168
169 HANDLE mapping = CreateFileMapping(file, NULL, protect, 0, 0, NULL);
170 if (RB_IO_BUFFER_DEBUG) fprintf(stderr, "io_buffer_storage_map_file:CreateFileMapping -> %p\n", mapping);
171 if (!mapping) rb_sys_fail("io_buffer_map_descriptor:CreateFileMapping");
172
173 void *base = MapViewOfFile(mapping, access, (DWORD)(offset >> 32), (DWORD)(offset & 0xFFFFFFFF), size);
174
175 if (!base) {
176 CloseHandle(mapping);
177 rb_sys_fail("io_buffer_storage_map_file:MapViewOfFile");
178 }
179
180 storage->mapping = mapping;
181#else
182 int protect = PROT_READ, access = 0;
183
184 if (flags & RB_IO_BUFFER_READONLY) {
185 buffer->flags |= RB_IO_BUFFER_READONLY;
186 }
187 else {
188 protect |= PROT_WRITE;
189 }
190
191 if (flags & RB_IO_BUFFER_PRIVATE) {
192 buffer->flags |= RB_IO_BUFFER_PRIVATE;
193 access |= MAP_PRIVATE;
194 }
195 else {
196 // This buffer refers to external buffer.
197 buffer->flags |= RB_IO_BUFFER_EXTERNAL;
198 buffer->flags |= RB_IO_BUFFER_SHARED;
199 access |= MAP_SHARED;
200 }
201
202 void *base = mmap(NULL, size, protect, access, descriptor, offset);
203
204 if (base == MAP_FAILED) {
205 rb_sys_fail("io_buffer_storage_map_file:mmap");
206 }
207#endif
208
209 buffer->base = base;
210 buffer->size = size;
211
212 buffer->flags |= RB_IO_BUFFER_MAPPED;
213 buffer->flags |= RB_IO_BUFFER_FILE;
214}
215
216static void
217io_buffer_experimental(void)
218{
219 static int warned = 0;
220
221 if (warned) return;
222
223 warned = 1;
224
225 if (rb_warning_category_enabled_p(RB_WARN_CATEGORY_EXPERIMENTAL)) {
227 "IO::Buffer is experimental and both the Ruby and C interface may change in the future!"
228 );
229 }
230}
231
232static void
233io_buffer_storage_zero(struct rb_io_buffer_storage *storage)
234{
235 storage->view.base = NULL;
236 storage->view.size = 0;
237 storage->view.flags = 0;
238 storage->view.source = Qnil;
239 storage->lock_count = 0;
240#if defined(_WIN32)
241 storage->mapping = NULL;
242#endif
243}
244
245static void
246io_buffer_storage_initialize(VALUE self, struct rb_io_buffer_storage *storage, void *base, size_t size, enum rb_io_buffer_flags flags, VALUE source)
247{
248 struct rb_io_buffer_view *buffer = &storage->view;
249 if (source != Qnil) {
250 // The buffer is backed by another object (e.g. a String). Here `base`
251 // is a byte *offset* into that source rather than an absolute pointer,
252 // and the memory is not owned by this buffer. The absolute base is
253 // resolved on demand as `source_base + offset` (see
254 // io_buffer_try_get_bytes), so it stays valid if the source moves.
255 }
256 else if (base) {
257 // If we are provided a pointer, we use it.
258 }
259 else if (size) {
260 // If we are provided a non-zero size, we allocate it:
261 if (flags & RB_IO_BUFFER_INTERNAL) {
262 base = calloc(size, 1);
263 }
264 else if (flags & RB_IO_BUFFER_MAPPED) {
265 base = io_buffer_map_memory(size, flags);
266 }
267
268 if (!base) {
269 rb_raise(rb_eIOBufferAllocationError, "Could not allocate buffer!");
270 }
271 }
272 else {
273 // Otherwise we don't do anything.
274 return;
275 }
276
277 buffer->base = base;
278 buffer->size = size;
279 // Public flags cannot change the payload's representation.
280 buffer->flags = flags & ~IO_BUFFER_SLICE;
281 storage->lock_count = 0;
282 RB_OBJ_WRITE(self, &buffer->source, source);
283
284#if defined(_WIN32)
285 storage->mapping = NULL;
286#endif
287}
288
289static void
290io_buffer_storage_release(struct rb_io_buffer_storage *storage)
291{
292 struct rb_io_buffer_view *buffer = &storage->view;
293 if (buffer->base) {
294 if (buffer->flags & RB_IO_BUFFER_INTERNAL) {
295 free(buffer->base);
296 }
297
298 if (buffer->flags & RB_IO_BUFFER_MAPPED) {
299#ifdef _WIN32
300 if (buffer->flags & RB_IO_BUFFER_FILE) {
301 UnmapViewOfFile(buffer->base);
302 }
303 else {
304 VirtualFree(buffer->base, 0, MEM_RELEASE);
305 }
306#else
307 munmap(buffer->base, buffer->size);
308#endif
309 }
310
311 // Previously we had this, but we found out due to the way GC works, we
312 // can't refer to any other Ruby objects here.
313 // if (RB_TYPE_P(buffer->source, T_STRING)) {
314 // rb_str_unlocktmp(buffer->source);
315 // }
316 }
317
318#if defined(_WIN32)
319 if (storage->mapping) {
320 if (RB_IO_BUFFER_DEBUG) fprintf(stderr, "io_buffer_storage_release:CloseHandle -> %p\n", storage->mapping);
321 if (!CloseHandle(storage->mapping)) {
322 fprintf(stderr, "io_buffer_storage_release:GetLastError -> %lu\n", GetLastError());
323 }
324 storage->mapping = NULL;
325 }
326#endif
327
328 io_buffer_storage_zero(storage);
329}
330
331static void
332rb_io_buffer_type_mark(void *_buffer)
333{
334 struct rb_io_buffer_view *buffer = _buffer;
335 if (buffer->source != Qnil) {
336 if (RB_TYPE_P(buffer->source, T_STRING)) {
337 // The `source` String has to be pinned, because the `base` may point to the embedded String content,
338 // which can be otherwise moved by GC compaction.
339 rb_gc_mark(buffer->source);
340 } else {
341 rb_gc_mark_movable(buffer->source);
342 }
343 }
344}
345
346static void
347rb_io_buffer_type_compact(void *_buffer)
348{
349 struct rb_io_buffer_view *buffer = _buffer;
350 if (buffer->source != Qnil) {
351 if (RB_TYPE_P(buffer->source, T_STRING)) {
352 // The `source` String has to be pinned, because the `base` may point to the embedded String content,
353 // which can be otherwise moved by GC compaction.
354 } else {
355 rb_gc_update_moved(&buffer->source);
356 }
357 }
358}
359
360static void
361rb_io_buffer_type_free(void *_buffer)
362{
363 struct rb_io_buffer_view *buffer = _buffer;
364
365 if (!io_buffer_slice_p(buffer)) io_buffer_storage_release(io_buffer_storage_from_view(buffer));
366}
367
368static size_t
369rb_io_buffer_type_size(const void *_buffer)
370{
371 const struct rb_io_buffer_view *buffer = _buffer;
372 size_t total = io_buffer_slice_p(buffer) ? sizeof(struct rb_io_buffer_view) : sizeof(struct rb_io_buffer_storage);
373
374 if (buffer->flags & RB_IO_BUFFER_ALLOCATION_FLAGS) {
375 total += buffer->size;
376 }
377
378 return total;
379}
380
381static const rb_data_type_t rb_io_buffer_type = {
382 .wrap_struct_name = "IO::Buffer",
383 .function = {
384 .dmark = rb_io_buffer_type_mark,
385 .dfree = rb_io_buffer_type_free,
386 .dsize = rb_io_buffer_type_size,
387 .dcompact = rb_io_buffer_type_compact,
388 },
389 .data = NULL,
390 .flags = RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE,
391};
392
393int
394rb_io_buffer_p(VALUE self)
395{
396 return rb_typeddata_is_kind_of(self, &rb_io_buffer_type);
397}
398
399// Shared byte-access interface: accepts both concrete Buffer representations.
400static struct rb_io_buffer_view *
401get_io_buffer_view(VALUE self)
402{
403 struct rb_io_buffer_view *view;
404 TypedData_Get_Struct(self, struct rb_io_buffer_view, &rb_io_buffer_type, view);
405 return view;
406}
407
408// Allocation-management interface: requires Storage.
409static struct rb_io_buffer_storage *
410get_io_buffer_storage(VALUE self)
411{
412 return io_buffer_storage_from_view(get_io_buffer_view(self));
413}
414
415// Whether this buffer owns an allocation and is responsible for releasing it.
416// Slices, String-backed buffers, and raw borrowed-memory wrappers do not own
417// their memory. A source-less buffer is not necessarily an owning buffer.
418static inline bool
419io_buffer_owning_p(const struct rb_io_buffer_view *buffer)
420{
421 return !io_buffer_slice_p(buffer) && (buffer->flags & RB_IO_BUFFER_ALLOCATION_FLAGS) != 0;
422}
423
424
425// For a slice (io_buffer_slice_p), the `base` field stores the byte offset of
426// the slice within its immediate source rather than an absolute pointer.
427static inline size_t
428io_buffer_slice_offset(const struct rb_io_buffer_view *buffer)
429{
430 return (uintptr_t)buffer->base;
431}
432
433// Follow the source chain to the buffer which owns the allocation lock count.
434// String-backed buffers manage their own lock count and pin their String source.
435static struct rb_io_buffer_storage *
436io_buffer_lock_owner(struct rb_io_buffer_view *buffer)
437{
438 while (io_buffer_slice_p(buffer)) {
439 if (NIL_P(buffer->source)) rb_raise(rb_eIOBufferInvalidatedError, "Uninitialized slice!");
440 buffer = get_io_buffer_view(buffer->source);
441 }
442
443 return io_buffer_storage_from_view(buffer);
444}
445
446static bool
447io_buffer_locked(struct rb_io_buffer_view *buffer)
448{
449 if (io_buffer_slice_p(buffer) && NIL_P(buffer->source)) return false;
450 return io_buffer_lock_owner(buffer)->lock_count > 0;
451}
452
453static inline enum rb_io_buffer_flags
454io_buffer_extract_flags(VALUE argument)
455{
456 if (rb_int_negative_p(argument)) {
457 rb_raise(rb_eArgError, "Flags can't be negative!");
458 }
459
460 enum rb_io_buffer_flags flags = RB_NUM2UINT(argument);
461
462 // We deliberately ignore unknown flags. Any future flags which are exposed this way should be safe to ignore.
463 return flags & RB_IO_BUFFER_FLAGS_MASK;
464}
465
466static inline enum rb_io_buffer_flags
467io_buffer_flags_for_map(enum rb_io_buffer_flags flags)
468{
469 if (flags & RB_IO_BUFFER_INTERNAL) {
470 rb_raise(rb_eArgError, "IO::Buffer::INTERNAL can't be used with IO::Buffer.map!");
471 }
472
473 if (flags & RB_IO_BUFFER_EXTERNAL) {
474 rb_raise(rb_eArgError, "IO::Buffer::EXTERNAL can't be used with IO::Buffer.map!");
475 }
476
477 if ((flags & RB_IO_BUFFER_MAPPING_FLAGS) == RB_IO_BUFFER_MAPPING_FLAGS) {
478 rb_raise(rb_eArgError, "Flags can't include both IO::Buffer::SHARED and IO::Buffer::PRIVATE!");
479 }
480
481 return flags;
482}
483
484// Extract an offset argument, which must be a non-negative integer.
485static inline size_t
486io_buffer_extract_offset(VALUE argument)
487{
488 if (rb_int_negative_p(argument)) {
489 rb_raise(rb_eArgError, "Offset can't be negative!");
490 }
491
492 return NUM2SIZET(argument);
493}
494
495// Extract a length argument, which must be a non-negative integer.
496// Length is generally considered a mutable property of an object and
497// semantically should be considered a subset of "size" as a concept.
498static inline size_t
499io_buffer_extract_length(VALUE argument)
500{
501 if (rb_int_negative_p(argument)) {
502 rb_raise(rb_eArgError, "Length can't be negative!");
503 }
504
505 return NUM2SIZET(argument);
506}
507
508// Extract a size argument, which must be a non-negative integer.
509// Size is generally considered an immutable property of an object.
510static inline size_t
511io_buffer_extract_size(VALUE argument)
512{
513 if (rb_int_negative_p(argument)) {
514 rb_raise(rb_eArgError, "Size can't be negative!");
515 }
516
517 return NUM2SIZET(argument);
518}
519
520// Extract an amount, which must be a non-negative integer.
521static inline size_t
522io_buffer_extract_amount(VALUE argument)
523{
524 if (rb_int_negative_p(argument)) {
525 rb_raise(rb_eArgError, "Amount can't be negative!");
526 }
527
528 return NUM2SIZET(argument);
529}
530
531// Extract a width argument, which must be a non-negative integer, and must be
532// at least the given minimum and at most RB_IO_BUFFER_HEXDUMP_MAXIMUM_WIDTH.
533static inline size_t
534io_buffer_extract_width(VALUE argument, size_t minimum)
535{
536 if (rb_int_negative_p(argument)) {
537 rb_raise(rb_eArgError, "Width can't be negative!");
538 }
539
540 size_t width = NUM2SIZET(argument);
541
542 if (width < minimum) {
543 rb_raise(rb_eArgError, "Width must be at least %" PRIuSIZE "!", minimum);
544 }
545
546 if (width > RB_IO_BUFFER_HEXDUMP_MAXIMUM_WIDTH) {
547 rb_raise(rb_eArgError, "Width must be at most %" PRIuSIZE "!", (size_t)RB_IO_BUFFER_HEXDUMP_MAXIMUM_WIDTH);
548 }
549
550 return width;
551}
552
553// Compute the default length for a buffer, given an offset into that buffer.
554// The default length is the size of the buffer minus the offset. The offset
555// must be less than the size of the buffer otherwise the length will be
556// invalid; in that case, an ArgumentError exception will be raised.
557static inline size_t
558io_buffer_default_length(const struct rb_io_buffer_view *buffer, size_t offset)
559{
560 if (offset > buffer->size) {
561 rb_raise(rb_eArgError, "The given offset is bigger than the buffer size!");
562 }
563
564 // Note that the "length" is computed by the size the offset.
565 return buffer->size - offset;
566}
567
568// Extract the optional offset and length arguments, returning the buffer.
569// The offset and length are optional, but if they are provided, they must be
570// positive integers. If the offset is not provided, it defaults to zero. If
571// the length is not provided, it defaults to the buffer size minus the offset.
572static inline struct rb_io_buffer_view *
573io_buffer_extract_offset_length(VALUE self, int argc, VALUE argv[], size_t *offset, size_t *length)
574{
575 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
576
577 if (argc >= 1 && !NIL_P(argv[0])) {
578 *offset = io_buffer_extract_offset(argv[0]);
579 }
580 else {
581 *offset = 0;
582 }
583
584 if (argc >= 2 && !NIL_P(argv[1])) {
585 *length = io_buffer_extract_length(argv[1]);
586 }
587 else {
588 *length = io_buffer_default_length(buffer, *offset);
589 }
590
591 return buffer;
592}
593
594VALUE
595rb_io_buffer_type_allocate(VALUE self)
596{
597 io_buffer_experimental();
598
599 struct rb_io_buffer_storage *buffer = NULL;
600 VALUE instance = TypedData_Make_Struct(self, struct rb_io_buffer_storage, &rb_io_buffer_type, buffer);
601
602 io_buffer_storage_zero(buffer);
603
604 return instance;
605}
606
607static VALUE
608io_buffer_slice_allocate(VALUE klass)
609{
610 struct rb_io_buffer_view *buffer;
611 VALUE instance = TypedData_Make_Struct(klass, struct rb_io_buffer_view, &rb_io_buffer_type, buffer);
612 buffer->flags = (enum rb_io_buffer_flags)IO_BUFFER_SLICE;
613 buffer->source = Qnil;
614 return instance;
615}
616
617/*
618 * call-seq:
619 * IO::Buffer.new([size, [flags]]) -> storage
620 *
621 * Creates an IO::Buffer::Storage with the given size and flags. Buffer is the
622 * common byte-view interface; this factory creates one storage-bearing object,
623 * not a separate view and allocation. See IO::Buffer::Storage.new.
624 */
625static VALUE
626io_buffer_s_new(int argc, VALUE *argv, VALUE klass)
627{
628 if (klass == rb_cIOBuffer) klass = rb_cIOBufferStorage;
629 return rb_class_new_instance_kw(argc, argv, klass, RB_PASS_CALLED_KEYWORDS);
630}
631
632static VALUE
633io_buffer_storage_class(VALUE klass)
634{
635 if (klass == rb_cIOBuffer) return rb_cIOBufferStorage;
636 if (RTEST(rb_class_inherited_p(klass, rb_cIOBufferStorage))) return klass;
637 rb_raise(rb_eTypeError, "Storage factory requires IO::Buffer::Storage!");
638}
639
640static VALUE io_buffer_for_make_instance(VALUE klass, VALUE string, enum rb_io_buffer_flags flags)
641{
642 VALUE instance = rb_io_buffer_type_allocate(klass);
643
644 flags |= RB_IO_BUFFER_EXTERNAL;
645
646 if (RB_OBJ_FROZEN(string))
647 flags |= RB_IO_BUFFER_READONLY;
648
649 if (!(flags & RB_IO_BUFFER_READONLY))
650 rb_str_modify(string);
651
652 // The whole String, starting at offset zero.
653 struct rb_io_buffer_storage *buffer = get_io_buffer_storage(instance);
654 io_buffer_storage_initialize(instance, buffer, NULL, RSTRING_LEN(string), flags, string);
655
656 return instance;
657}
658
660 VALUE klass;
661 VALUE string;
662 VALUE instance;
663 enum rb_io_buffer_flags flags;
664};
665
666static VALUE
667io_buffer_for_yield_instance(VALUE _arguments)
668{
670
671 arguments->instance = io_buffer_for_make_instance(arguments->klass, arguments->string, arguments->flags);
672
673 if (!RB_OBJ_FROZEN(arguments->string)) {
674 rb_str_locktmp(arguments->string);
675 }
676
677 return rb_yield(arguments->instance);
678}
679
680static VALUE
681io_buffer_for_yield_instance_ensure(VALUE _arguments)
682{
684
685 if (arguments->instance != Qnil) {
686 rb_io_buffer_free(arguments->instance);
687 }
688
689 if (!RB_OBJ_FROZEN(arguments->string)) {
690 rb_str_unlocktmp(arguments->string);
691 }
692
693 return Qnil;
694}
695
697 VALUE klass;
698 VALUE string;
699 VALUE instance;
700 enum rb_io_buffer_flags flags;
701 int locked;
702 VALUE (*callback)(VALUE, VALUE);
703 VALUE argument;
704};
705
706static VALUE rb_io_buffer_locked_ensure(VALUE self);
707
709 VALUE buffer;
710 VALUE (*callback)(VALUE, VALUE);
711 VALUE argument;
712};
713
714static VALUE
715io_buffer_for_locked_callback_call(VALUE _arguments)
716{
717 struct io_buffer_for_locked_callback_arguments *arguments = (void *)_arguments;
718
719 return arguments->callback(arguments->buffer, arguments->argument);
720}
721
722static VALUE
723io_buffer_for_locked_callback(VALUE buffer, VALUE (*callback)(VALUE, VALUE), VALUE argument)
724{
725 struct io_buffer_for_locked_callback_arguments arguments = {
726 .buffer = buffer,
727 .callback = callback,
728 .argument = argument,
729 };
730
731 rb_io_buffer_lock(buffer);
732 return rb_ensure(io_buffer_for_locked_callback_call, (VALUE)&arguments, rb_io_buffer_locked_ensure, buffer);
733}
734
735static VALUE
736io_buffer_for_callback_call(VALUE _arguments)
737{
738 struct io_buffer_for_callback_arguments *arguments = (struct io_buffer_for_callback_arguments *)_arguments;
739
740 arguments->instance = io_buffer_for_make_instance(arguments->klass, arguments->string, arguments->flags);
741
742 if (!RB_OBJ_FROZEN(arguments->string)) {
743 rb_str_locktmp(arguments->string);
744 arguments->locked = 1;
745 }
746
747 return io_buffer_for_locked_callback(arguments->instance, arguments->callback, arguments->argument);
748}
749
750static VALUE
751io_buffer_for_callback_ensure(VALUE _arguments)
752{
753 struct io_buffer_for_callback_arguments *arguments = (struct io_buffer_for_callback_arguments *)_arguments;
754
755 if (arguments->instance != Qnil) {
756 rb_io_buffer_free(arguments->instance);
757 }
758
759 if (arguments->locked) {
760 rb_str_unlocktmp(arguments->string);
761 }
762
763 return Qnil;
764}
765
766VALUE
767rb_io_buffer_for_reading(VALUE string_or_buffer, VALUE (*callback)(VALUE, VALUE), VALUE argument)
768{
769 if (rb_io_buffer_p(string_or_buffer)) {
770 return io_buffer_for_locked_callback(string_or_buffer, callback, argument);
771 }
772 else if (RB_TYPE_P(string_or_buffer, T_STRING)) {
773 StringValue(string_or_buffer);
774 struct io_buffer_for_callback_arguments arguments = {
775 .klass = rb_cIOBufferStorage,
776 .string = string_or_buffer,
777 .instance = Qnil,
778 .flags = RB_IO_BUFFER_READONLY,
779 .locked = 0,
780 .callback = callback,
781 .argument = argument,
782 };
783 return rb_ensure(io_buffer_for_callback_call, (VALUE)&arguments,
784 io_buffer_for_callback_ensure, (VALUE)&arguments);
785 }
786 else {
787 rb_raise(rb_eTypeError, "expected String or IO::Buffer, not %"PRIsVALUE,
788 rb_obj_class(string_or_buffer));
789 }
790}
791
792/* Forward declaration: io_buffer_readonly_p is defined later in this file. */
793static int io_buffer_readonly_p(const struct rb_io_buffer_view *buffer);
794
795VALUE
796rb_io_buffer_for_writing(VALUE string_or_buffer, VALUE (*callback)(VALUE, VALUE), VALUE argument)
797{
798 if (rb_io_buffer_p(string_or_buffer)) {
799 struct rb_io_buffer_view *buffer = get_io_buffer_view(string_or_buffer);
800 if (io_buffer_readonly_p(buffer)) {
801 rb_raise(rb_eArgError, "buffer is read-only");
802 }
803 return io_buffer_for_locked_callback(string_or_buffer, callback, argument);
804 }
805 else if (RB_TYPE_P(string_or_buffer, T_STRING)) {
806 StringValue(string_or_buffer);
807 struct io_buffer_for_callback_arguments arguments = {
808 .klass = rb_cIOBufferStorage,
809 .string = string_or_buffer,
810 .instance = Qnil,
811 .flags = 0,
812 .locked = 0,
813 .callback = callback,
814 .argument = argument,
815 };
816 return rb_ensure(io_buffer_for_callback_call, (VALUE)&arguments,
817 io_buffer_for_callback_ensure, (VALUE)&arguments);
818 }
819 else {
820 rb_raise(rb_eTypeError, "expected String or IO::Buffer, not %"PRIsVALUE,
821 rb_obj_class(string_or_buffer));
822 }
823}
824
825/*
826 * call-seq:
827 * IO::Buffer.for(string) -> readonly io_buffer
828 * IO::Buffer.for(string) {|io_buffer| ... read/write io_buffer ...}
829 *
830 * Creates a zero-copy IO::Buffer from the given string's memory. Without a
831 * block, a frozen snapshot of the string is used as the buffer source, so
832 * later changes to the original string do not affect the buffer. When a block
833 * is provided, the buffer is associated directly with the string's internal
834 * buffer and updating the buffer will update the string.
835 *
836 * In the block form, the string is locked and cannot be modified while the
837 * block is executing.
838 *
839 * If the string is frozen, it will create a read-only buffer which cannot be
840 * modified. If the string is shared, it may trigger a copy-on-write when
841 * using the block form.
842 *
843 * string = 'test'
844 * buffer = IO::Buffer.for(string)
845 * buffer.external? #=> true
846 *
847 * buffer.get_string(0, 1)
848 * # => "t"
849 * string
850 * # => "test"
851 *
852 * buffer.resize(100)
853 * # in `resize': Cannot resize external buffer! (IO::Buffer::AccessError)
854 *
855 * IO::Buffer.for(string) do |buffer|
856 * buffer.set_string("T")
857 * string
858 * # => "Test"
859 * end
860 */
861VALUE
862rb_io_buffer_type_for(VALUE klass, VALUE string)
863{
864 klass = io_buffer_storage_class(klass);
865 StringValue(string);
866
867 // If the string is frozen, both code paths are okay.
868 // If the string is not frozen, if a block is not given, it must be frozen.
869 if (rb_block_given_p()) {
870 struct io_buffer_for_yield_instance_arguments arguments = {
871 .klass = klass,
872 .string = string,
873 .instance = Qnil,
874 .flags = 0,
875 };
876
877 return rb_ensure(io_buffer_for_yield_instance, (VALUE)&arguments, io_buffer_for_yield_instance_ensure, (VALUE)&arguments);
878 }
879 else {
880 // Use a Ruby-visible frozen snapshot as the backing source. A hidden
881 // temporary frozen String cannot be returned by IO::Buffer#source.
882 string = rb_str_new_frozen(string);
883 return io_buffer_for_make_instance(klass, string, RB_IO_BUFFER_READONLY);
884 }
885}
886
887/*
888 * call-seq:
889 * IO::Buffer.string(length) {|io_buffer| ... read/write io_buffer ...} -> string
890 *
891 * Creates a new string of the given length and yields a zero-copy IO::Buffer
892 * instance to the block which uses the string as a source. The block is
893 * expected to write to the buffer and the string will be returned.
894 *
895 * IO::Buffer.string(4) do |buffer|
896 * buffer.set_string("Ruby")
897 * end
898 * # => "Ruby"
899 */
900VALUE
901rb_io_buffer_type_string(VALUE klass, VALUE length)
902{
903 klass = io_buffer_storage_class(klass);
904 VALUE string = rb_str_new(NULL, RB_NUM2LEN(length));
905
906 struct io_buffer_for_yield_instance_arguments arguments = {
907 .klass = klass,
908 .string = string,
909 .instance = Qnil,
910 };
911
912 rb_ensure(io_buffer_for_yield_instance, (VALUE)&arguments, io_buffer_for_yield_instance_ensure, (VALUE)&arguments);
913
914 return string;
915}
916
917VALUE
918rb_io_buffer_new(void *base, size_t size, enum rb_io_buffer_flags flags)
919{
920 VALUE instance = rb_io_buffer_type_allocate(rb_cIOBufferStorage);
921
922 struct rb_io_buffer_storage *buffer = get_io_buffer_storage(instance);
923
924 io_buffer_storage_initialize(instance, buffer, base, size, flags, Qnil);
925
926 return instance;
927}
928
929VALUE
930rb_io_buffer_new_locked(void *base, size_t size, enum rb_io_buffer_flags flags)
931{
932 VALUE instance = rb_io_buffer_new(base, size, flags);
933
934 rb_io_buffer_lock(instance);
935
936 return instance;
937}
938
939static VALUE
940io_buffer_storage_map(VALUE klass, VALUE io, size_t size, rb_off_t offset, enum rb_io_buffer_flags flags)
941{
942 if (UNLIKELY(offset < 0)) {
943 rb_raise(rb_eArgError,
944 "Offset (%" PRIsVALUE ") can't be negative!",
945 OFFT2NUM(offset));
946 }
947
948 if (UNLIKELY((uintmax_t)offset % RUBY_IO_BUFFER_MAP_ALIGNMENT != 0)) {
949 rb_raise(rb_eArgError,
950 "Offset (%" PRIsVALUE ") must be a multiple of IO::Buffer::MAP_ALIGNMENT (%" PRIuSIZE ")!",
951 OFFT2NUM(offset),
952 RUBY_IO_BUFFER_MAP_ALIGNMENT);
953 }
954
955 VALUE instance = rb_io_buffer_type_allocate(klass);
956 int descriptor = rb_io_descriptor(io);
957 struct rb_io_buffer_storage *storage = get_io_buffer_storage(instance);
958
959 io_buffer_storage_map_file(storage, descriptor, size, offset, flags);
960
961 return instance;
962}
963
964VALUE
965rb_io_buffer_map(VALUE io, size_t size, rb_off_t offset, enum rb_io_buffer_flags flags)
966{
967 return io_buffer_storage_map(rb_cIOBufferStorage, io, size, offset, flags);
968}
969
970/*
971 * call-seq: IO::Buffer.map(file, [size, [offset, [flags]]]) -> io_buffer
972 *
973 * Create an IO::Buffer for reading from +file+ by memory-mapping the file.
974 * +file+ should be a +File+ instance, opened for reading or reading and writing.
975 *
976 * Optional +size+ and +offset+ of mapping can be specified. The +offset+ must
977 * be a multiple of IO::Buffer::MAP_ALIGNMENT. The +size+ does not need to be
978 * aligned. Trying to map an empty file or specify +size+ of 0 will raise an
979 * error.
980 *
981 * By default, the buffer is writable and expects the file to be writable.
982 * It is also shared, so several processes can use the same mapping.
983 *
984 * The mapping mode may be explicitly selected with IO::Buffer::SHARED or
985 * IO::Buffer::PRIVATE, but the two flags are mutually exclusive.
986 * IO::Buffer::MAPPED is accepted but redundant because this method always
987 * creates a mapped buffer. IO::Buffer::INTERNAL and IO::Buffer::EXTERNAL
988 * cannot be specified.
989 *
990 * You can pass IO::Buffer::READONLY in +flags+ argument to make a read-only buffer;
991 * this allows to work with files opened only for reading.
992 * Specifying IO::Buffer::PRIVATE in +flags+ creates a private mapping,
993 * which will not impact other processes or the underlying file.
994 * It also allows updating a buffer created from a read-only file.
995 *
996 * File.write('test.txt', 'test')
997 *
998 * buffer = IO::Buffer.map(File.open('test.txt'), nil, 0, IO::Buffer::READONLY)
999 * # => #<IO::Buffer 0x00000001014a0000+4 EXTERNAL MAPPED FILE SHARED READONLY>
1000 *
1001 * buffer.readonly? # => true
1002 *
1003 * buffer.get_string
1004 * # => "test"
1005 *
1006 * buffer.set_string('b', 0)
1007 * # 'IO::Buffer#set_string': Buffer is not writable! (IO::Buffer::AccessError)
1008 *
1009 * # create read/write mapping: length 4 bytes, offset 0, flags 0
1010 * buffer = IO::Buffer.map(File.open('test.txt', 'r+'), 4, 0)
1011 * buffer.set_string('b', 0)
1012 * # => 1
1013 *
1014 * # Check it
1015 * File.read('test.txt')
1016 * # => "best"
1017 *
1018 * Note that some operating systems may not have cache coherency between mapped
1019 * buffers and file reads.
1020 */
1021static VALUE
1022io_buffer_map(int argc, VALUE *argv, VALUE klass)
1023{
1024 klass = io_buffer_storage_class(klass);
1025 rb_check_arity(argc, 1, 4);
1026
1027 // We might like to handle a string path?
1028 VALUE io = argv[0];
1029
1030 rb_off_t file_size = rb_file_size(io);
1031 // Compiler can confirm that we handled file_size <= 0 case:
1032 if (UNLIKELY(file_size <= 0)) {
1033 rb_raise(rb_eArgError, "Invalid negative or zero file size!");
1034 }
1035 // Here, we assume that file_size is positive:
1036 else if (UNLIKELY((uintmax_t)file_size > SIZE_MAX)) {
1037 rb_raise(rb_eArgError, "File larger than address space!");
1038 }
1039
1040 size_t size;
1041 if (argc >= 2 && !RB_NIL_P(argv[1])) {
1042 size = io_buffer_extract_size(argv[1]);
1043 if (UNLIKELY(size == 0)) {
1044 rb_raise(rb_eArgError, "Size can't be zero!");
1045 }
1046 if (UNLIKELY(size > (size_t)file_size)) {
1047 rb_raise(rb_eArgError,
1048 "Size (%" PRIuSIZE ") can't be larger than "
1049 "file size (%" PRIuSIZE ")",
1050 size,
1051 (size_t)file_size);
1052 }
1053 }
1054 else {
1055 // This conversion should be safe:
1056 size = (size_t)file_size;
1057 }
1058
1059 // This is the file offset, not the buffer offset:
1060 rb_off_t offset = 0;
1061 if (argc >= 3) {
1062 offset = NUM2OFFT(argv[2]);
1063 if (UNLIKELY(offset < 0)) {
1064 rb_raise(rb_eArgError,
1065 "Offset (%" PRIsVALUE ") can't be negative!",
1066 argv[2]);
1067 }
1068 if (UNLIKELY(offset >= file_size)) {
1069 rb_raise(rb_eArgError,
1070 "Offset (%" PRIsVALUE ") can't be larger than "
1071 "file size (%" PRIuSIZE ")",
1072 argv[2],
1073 (size_t)file_size);
1074 }
1075 if (RB_NIL_P(argv[1])) {
1076 // Decrease size if it's set from the actual file size:
1077 size = (size_t)(file_size - offset);
1078 }
1079 else if (UNLIKELY((size_t)(file_size - offset) < size)) {
1080 size_t maximum_offset =
1081 ((size_t)file_size - size) / RUBY_IO_BUFFER_MAP_ALIGNMENT *
1082 RUBY_IO_BUFFER_MAP_ALIGNMENT;
1083 rb_raise(rb_eArgError,
1084 "Offset (%" PRIsVALUE ") can't be larger than "
1085 "%" PRIuSIZE " for requested size (%" PRIuSIZE ")",
1086 argv[2],
1087 maximum_offset,
1088 size);
1089 }
1090 }
1091
1092 enum rb_io_buffer_flags flags = 0;
1093 if (argc >= 4) {
1094 flags = io_buffer_extract_flags(argv[3]);
1095 }
1096 flags = io_buffer_flags_for_map(flags);
1097
1098 return io_buffer_storage_map(klass, io, size, offset, flags);
1099}
1100
1101// Compute the optimal allocation flags for a buffer of the given size.
1102static inline enum rb_io_buffer_flags
1103io_flags_for_size(size_t size)
1104{
1105 if (size >= RUBY_IO_BUFFER_PAGE_SIZE) {
1106 return RB_IO_BUFFER_MAPPED;
1107 }
1108
1109 return RB_IO_BUFFER_INTERNAL;
1110}
1111
1112static inline enum rb_io_buffer_flags
1113io_buffer_flags_for_new(enum rb_io_buffer_flags flags, size_t size)
1114{
1115 if (size == 0) {
1116 // A null buffer has no allocation and therefore no allocation flags:
1117 return 0;
1118 }
1119
1120 if (!(flags & RB_IO_BUFFER_ALLOCATION_FLAGS)) {
1121 if (flags & RB_IO_BUFFER_MAPPING_FLAGS) {
1122 // Mapping properties imply a mapped allocation:
1123 flags |= RB_IO_BUFFER_MAPPED;
1124 }
1125 else {
1126 // No explicit allocation mode was given, so infer one from size:
1127 flags |= io_flags_for_size(size);
1128 }
1129 }
1130
1131 enum rb_io_buffer_flags allocation = flags & RB_IO_BUFFER_ALLOCATION_FLAGS;
1132 RUBY_ASSERT(allocation != 0);
1133
1134 if ((unsigned int)allocation == RB_IO_BUFFER_ALLOCATION_FLAGS) {
1135 rb_raise(rb_eArgError, "Flags can't include both IO::Buffer::INTERNAL and IO::Buffer::MAPPED!");
1136 }
1137
1138 if (flags & RB_IO_BUFFER_EXTERNAL) {
1139 rb_raise(rb_eArgError, "IO::Buffer::EXTERNAL can't be used with IO::Buffer.new!");
1140 }
1141
1142 if ((flags & RB_IO_BUFFER_MAPPING_FLAGS) && allocation != RB_IO_BUFFER_MAPPED) {
1143 rb_raise(rb_eArgError, "IO::Buffer::SHARED and IO::Buffer::PRIVATE require IO::Buffer::MAPPED!");
1144 }
1145
1146 if ((flags & RB_IO_BUFFER_MAPPING_FLAGS) == RB_IO_BUFFER_MAPPING_FLAGS) {
1147 rb_raise(rb_eArgError, "Flags can't include both IO::Buffer::SHARED and IO::Buffer::PRIVATE!");
1148 }
1149
1150 return flags;
1151}
1152
1153/*
1154 * call-seq: IO::Buffer.new([size = DEFAULT_SIZE, [flags]]) -> io_buffer
1155 *
1156 * Create a new zero-filled IO::Buffer of +size+ bytes.
1157 * By default, the buffer will be _internal_: directly allocated chunk
1158 * of the memory. But if the requested +size+ is more than OS-specific
1159 * IO::Buffer::PAGE_SIZE, the buffer would be allocated using the
1160 * virtual memory mechanism (anonymous +mmap+ on Unix, +VirtualAlloc+
1161 * on Windows). The behavior can be forced by passing IO::Buffer::MAPPED
1162 * as a second parameter.
1163 *
1164 * IO::Buffer::SHARED and IO::Buffer::PRIVATE imply IO::Buffer::MAPPED and are
1165 * mutually exclusive. Otherwise, if +flags+ do not include an allocation
1166 * mode, IO::Buffer::INTERNAL or IO::Buffer::MAPPED is inferred from the
1167 * requested size. The two allocation modes are mutually exclusive.
1168 *
1169 * buffer = IO::Buffer.new(4)
1170 * # =>
1171 * # #<IO::Buffer 0x000055b34497ea10+4 INTERNAL>
1172 * # 0x00000000 00 00 00 00 ....
1173 *
1174 * buffer.get_string(0, 1) # => "\x00"
1175 *
1176 * buffer.set_string("test")
1177 * buffer
1178 * # =>
1179 * # #<IO::Buffer 0x000055b34497ea10+4 INTERNAL>
1180 * # 0x00000000 74 65 73 74 test
1181 */
1182VALUE
1183rb_io_buffer_initialize(int argc, VALUE *argv, VALUE self)
1184{
1185 rb_check_frozen(self);
1186 rb_check_arity(argc, 0, 2);
1187
1188 size_t size;
1189 if (argc > 0) {
1190 size = io_buffer_extract_size(argv[0]);
1191 }
1192 else {
1193 size = RUBY_IO_BUFFER_DEFAULT_SIZE;
1194 }
1195
1196 enum rb_io_buffer_flags flags = 0;
1197 if (argc >= 2) {
1198 flags = io_buffer_extract_flags(argv[1]);
1199 }
1200 flags = io_buffer_flags_for_new(flags, size);
1201
1202 struct rb_io_buffer_storage *buffer = get_io_buffer_storage(self);
1203 if (buffer->lock_count) rb_raise(rb_eIOBufferLockedError, "Cannot initialize locked buffer!");
1204 io_buffer_storage_release(buffer);
1205 io_buffer_storage_initialize(self, buffer, NULL, size, flags, Qnil);
1206
1207 return self;
1208}
1209
1210// Resolve `source_base + buffer->base`, with a source base of zero for
1211// source-less buffers (see struct rb_io_buffer_view). Source-backed ranges are
1212// checked against the source's current size, so they survive relocation and
1213// can become valid again after the source regrows.
1214// Returns non-zero if valid, setting `*base`/`*size` (NULL/0 when invalid).
1215// This only inspects metadata and does not enforce read/write permissions;
1216// the accessors below check permissions and expose the appropriate pointer type.
1217// Valid empty ranges may resolve to NULL. Keep the storage locked while using
1218// a resolved pointer across calls that can release the GVL or invoke Ruby.
1219static int
1220io_buffer_try_get_bytes(const struct rb_io_buffer_view *buffer, void **base, size_t *size)
1221{
1222 size_t length = buffer->size;
1223 size_t offset = 0;
1224 void *source_base = NULL;
1225
1226 while (buffer->source != Qnil) {
1227 const struct rb_io_buffer_view *source_buffer = NULL;
1228 size_t source_size;
1229
1230 if (io_buffer_slice_p(buffer)) {
1231 source_buffer = get_io_buffer_view(buffer->source);
1232 source_size = source_buffer->size;
1233 }
1234 else {
1235 // A String-backed buffer is rooted in the pinned String.
1236 RSTRING_GETMEM(buffer->source, source_base, source_size);
1237 }
1238
1239 size_t relative_offset = io_buffer_slice_offset(buffer);
1240 if (relative_offset > source_size || buffer->size > source_size - relative_offset ||
1241 relative_offset > SIZE_MAX - offset) {
1242 *base = NULL;
1243 *size = 0;
1244 return 0;
1245 }
1246
1247 offset += relative_offset;
1248 if (!source_buffer) {
1249 *base = source_base ? (char *)source_base + offset : NULL;
1250 *size = length;
1251 return 1;
1252 }
1253
1254 buffer = source_buffer;
1255 }
1256
1257 // A source-less buffer (allocated, mapped, or borrowed) contributes the
1258 // absolute base pointer. The accumulated offset selects a range within it.
1259 if (io_buffer_slice_p(buffer)) {
1260 // A slice with no source can only be an uninitialized object.
1261 *base = NULL;
1262 *size = 0;
1263 return 0;
1264 }
1265
1266 *base = buffer->base ? (char *)buffer->base + offset : NULL;
1267 *size = length;
1268 return 1;
1269}
1270
1271static int
1272io_buffer_validate(const struct rb_io_buffer_view *buffer)
1273{
1274 void *base;
1275 size_t size;
1276 return io_buffer_try_get_bytes(buffer, &base, &size);
1277}
1278
1279enum rb_io_buffer_flags
1280rb_io_buffer_get_bytes(VALUE self, void **base, size_t *size)
1281{
1282 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1283
1284 if (io_buffer_try_get_bytes(buffer, base, size)) {
1285 enum rb_io_buffer_flags flags = buffer->flags & ~IO_BUFFER_SLICE;
1286 if (io_buffer_readonly_p(buffer)) flags |= RB_IO_BUFFER_READONLY;
1287 return flags;
1288 }
1289
1290 return 0;
1291}
1292
1293static inline void
1294io_buffer_get_bytes_for_writing(const struct rb_io_buffer_view *buffer, void **base, size_t *size)
1295{
1296 if (io_buffer_readonly_p(buffer)) {
1297 rb_raise(rb_eIOBufferAccessError, "Buffer is not writable!");
1298 }
1299
1300 if (!io_buffer_validate(buffer)) {
1301 rb_raise(rb_eIOBufferInvalidatedError, "Buffer is invalid!");
1302 }
1303
1304 io_buffer_try_get_bytes(buffer, base, size);
1305}
1306
1307static void
1308io_buffer_validate_for_writing(const struct rb_io_buffer_view *buffer)
1309{
1310 void *base;
1311 size_t size;
1312 io_buffer_get_bytes_for_writing(buffer, &base, &size);
1313}
1314
1315static struct rb_io_buffer_view *
1316get_io_buffer_view_for_writing(VALUE self)
1317{
1318 rb_check_frozen(self);
1319
1320 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1321 io_buffer_validate_for_writing(buffer);
1322 return buffer;
1323}
1324
1325void
1326rb_io_buffer_get_bytes_for_writing(VALUE self, void **base, size_t *size)
1327{
1328 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1329
1330 io_buffer_get_bytes_for_writing(buffer, base, size);
1331}
1332
1333static void
1334io_buffer_get_bytes_for_reading(const struct rb_io_buffer_view *buffer, const void **base, size_t *size)
1335{
1336 void *writable_base = NULL;
1337 if (!io_buffer_try_get_bytes(buffer, &writable_base, size)) {
1338 rb_raise(rb_eIOBufferInvalidatedError, "Buffer has been invalidated!");
1339 }
1340 *base = writable_base;
1341}
1342
1343static void
1344io_buffer_validate_for_reading(const struct rb_io_buffer_view *buffer)
1345{
1346 const void *base;
1347 size_t size;
1348 io_buffer_get_bytes_for_reading(buffer, &base, &size);
1349}
1350
1351void
1352rb_io_buffer_get_bytes_for_reading(VALUE self, const void **base, size_t *size)
1353{
1354 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1355
1356 io_buffer_get_bytes_for_reading(buffer, base, size);
1357}
1358
1359/*
1360 * call-seq: to_s -> string
1361 *
1362 * Short representation of the buffer. It includes the address, size and
1363 * symbolic flags. This format is subject to change.
1364 *
1365 * puts IO::Buffer.new(4) # uses to_s internally
1366 * # #<IO::Buffer 0x000055769f41b1a0+4 INTERNAL>
1367 */
1368VALUE
1369rb_io_buffer_to_s(VALUE self)
1370{
1371 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1372
1373 VALUE result = rb_str_new_cstr("#<");
1374
1375 rb_str_append(result, rb_class_name(CLASS_OF(self)));
1376
1377 // Resolve the current base (following slice indirection) for display:
1378 void *base = NULL;
1379 size_t size = 0;
1380 io_buffer_try_get_bytes(buffer, &base, &size);
1381 rb_str_catf(result, " %p+%"PRIdSIZE, base, buffer->size);
1382
1383 if (base == NULL) {
1384 rb_str_cat2(result, " NULL");
1385 }
1386
1387 if (buffer->flags & RB_IO_BUFFER_EXTERNAL) {
1388 rb_str_cat2(result, " EXTERNAL");
1389 }
1390
1391 if (buffer->flags & RB_IO_BUFFER_INTERNAL) {
1392 rb_str_cat2(result, " INTERNAL");
1393 }
1394
1395 if (buffer->flags & RB_IO_BUFFER_MAPPED) {
1396 rb_str_cat2(result, " MAPPED");
1397 }
1398
1399 if (buffer->flags & RB_IO_BUFFER_FILE) {
1400 rb_str_cat2(result, " FILE");
1401 }
1402
1403 if (buffer->flags & RB_IO_BUFFER_SHARED) {
1404 rb_str_cat2(result, " SHARED");
1405 }
1406
1407 if (io_buffer_locked(buffer)) {
1408 rb_str_cat2(result, " LOCKED");
1409 }
1410
1411 if (buffer->flags & RB_IO_BUFFER_PRIVATE) {
1412 rb_str_cat2(result, " PRIVATE");
1413 }
1414
1415 if (io_buffer_readonly_p(buffer)) {
1416 rb_str_cat2(result, " READONLY");
1417 }
1418
1419 if (buffer->source != Qnil) {
1420 rb_str_cat2(result, " SLICE");
1421 }
1422
1423 if (!io_buffer_validate(buffer)) {
1424 rb_str_cat2(result, " INVALID");
1425 }
1426
1427 return rb_str_cat2(result, ">");
1428}
1429
1430// 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.
1431// This is used to preallocate the output string.
1432inline static size_t
1433io_buffer_hexdump_output_size(size_t width, size_t size, int first)
1434{
1435 // The preview on the right hand side is 1:1:
1436 size_t total = size;
1437
1438 size_t whole_lines = (size / width);
1439 size_t partial_line = (size % width) ? 1 : 0;
1440
1441 // For each line:
1442 // 1 byte 10 bytes 1 byte width*3 bytes 1 byte size bytes
1443 // (newline) (address) (space) (hexdump ) (space) (preview)
1444 total += (whole_lines + partial_line) * (1 + 10 + width*3 + 1 + 1);
1445
1446 // If the hexdump is the first line, one less newline will be emitted:
1447 if (size && first) total -= 1;
1448
1449 return total;
1450}
1451
1452// Append a hexdump of the given width (bytes per line), base address, size, and whether it is the first line in the output.
1453// If the hexdump is not the first line, it will prepend a newline if there is any output at all.
1454// If formatting here is adjusted, please update io_buffer_hexdump_output_size accordingly.
1455static VALUE
1456io_buffer_hexdump(VALUE string, size_t width, const char *base, size_t length, size_t offset, int first)
1457{
1458 char *text = alloca(width+1);
1459 text[width] = '\0';
1460
1461 for (; offset < length; offset += width) {
1462 memset(text, '\0', width);
1463 if (first) {
1464 rb_str_catf(string, "0x%08" PRIxSIZE " ", offset);
1465 first = 0;
1466 }
1467 else {
1468 rb_str_catf(string, "\n0x%08" PRIxSIZE " ", offset);
1469 }
1470
1471 for (size_t i = 0; i < width; i += 1) {
1472 if (offset+i < length) {
1473 unsigned char value = ((unsigned char*)base)[offset+i];
1474
1475 if (value < 127 && isprint(value)) {
1476 text[i] = (char)value;
1477 }
1478 else {
1479 text[i] = '.';
1480 }
1481
1482 rb_str_catf(string, " %02x", value);
1483 }
1484 else {
1485 rb_str_cat2(string, " ");
1486 }
1487 }
1488
1489 rb_str_catf(string, " %s", text);
1490 }
1491
1492 return string;
1493}
1494
1495/*
1496 * call-seq: inspect -> string
1497 *
1498 * Inspect the buffer and report useful information about it's internal state.
1499 * Only a limited portion of the buffer will be displayed in a hexdump style
1500 * format.
1501 *
1502 * buffer = IO::Buffer.for("Hello World")
1503 * puts buffer.inspect
1504 * # #<IO::Buffer 0x000000010198ccd8+11 EXTERNAL READONLY SLICE>
1505 * # 0x00000000 48 65 6c 6c 6f 20 57 6f 72 6c 64 Hello World
1506 */
1507VALUE
1508rb_io_buffer_inspect(VALUE self)
1509{
1510 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1511
1512 VALUE result = rb_io_buffer_to_s(self);
1513
1514 void *base = NULL;
1515 size_t total = 0;
1516 if (io_buffer_try_get_bytes(buffer, &base, &total) && base) {
1517 // Limit the maximum size generated by inspect:
1518 size_t size = buffer->size;
1519 int clamped = 0;
1520
1521 if (size > RB_IO_BUFFER_INSPECT_HEXDUMP_MAXIMUM_SIZE) {
1522 size = RB_IO_BUFFER_INSPECT_HEXDUMP_MAXIMUM_SIZE;
1523 clamped = 1;
1524 }
1525
1526 io_buffer_hexdump(result, RB_IO_BUFFER_INSPECT_HEXDUMP_WIDTH, base, size, 0, 0);
1527
1528 if (clamped) {
1529 rb_str_catf(result, "\n(and %" PRIuSIZE " more bytes not printed)", buffer->size - size);
1530 }
1531 }
1532
1533 return result;
1534}
1535
1536/*
1537 * call-seq: size -> integer
1538 *
1539 * Returns the size of the buffer that was explicitly set (on creation with ::new
1540 * or on #resize), or deduced on buffer's creation from string or file.
1541 */
1542VALUE
1543rb_io_buffer_size(VALUE self)
1544{
1545 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1546
1547 return SIZET2NUM(buffer->size);
1548}
1549
1550/*
1551 * call-seq: valid? -> true or false
1552 *
1553 * A buffer without a source is always valid, including a null buffer. A
1554 * source-backed buffer is valid when its offset and length fit within its
1555 * source's current size.
1556 *
1557 * Relocating a source does not invalidate a source-backed buffer. Freeing,
1558 * transferring, or shrinking the source can make it invalid; if the same
1559 * source later grows to include the range again, the buffer becomes valid
1560 * and refers to the current contents at its original offset.
1561 *
1562 * An empty source-backed range at offset zero can be valid even when its
1563 * source has no storage. #valid?, #null? and #empty? describe distinct
1564 * properties: a buffer can be valid, null, and empty at the same time.
1565 */
1566static VALUE
1567rb_io_buffer_valid_p(VALUE self)
1568{
1569 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1570
1571 return RBOOL(io_buffer_validate(buffer));
1572}
1573
1574/*
1575 * call-seq: null? -> true or false
1576 *
1577 * Returns whether the buffer has no recorded base address.
1578 *
1579 * A buffer is null if it was freed with #free, transferred with #transfer, or
1580 * was never allocated in the first place. A zero-sized buffer or slice may
1581 * have a non-null address, so #null? and #empty? are distinct properties.
1582 *
1583 * buffer = IO::Buffer.new(0)
1584 * buffer.null? #=> true
1585 *
1586 * buffer = IO::Buffer.new(4)
1587 * buffer.null? #=> false
1588 * buffer.free
1589 * buffer.null? #=> true
1590 */
1591static VALUE
1592rb_io_buffer_null_p(VALUE self)
1593{
1594 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1595
1596 void *base = NULL;
1597 size_t size = 0;
1598 io_buffer_try_get_bytes(buffer, &base, &size);
1599
1600 return RBOOL(base == NULL);
1601}
1602
1603/*
1604 * call-seq: empty? -> true or false
1605 *
1606 * Returns whether the buffer has zero size.
1607 *
1608 * A buffer can be empty but have a non-null address, for example a zero-sized
1609 * slice or a buffer created with ::for from an empty string. Therefore
1610 * #empty? does not imply #null?.
1611 */
1612static VALUE
1613rb_io_buffer_empty_p(VALUE self)
1614{
1615 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1616
1617 return RBOOL(buffer->size == 0);
1618}
1619
1620/*
1621 * call-seq: external? -> true or false
1622 *
1623 * The buffer is _external_ if it references the memory which is not
1624 * allocated or mapped by the buffer itself.
1625 *
1626 * A buffer created using ::for has an external reference to the string's
1627 * memory.
1628 *
1629 * External buffer can't be resized.
1630 */
1631static VALUE
1632rb_io_buffer_external_p(VALUE self)
1633{
1634 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1635
1636 return RBOOL(buffer->flags & RB_IO_BUFFER_EXTERNAL);
1637}
1638
1639/*
1640 * call-seq: internal? -> true or false
1641 *
1642 * If the buffer is _internal_, meaning it references memory allocated by the
1643 * buffer itself.
1644 *
1645 * An internal buffer is not associated with any external memory (e.g. string)
1646 * or file mapping.
1647 *
1648 * Internal buffers are created using ::new and is the default when the
1649 * requested size is less than the IO::Buffer::PAGE_SIZE and it was not
1650 * requested to be mapped on creation.
1651 *
1652 * Internal buffers can be resized. Slices remain valid if their ranges still
1653 * fit within the resized buffer, including when its storage is relocated.
1654 */
1655static VALUE
1656rb_io_buffer_internal_p(VALUE self)
1657{
1658 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1659
1660 return RBOOL(buffer->flags & RB_IO_BUFFER_INTERNAL);
1661}
1662
1663/*
1664 * call-seq: mapped? -> true or false
1665 *
1666 * If the buffer is _mapped_, meaning it references memory mapped by the
1667 * buffer.
1668 *
1669 * Mapped buffers are either anonymous, if created by ::new with the
1670 * IO::Buffer::MAPPED flag or if the size was at least IO::Buffer::PAGE_SIZE,
1671 * or backed by a file if created with ::map.
1672 *
1673 * Mapped buffers can usually be resized. Slices remain valid if their ranges
1674 * still fit within the resized buffer, including when its mapping is moved.
1675 */
1676static VALUE
1677rb_io_buffer_mapped_p(VALUE self)
1678{
1679 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1680
1681 return RBOOL(buffer->flags & RB_IO_BUFFER_MAPPED);
1682}
1683
1684/*
1685 * call-seq: shared? -> true or false
1686 *
1687 * If the buffer is _shared_, meaning it references memory that can be shared
1688 * with other processes (and thus might change without being modified
1689 * locally).
1690 *
1691 * # Create a test file:
1692 * File.write('test.txt', 'test')
1693 *
1694 * # Create a shared mapping from the given file, the file must be opened in
1695 * # read-write mode unless we also specify IO::Buffer::READONLY:
1696 * buffer = IO::Buffer.map(File.open('test.txt', 'r+'), nil, 0)
1697 * # => #<IO::Buffer 0x00007f1bffd5e000+4 EXTERNAL MAPPED SHARED>
1698 *
1699 * # Write to the buffer, which will modify the mapped file:
1700 * buffer.set_string('b', 0)
1701 * # => 1
1702 *
1703 * # The file itself is modified:
1704 * File.read('test.txt')
1705 * # => "best"
1706 */
1707static VALUE
1708rb_io_buffer_shared_p(VALUE self)
1709{
1710 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1711
1712 return RBOOL(buffer->flags & RB_IO_BUFFER_SHARED);
1713}
1714
1715/*
1716 * call-seq: locked? -> true or false
1717 *
1718 * If the buffer is _locked_, its underlying allocation cannot be resized,
1719 * freed or transferred. Locks are shared with slices and may be nested.
1720 *
1721 * Locking is a lifetime mechanism used to ensure buffers don't move while
1722 * being used by a system call or other native operation.
1723 *
1724 * buffer.locked do
1725 * buffer.write(io) # theoretical system call interface
1726 * end
1727 */
1728static VALUE
1729rb_io_buffer_locked_p(VALUE self)
1730{
1731 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1732
1733 return RBOOL(io_buffer_locked(buffer));
1734}
1735
1736/* call-seq: private? -> true or false
1737 *
1738 * If the buffer is _private_, meaning modifications to the buffer will not
1739 * be replicated to the underlying file mapping.
1740 *
1741 * # Create a test file:
1742 * File.write('test.txt', 'test')
1743 *
1744 * # Create a private mapping from the given file. Note that the file here
1745 * # is opened in read-only mode, but it doesn't matter due to the private
1746 * # mapping:
1747 * buffer = IO::Buffer.map(File.open('test.txt'), nil, 0, IO::Buffer::PRIVATE)
1748 * # => #<IO::Buffer 0x00007fce63f11000+4 MAPPED PRIVATE>
1749 *
1750 * # Write to the buffer (invoking CoW of the underlying file buffer):
1751 * buffer.set_string('b', 0)
1752 * # => 1
1753 *
1754 * # The file itself is not modified:
1755 * File.read('test.txt')
1756 * # => "test"
1757 */
1758static VALUE
1759rb_io_buffer_private_p(VALUE self)
1760{
1761 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1762
1763 return RBOOL(buffer->flags & RB_IO_BUFFER_PRIVATE);
1764}
1765
1766static int
1767io_buffer_readonly_p(const struct rb_io_buffer_view *buffer)
1768{
1769 for (;;) {
1770 if (buffer->flags & RB_IO_BUFFER_READONLY)
1771 return 1;
1772
1773 VALUE source = buffer->source;
1774 if (NIL_P(source))
1775 return 0;
1776
1777 if (OBJ_FROZEN(source))
1778 return 1;
1779
1780 if (RB_TYPE_P(source, T_STRING))
1781 return 0;
1782
1783 buffer = get_io_buffer_view(source);
1784 }
1785}
1786
1787int
1788rb_io_buffer_readonly_p(VALUE self)
1789{
1790 const struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1791 return io_buffer_readonly_p(buffer);
1792}
1793
1794/*
1795 * call-seq: readonly? -> true or false
1796 *
1797 * If the buffer is <i>read only</i>, meaning the buffer cannot be modified using
1798 * #set_value, #set_string or #copy and similar.
1799 *
1800 * A buffer created by IO::Buffer.for without a block is read-only, as is one
1801 * backed by a frozen string or a read-only file.
1802 *
1803 * A slice derives read-only access from its current source. Replacing the
1804 * source's storage can therefore change the slice's read-only status.
1805 */
1806static VALUE
1807io_buffer_readonly(VALUE self)
1808{
1809 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1810
1811 return RBOOL(io_buffer_readonly_p(buffer));
1812}
1813
1814static void
1815io_buffer_lock(struct rb_io_buffer_view *buffer)
1816{
1817 struct rb_io_buffer_storage *owner = io_buffer_lock_owner(buffer);
1818
1819 if (owner->lock_count == SIZE_MAX) {
1820 rb_raise(rb_eIOBufferLockedError, "It's locks all the way down!");
1821 }
1822
1823 owner->lock_count += 1;
1824}
1825
1826VALUE
1827rb_io_buffer_lock(VALUE self)
1828{
1829 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1830
1831 io_buffer_lock(buffer);
1832
1833 return self;
1834}
1835
1836static void
1837io_buffer_unlock(struct rb_io_buffer_view *buffer)
1838{
1839 struct rb_io_buffer_storage *owner = io_buffer_lock_owner(buffer);
1840
1841 if (owner->lock_count == 0) {
1842 rb_raise(rb_eIOBufferLockedError, "Buffer not locked!");
1843 }
1844
1845 owner->lock_count -= 1;
1846}
1847
1848VALUE
1849rb_io_buffer_unlock(VALUE self)
1850{
1851 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1852
1853 io_buffer_unlock(buffer);
1854
1855 return self;
1856}
1857
1858int
1859rb_io_buffer_try_unlock(VALUE self)
1860{
1861 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1862 struct rb_io_buffer_storage *owner = io_buffer_lock_owner(buffer);
1863
1864 if (owner->lock_count > 0) {
1865 owner->lock_count -= 1;
1866
1867 return 1;
1868 }
1869
1870 return 0;
1871}
1872
1873static VALUE
1874rb_io_buffer_locked_ensure(VALUE self)
1875{
1876 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1877
1878 io_buffer_unlock(buffer);
1879
1880 return Qnil;
1881}
1882
1884 VALUE self;
1885 VALUE (*callback)(const void *base, size_t size, VALUE argument);
1886 VALUE argument;
1887};
1888
1889static VALUE
1890io_buffer_readable_bytes_call(VALUE _arguments)
1891{
1892 struct io_buffer_readable_bytes_arguments *arguments = (void *)_arguments;
1893
1894 const void *base;
1895 size_t size;
1896 rb_io_buffer_get_bytes_for_reading(arguments->self, &base, &size);
1897
1898 return arguments->callback(base, size, arguments->argument);
1899}
1900
1901VALUE
1902rb_io_buffer_locked_for_reading(VALUE self, VALUE (*callback)(const void *base, size_t size, VALUE argument), VALUE argument)
1903{
1904 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1905 io_buffer_validate_for_reading(buffer);
1906
1907 struct io_buffer_readable_bytes_arguments arguments = {
1908 .self = self,
1909 .callback = callback,
1910 .argument = argument,
1911 };
1912
1913 rb_io_buffer_lock(self);
1914 return rb_ensure(io_buffer_readable_bytes_call, (VALUE)&arguments, rb_io_buffer_locked_ensure, self);
1915}
1916
1918 VALUE self;
1919 VALUE (*callback)(void *base, size_t size, VALUE argument);
1920 VALUE argument;
1921};
1922
1923static VALUE
1924io_buffer_writable_bytes_call(VALUE _arguments)
1925{
1926 struct io_buffer_writable_bytes_arguments *arguments = (void *)_arguments;
1927
1928 void *base;
1929 size_t size;
1930 rb_io_buffer_get_bytes_for_writing(arguments->self, &base, &size);
1931
1932 return arguments->callback(base, size, arguments->argument);
1933}
1934
1935VALUE
1936rb_io_buffer_locked_for_writing(VALUE self, VALUE (*callback)(void *base, size_t size, VALUE argument), VALUE argument)
1937{
1938 get_io_buffer_view_for_writing(self);
1939
1940 struct io_buffer_writable_bytes_arguments arguments = {
1941 .self = self,
1942 .callback = callback,
1943 .argument = argument,
1944 };
1945
1946 rb_io_buffer_lock(self);
1947 return rb_ensure(io_buffer_writable_bytes_call, (VALUE)&arguments, rb_io_buffer_locked_ensure, self);
1948}
1949
1950/*
1951 * call-seq: locked { ... }
1952 *
1953 * Prevents the buffer or its buffer source from being moved or freed while
1954 * the block is executing. Locks are nested and shared with slices backed by
1955 * the same buffer source. The source remains locked until every nested lock
1956 * has been released.
1957 *
1958 * Locking protects allocation lifetime; it does not serialize access to the
1959 * bytes. Code that shares mutable buffer contents between threads must still
1960 * use appropriate synchronization.
1961 *
1962 * buffer = IO::Buffer.new(4)
1963 * buffer.locked? #=> false
1964 *
1965 * Fiber.schedule do
1966 * buffer.locked do
1967 * buffer.write(io) # theoretical system call interface
1968 * end
1969 * end
1970 *
1971 * Fiber.schedule do
1972 * buffer.locked do
1973 * buffer.set_string("test", 0) # Nested locking is allowed.
1974 * end
1975 * end
1976 */
1977VALUE
1978rb_io_buffer_locked(VALUE self)
1979{
1980 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
1981
1982 // Only yield the block for a currently valid view. In particular, an
1983 // invalid slice should not lock its source.
1984 io_buffer_validate_for_reading(buffer);
1985
1986 io_buffer_lock(buffer);
1987
1988 return rb_ensure(rb_yield, self, rb_io_buffer_locked_ensure, self);
1989}
1990
1991VALUE
1992rb_io_buffer_free(VALUE self)
1993{
1994 struct rb_io_buffer_storage *buffer = get_io_buffer_storage(self);
1995
1996 if (buffer->lock_count) {
1997 rb_raise(rb_eIOBufferLockedError, "Buffer is locked!");
1998 }
1999
2000 io_buffer_storage_release(buffer);
2001
2002 return self;
2003}
2004
2005/*
2006 * call-seq: free -> self
2007 *
2008 * If the buffer references memory, release it back to the operating system.
2009 * * for a _mapped_ buffer (e.g. from file): unmap.
2010 * * for a buffer created from scratch: free memory.
2011 * * for a buffer created from string: undo the association.
2012 *
2013 * After releasing any referenced memory, the buffer is reset to a valid,
2014 * empty, null state. It has no backing storage and its size is zero.
2015 * Zero-length operations remain valid, while operations requiring bytes fail
2016 * normal bounds checking.
2017 *
2018 * Repeated calls on an unlocked, unfrozen Storage are harmless and return
2019 * +self+. You can resize the buffer to allocate new storage. This method is
2020 * not available on Slice, which never manages storage.
2021 *
2022 * buffer = IO::Buffer.for('test')
2023 * buffer.free
2024 * # => #<IO::Buffer 0x0000000000000000+0 NULL>
2025 *
2026 * buffer.null? # => true
2027 * buffer.empty? # => true
2028 * buffer.valid? # => true
2029 * buffer.get_string # => ""
2030 *
2031 * buffer.get_value(:U8, 0) # raises ArgumentError
2032 *
2033 * A frozen buffer cannot be freed, as that would release the memory its
2034 * contents live in:
2035 *
2036 * buffer = IO::Buffer.for('test').freeze
2037 * buffer.free
2038 * # in `free': can't modify frozen IO::Buffer (FrozenError)
2039 */
2040static VALUE
2041io_buffer_free(VALUE self)
2042{
2043 rb_check_frozen(self);
2044
2045 return rb_io_buffer_free(self);
2046}
2047
2048VALUE rb_io_buffer_free_locked(VALUE self)
2049{
2050 struct rb_io_buffer_storage *buffer = get_io_buffer_storage(self);
2051
2052 // This function is used to invalidate temporary wrappers around borrowed
2053 // memory. If another lock remains, the owner cannot safely end the
2054 // lifetime of that memory while another operation still retains it.
2055 if (buffer->lock_count != 1) {
2056 rb_bug("rb_io_buffer_free_locked: expected lock count 1, got %" PRIuSIZE, buffer->lock_count);
2057 }
2058
2059 io_buffer_unlock(&buffer->view);
2060 io_buffer_storage_release(buffer);
2061
2062 return self;
2063}
2064
2065static bool
2066size_sum_is_bigger_than(size_t a, size_t b, size_t x)
2067{
2068 struct rbimpl_size_overflow_tag size = rbimpl_size_add_overflow(a, b);
2069 return size.overflowed || size.result > x;
2070}
2071
2072// Validate that access to the buffer is within bounds, assuming you want to
2073// access length bytes from the specified offset.
2074static inline void
2075io_buffer_validate_range(const struct rb_io_buffer_view *buffer, size_t offset, size_t length)
2076{
2077 io_buffer_validate_for_reading(buffer);
2078
2079 if (size_sum_is_bigger_than(offset, length, buffer->size)) {
2080 rb_raise(rb_eArgError, "Specified offset+length is bigger than the buffer size!");
2081 }
2082}
2083
2084/*
2085 * call-seq: hexdump([offset, [length, [width]]]) -> string or nil
2086 *
2087 * Returns a human-readable string representation of the buffer. The exact
2088 * format is subject to change.
2089 *
2090 * Returns +nil+ if the buffer does not reference any memory, that is, if
2091 * #null? returns +true+ (for example after #free or #transfer).
2092 *
2093 * buffer = IO::Buffer.for("Hello World")
2094 * puts buffer.hexdump
2095 * # 0x00000000 48 65 6c 6c 6f 20 57 6f 72 6c 64 Hello World
2096 *
2097 * As buffers are usually fairly big, you may want to limit the output by
2098 * specifying the offset and length:
2099 *
2100 * puts buffer.hexdump(6, 5)
2101 * # 0x00000006 57 6f 72 6c 64 World
2102 */
2103static VALUE
2104rb_io_buffer_hexdump(int argc, VALUE *argv, VALUE self)
2105{
2106 rb_check_arity(argc, 0, 3);
2107
2108 size_t offset, length;
2109 struct rb_io_buffer_view *buffer = io_buffer_extract_offset_length(self, argc, argv, &offset, &length);
2110
2111 size_t width = RB_IO_BUFFER_HEXDUMP_DEFAULT_WIDTH;
2112 if (argc >= 3) {
2113 width = io_buffer_extract_width(argv[2], 1);
2114 }
2115
2116 // This may raise an exception if the offset/length is invalid:
2117 io_buffer_validate_range(buffer, offset, length);
2118
2119 VALUE result = Qnil;
2120
2121 void *base = NULL;
2122 size_t size = 0;
2123 if (io_buffer_try_get_bytes(buffer, &base, &size) && base) {
2124 result = rb_str_buf_new(io_buffer_hexdump_output_size(width, length, 1));
2125
2126 io_buffer_hexdump(result, width, base, offset+length, offset, 1);
2127 }
2128
2129 return result;
2130}
2131
2132static VALUE
2133rb_io_buffer_slice(struct rb_io_buffer_view *buffer, VALUE self, size_t offset, size_t length)
2134{
2135 io_buffer_validate_range(buffer, offset, length);
2136
2137 VALUE instance = io_buffer_slice_allocate(rb_cIOBufferSlice);
2138 struct rb_io_buffer_view *slice = get_io_buffer_view(instance);
2139
2140 slice->size = length;
2141
2142 // Retain the immediate parent and store an offset into its current view.
2143 // Address resolution follows the source chain when the bytes are accessed.
2144 slice->base = (void *)(uintptr_t)offset;
2145 RB_OBJ_WRITE(instance, &slice->source, self);
2146
2147 return instance;
2148}
2149
2150/*
2151 * call-seq: IO::Buffer::Slice.new(source, [offset, [length]]) -> slice
2152 *
2153 * Creates a parent-relative view of a Buffer or another Slice. The source is
2154 * retained, not copied. Resizing or advancing this view never allocates storage.
2155 */
2156static VALUE
2157io_buffer_slice_initialize(int argc, VALUE *argv, VALUE self)
2158{
2159 rb_check_frozen(self);
2160 rb_check_arity(argc, 1, 3);
2161 struct rb_io_buffer_view *slice = get_io_buffer_view(self);
2162 if (!NIL_P(slice->source)) rb_raise(rb_eRuntimeError, "Slice is already initialized!");
2163
2164 VALUE source = argv[0];
2165 size_t offset, length;
2166 struct rb_io_buffer_view *parent = io_buffer_extract_offset_length(source, argc-1, argv+1, &offset, &length);
2167 io_buffer_validate_range(parent, offset, length);
2168
2169 slice = get_io_buffer_view(self);
2170 if (!NIL_P(slice->source)) rb_raise(rb_eRuntimeError, "Slice is already initialized!");
2171 slice->base = (void *)(uintptr_t)offset;
2172 slice->size = length;
2173 RB_OBJ_WRITE(self, &slice->source, source);
2174 return self;
2175}
2176
2177/*
2178 * call-seq:
2179 * dup -> slice
2180 * clone -> slice
2181 *
2182 * Copies the view, retaining the same source, offset, and size without
2183 * copying the underlying bytes. Advancing or resizing the copy does not
2184 * change the original view; writes through either view affect shared storage.
2185 *
2186 * buffer = IO::Buffer.new(6)
2187 * buffer.set_string("abcdef")
2188 * slice = buffer.slice(1, 3)
2189 * copy = slice.dup
2190 * copy.source.equal?(slice.source) # => true
2191 * copy.advance(1)
2192 * copy.get_string # => "cd"
2193 * slice.get_string # => "bcd"
2194 * copy.set_string("XY")
2195 * buffer.get_string # => "abXYef"
2196 *
2197 * This differs from IO::Buffer::Storage#dup, which copies the bytes into independent
2198 * storage. The usual Object#dup and Object#clone frozen-state rules apply.
2199 */
2200static VALUE
2201io_buffer_slice_initialize_copy(VALUE self, VALUE other)
2202{
2203 if (self == other) return self;
2204 rb_check_frozen(self);
2205 struct rb_io_buffer_view *slice = get_io_buffer_view(self);
2206 const struct rb_io_buffer_view *original = get_io_buffer_view(other);
2207 if (!io_buffer_slice_p(original)) rb_raise(rb_eTypeError, "Expected IO::Buffer::Slice!");
2208 if (!NIL_P(slice->source)) rb_raise(rb_eRuntimeError, "Slice is already initialized!");
2209
2210 slice->base = original->base;
2211 slice->size = original->size;
2212 slice->flags = original->flags;
2213 RB_OBJ_WRITE(self, &slice->source, original->source);
2214 return self;
2215}
2216
2217/*
2218 * call-seq: source -> io_buffer, string, or nil
2219 *
2220 * Returns the object backing this view, or +nil+ for a source-less buffer.
2221 * A slice's source is the buffer on which #slice was called, including when
2222 * that buffer is itself a slice. The source is retained while the view lives.
2223 *
2224 * root = IO::Buffer.new(8)
2225 * parent = root.slice(1, 6)
2226 * child = parent.slice(1, 2)
2227 * child.source.equal?(parent) # => true
2228 * parent.source.equal?(root) # => true
2229 * root.source # => nil
2230 *
2231 * For a String-backed buffer the source is its backing String. Without a
2232 * block, IO::Buffer.for may use a frozen internal copy rather than the
2233 * original String. A source-less buffer may own or borrow its memory;
2234 * a +nil+ source does not imply allocation ownership.
2235 *
2236 * An invalid slice still retains and returns its source. Storage#free or
2237 * Storage#transfer clears that Storage object's source; Slice has neither operation.
2238 * There is no source setter.
2239 */
2240static VALUE
2241io_buffer_source(VALUE self)
2242{
2243 return get_io_buffer_view(self)->source;
2244}
2245
2246/*
2247 * call-seq: slice([offset, [length]]) -> io_buffer
2248 *
2249 * Produce another IO::Buffer which is a slice (or view into) the current one
2250 * starting at +offset+ bytes and going for +length+ bytes.
2251 *
2252 * Slicing does not copy memory. The slice retains +self+ as its source and
2253 * tracks a logical offset and length within that view. Nested slices retain
2254 * their immediate parent rather than being flattened.
2255 *
2256 * A slice becomes invalid if its source is freed, transferred, resized so
2257 * that the slice is outside its bounds, or otherwise invalidated. It becomes
2258 * valid again if the source becomes valid and the range fits within it.
2259 * Reallocating the underlying storage does not invalidate the slice.
2260 *
2261 * If the offset is not given, it will be zero. If the offset is negative, it
2262 * will raise an ArgumentError.
2263 *
2264 * If the length is not given, the slice will be as long as the original
2265 * buffer minus the specified offset. If the length is negative, it will raise
2266 * an ArgumentError.
2267 *
2268 * Raises RuntimeError if the <tt>offset+length</tt> is out of the current
2269 * buffer's bounds.
2270 *
2271 * string = 'test'
2272 * buffer = IO::Buffer.for(string).dup
2273 *
2274 * slice = buffer.slice
2275 * # =>
2276 * # #<IO::Buffer 0x0000000108338e68+4 SLICE>
2277 * # 0x00000000 74 65 73 74 test
2278 *
2279 * buffer.slice(2)
2280 * # =>
2281 * # #<IO::Buffer 0x0000000108338e6a+2 SLICE>
2282 * # 0x00000000 73 74 st
2283 *
2284 * slice = buffer.slice(1, 2)
2285 * # =>
2286 * # #<IO::Buffer 0x00007fc3d34ebc49+2 SLICE>
2287 * # 0x00000000 65 73 es
2288 *
2289 * # Put "o" into 0s position of the slice
2290 * slice.set_string('o', 0)
2291 * slice
2292 * # =>
2293 * # #<IO::Buffer 0x00007fc3d34ebc49+2 SLICE>
2294 * # 0x00000000 6f 73 os
2295 *
2296 * # it is also visible at position 1 of the original buffer
2297 * buffer
2298 * # =>
2299 * # #<IO::Buffer 0x00007fc3d31e2d80+4 INTERNAL>
2300 * # 0x00000000 74 6f 73 74 tost
2301 */
2302static VALUE
2303io_buffer_slice(int argc, VALUE *argv, VALUE self)
2304{
2305 rb_check_arity(argc, 0, 2);
2306
2307 size_t offset, length;
2308 struct rb_io_buffer_view *buffer = io_buffer_extract_offset_length(self, argc, argv, &offset, &length);
2309
2310 return rb_io_buffer_slice(buffer, self, offset, length);
2311}
2312
2313VALUE
2314rb_io_buffer_transfer(VALUE self)
2315{
2316 struct rb_io_buffer_storage *buffer = get_io_buffer_storage(self);
2317
2318 if (buffer->lock_count) {
2319 rb_raise(rb_eIOBufferLockedError, "Cannot transfer ownership of locked buffer!");
2320 }
2321
2322 VALUE instance = rb_io_buffer_type_allocate(rb_class_of(self));
2323 struct rb_io_buffer_storage *transferred = get_io_buffer_storage(instance);
2324
2325 *transferred = *buffer;
2326 io_buffer_storage_zero(buffer);
2327
2328 return instance;
2329}
2330
2331/*
2332 * call-seq: transfer -> new_io_buffer
2333 *
2334 * Transfers ownership of the underlying memory to a new buffer, causing the
2335 * current buffer to become uninitialized.
2336 *
2337 * buffer = IO::Buffer.for('test')
2338 * other = buffer.transfer
2339 * other
2340 * # =>
2341 * # #<IO::Buffer 0x00007f136a15f7b0+4 EXTERNAL READONLY SLICE>
2342 * # 0x00000000 74 65 73 74 test
2343 * buffer
2344 * # =>
2345 * # #<IO::Buffer 0x0000000000000000+0 NULL EXTERNAL READONLY>
2346 * buffer.null?
2347 * # => true
2348 *
2349 * A frozen buffer cannot transfer ownership, as that would leave it
2350 * uninitialized:
2351 *
2352 * buffer = IO::Buffer.for('test').freeze
2353 * buffer.transfer
2354 * # in `transfer': can't modify frozen IO::Buffer (FrozenError)
2355 */
2356static VALUE
2357io_buffer_transfer(VALUE self)
2358{
2359 rb_check_frozen(self);
2360
2361 return rb_io_buffer_transfer(self);
2362}
2363
2364static void
2365io_buffer_storage_resize_clear(const struct rb_io_buffer_storage *storage, void* base, size_t size)
2366{
2367 if (size > storage->view.size) {
2368 memset((unsigned char*)base+storage->view.size, 0, size - storage->view.size);
2369 }
2370}
2371
2372static void
2373io_buffer_storage_resize_copy(VALUE self, struct rb_io_buffer_storage *storage, size_t size)
2374{
2375 // Allocate and copy before releasing the old storage.
2376 struct rb_io_buffer_storage resized = {0};
2377 enum rb_io_buffer_flags flags = io_flags_for_size(size) | (storage->view.flags & RB_IO_BUFFER_READONLY);
2378 io_buffer_storage_initialize(self, &resized, NULL, size, flags, Qnil);
2379
2380 if (storage->view.base) {
2381 size_t preserve = storage->view.size;
2382 if (preserve > size) preserve = size;
2383 memcpy(resized.view.base, storage->view.base, preserve);
2384
2385 io_buffer_storage_resize_clear(storage, resized.view.base, size);
2386 }
2387
2388 io_buffer_storage_release(storage);
2389 *storage = resized;
2390}
2391
2392void
2393rb_io_buffer_advance(VALUE self, size_t amount)
2394{
2395 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
2396
2397 if (io_buffer_owning_p(buffer)) {
2398 rb_raise(rb_eIOBufferAccessError, "Cannot advance an owning buffer!");
2399 }
2400
2401 if (!io_buffer_validate(buffer)) {
2402 rb_raise(rb_eIOBufferInvalidatedError, "Buffer has been invalidated!");
2403 }
2404
2405 if (amount > buffer->size) {
2406 rb_raise(rb_eArgError, "Advance amount exceeds buffer size!");
2407 }
2408
2409 if (buffer->source != Qnil) {
2410 // Source-backed buffers store an offset into their immediate source.
2411 // Advance the offset without changing any ancestor's range.
2412 buffer->base = (void *)(uintptr_t)(io_buffer_slice_offset(buffer) + amount);
2413 }
2414 else if (buffer->base) {
2415 // Source-less borrowed buffers store their pointer directly.
2416 buffer->base = (char *)buffer->base + amount;
2417 }
2418
2419 buffer->size -= amount;
2420}
2421
2422static void
2423io_buffer_resize_slice(struct rb_io_buffer_view *slice, size_t size)
2424{
2425 if (NIL_P(slice->source)) rb_raise(rb_eIOBufferInvalidatedError, "Uninitialized slice!");
2426 struct rb_io_buffer_view *source = get_io_buffer_view(slice->source);
2427
2428 void *source_base = NULL;
2429 size_t source_size = 0;
2430
2431 if (!io_buffer_try_get_bytes(source, &source_base, &source_size)) {
2432 rb_raise(rb_eIOBufferInvalidatedError, "Buffer is invalid!");
2433 }
2434
2435 size_t offset = io_buffer_slice_offset(slice);
2436
2437 if (offset > source_size) {
2438 rb_raise(rb_eIOBufferInvalidatedError, "Buffer is invalid!");
2439 }
2440
2441 if (size > source_size - offset) {
2442 rb_raise(rb_eArgError, "Resized slice exceeds its source buffer!");
2443 }
2444
2445 // Validate the requested range rather than the current range so that
2446 // shrinking a slice can restore its validity after the source shrinks.
2447 slice->size = size;
2448}
2449
2450static void
2451io_buffer_storage_resize(VALUE self, struct rb_io_buffer_storage *storage, size_t size)
2452{
2453 struct rb_io_buffer_view *buffer = &storage->view;
2454 io_buffer_validate_for_reading(buffer);
2455
2456 if (storage->lock_count) {
2457 rb_raise(rb_eIOBufferLockedError, "Cannot resize locked buffer!");
2458 }
2459
2460 // An external buffer (including a String-backed buffer, whose base is an
2461 // offset into the source) does not own its memory and cannot be resized.
2462 // This must be checked before the empty-buffer case below, since a
2463 // String-backed buffer at offset 0 has a NULL `base`.
2464 if (buffer->flags & RB_IO_BUFFER_EXTERNAL) {
2465 rb_raise(rb_eIOBufferAccessError, "Cannot resize external buffer!");
2466 }
2467
2468 if (buffer->base == NULL) {
2469 io_buffer_storage_initialize(self, storage, NULL, size, io_flags_for_size(size), Qnil);
2470 return;
2471 }
2472
2473 if (size == 0) {
2474 io_buffer_storage_release(storage);
2475 return;
2476 }
2477
2478#if defined(HAVE_MREMAP) && defined(MREMAP_MAYMOVE)
2479 if (buffer->flags & RB_IO_BUFFER_MAPPED) {
2480 void *base = mremap(buffer->base, buffer->size, size, MREMAP_MAYMOVE);
2481
2482 if (base == MAP_FAILED) {
2483 rb_sys_fail("rb_io_buffer_resize:mremap");
2484 }
2485
2486 io_buffer_storage_resize_clear(storage, base, size);
2487
2488 buffer->base = base;
2489 buffer->size = size;
2490
2491 return;
2492 }
2493#endif
2494
2495 if (buffer->flags & RB_IO_BUFFER_INTERNAL) {
2496 void *base = realloc(buffer->base, size);
2497
2498 if (!base) {
2499 rb_sys_fail("rb_io_buffer_resize:realloc");
2500 }
2501
2502 io_buffer_storage_resize_clear(storage, base, size);
2503
2504 buffer->base = base;
2505 buffer->size = size;
2506
2507 return;
2508 }
2509
2510 io_buffer_storage_resize_copy(self, storage, size);
2511}
2512
2513void
2514rb_io_buffer_resize(VALUE self, size_t size)
2515{
2516 struct rb_io_buffer_view *view = get_io_buffer_view(self);
2517 if (io_buffer_slice_p(view)) {
2518 io_buffer_resize_slice(view, size);
2519 }
2520 else {
2521 io_buffer_storage_resize(self, io_buffer_storage_from_view(view), size);
2522 }
2523}
2524
2525/*
2526 * call-seq: resize(new_size) -> self
2527 *
2528 * Resizes a buffer to a +new_size+ bytes, preserving its content.
2529 * Depending on the old and new size, the memory area associated with
2530 * the buffer might be either extended, or rellocated at different
2531 * address with content being copied.
2532 *
2533 * buffer = IO::Buffer.new(4)
2534 * buffer.set_string("test", 0)
2535 * buffer.resize(8) # resize to 8 bytes
2536 * # =>
2537 * # #<IO::Buffer 0x0000555f5d1a1630+8 INTERNAL>
2538 * # 0x00000000 74 65 73 74 00 00 00 00 test....
2539 *
2540 * When the buffer is a slice, resizing changes the size of the view without
2541 * modifying the source buffer or allocating new storage. The resized view
2542 * must remain within the source buffer. Growing the view exposes the existing
2543 * bytes in the source; they are not cleared. Because the source allocation
2544 * does not change, a slice can be resized while its source is locked.
2545 *
2546 * External owning buffers (created with ::for), and locked owning buffers
2547 * cannot be resized. Frozen buffers cannot be resized.
2548 */
2549static VALUE
2550io_buffer_resize(VALUE self, VALUE size)
2551{
2552 rb_check_frozen(self);
2553
2554 rb_io_buffer_resize(self, io_buffer_extract_size(size));
2555
2556 return self;
2557}
2558
2559/*
2560 * call-seq: advance(amount) -> self
2561 *
2562 * Advances the beginning of a non-owning buffer view by +amount+ bytes,
2563 * reducing its size by the same amount. The backing memory is not moved or
2564 * modified. The buffer must refer to memory managed elsewhere or be a slice;
2565 * a buffer which owns its allocation cannot be advanced.
2566 *
2567 * The source and allocation lock count are unchanged. Advancing is allowed
2568 * while the bytes are read-only or the allocation is locked, because it only
2569 * changes the view. If +amount+ equals the current size, the buffer becomes
2570 * an empty view at its previous end.
2571 *
2572 * Raises ArgumentError if +amount+ is negative or exceeds the current size,
2573 * IO::Buffer::InvalidatedError if the view is invalid, or
2574 * IO::Buffer::AccessError if the buffer owns its allocation. A frozen buffer
2575 * cannot be advanced.
2576 *
2577 * buffer = IO::Buffer.for("test")
2578 * buffer.advance(1)
2579 * buffer.get_string # => "est"
2580 */
2581static VALUE
2582io_buffer_advance(VALUE self, VALUE amount)
2583{
2584 rb_check_frozen(self);
2585
2586 size_t size = io_buffer_extract_amount(amount);
2587
2588 // Argument conversion may call Ruby code which freezes the receiver.
2589 rb_check_frozen(self);
2590
2591 rb_io_buffer_advance(self, size);
2592
2593 return self;
2594}
2595
2596/*
2597 * call-seq: <=>(other) -> integer
2598 *
2599 * Returns a negative integer, zero, or a positive integer if the receiver is
2600 * less than, equal to, or greater than +other+, respectively.
2601 *
2602 * Buffers are compared by size first, and if the sizes are equal, by the exact
2603 * contents of the memory they are referencing using +memcmp+. Only the sign of
2604 * the returned integer is meaningful; the result of +memcmp+ is returned as is.
2605 *
2606 * IO::Buffer.for("abc") <=> IO::Buffer.for("abc") # => 0
2607 * IO::Buffer.for("abc") <=> IO::Buffer.for("ab") # => 1
2608 * IO::Buffer.for("abc") <=> IO::Buffer.for("abd") # => -1
2609 */
2610static VALUE
2611rb_io_buffer_compare(VALUE self, VALUE other)
2612{
2613 const void *ptr1, *ptr2;
2614 size_t size1, size2;
2615
2616 rb_io_buffer_get_bytes_for_reading(self, &ptr1, &size1);
2617 rb_io_buffer_get_bytes_for_reading(other, &ptr2, &size2);
2618
2619 if (size1 < size2) {
2620 return RB_INT2NUM(-1);
2621 }
2622
2623 if (size1 > size2) {
2624 return RB_INT2NUM(1);
2625 }
2626
2627 if (size1 == 0) {
2628 return RB_INT2NUM(0);
2629 }
2630
2631 RUBY_ASSERT(ptr1 != NULL);
2632 RUBY_ASSERT(ptr2 != NULL);
2633 return RB_INT2NUM(memcmp(ptr1, ptr2, size1));
2634}
2635
2636/*
2637 * call-seq: ==(other) -> true or false
2638 *
2639 * Returns whether +other+ is an IO::Buffer with the same contents as the
2640 * receiver.
2641 *
2642 * IO::Buffer.for("abc") == IO::Buffer.for("abc") # => true
2643 * IO::Buffer.for("abc") == IO::Buffer.for("ab") # => false
2644 * IO::Buffer.for("abc") == "abc" # => false
2645 */
2646static VALUE
2647io_buffer_equal(VALUE self, VALUE other)
2648{
2649 if (!rb_io_buffer_p(other)) return Qfalse;
2650
2651 return RBOOL(rb_io_buffer_compare(self, other) == INT2FIX(0));
2652}
2653
2654static void
2655io_buffer_validate_type(size_t size, size_t offset, size_t extend)
2656{
2657 if (size_sum_is_bigger_than(offset, extend, size)) {
2658 rb_raise(rb_eArgError, "Type extends beyond end of buffer! (offset=%"PRIdSIZE" > size=%"PRIdSIZE")", offset, size);
2659 }
2660}
2661
2662// Lower case: little endian.
2663// Upper case: big endian (network endian).
2664//
2665// :U8 | unsigned 8-bit integer.
2666// :S8 | signed 8-bit integer.
2667//
2668// :u16, :U16 | unsigned 16-bit integer.
2669// :s16, :S16 | signed 16-bit integer.
2670//
2671// :u32, :U32 | unsigned 32-bit integer.
2672// :s32, :S32 | signed 32-bit integer.
2673//
2674// :u64, :U64 | unsigned 64-bit integer.
2675// :s64, :S64 | signed 64-bit integer.
2676//
2677// :u128, :U128 | unsigned 128-bit integer.
2678// :s128, :S128 | signed 128-bit integer.
2679//
2680// :f32, :F32 | 32-bit floating point number.
2681// :f64, :F64 | 64-bit floating point number.
2682
2683#define ruby_swap8(value) value
2684
2685union swapf32 {
2686 uint32_t integral;
2687 float value;
2688};
2689
2690static float
2691ruby_swapf32(float value)
2692{
2693 union swapf32 swap = {.value = value};
2694 swap.integral = ruby_swap32(swap.integral);
2695 return swap.value;
2696}
2697
2698union swapf64 {
2699 uint64_t integral;
2700 double value;
2701};
2702
2703static double
2704ruby_swapf64(double value)
2705{
2706 union swapf64 swap = {.value = value};
2707 swap.integral = ruby_swap64(swap.integral);
2708 return swap.value;
2709}
2710
2711// Structures and conversion functions are now in numeric.h/numeric.c
2712// Unified swap function for 128-bit integers (works with both signed and unsigned)
2713// Since both rb_uint128_t and rb_int128_t have the same memory layout,
2714// we can use a union to make the swap function work with both types
2715static inline rb_uint128_t
2716ruby_swap128_uint(rb_uint128_t x)
2717{
2718 rb_uint128_t result;
2719#ifdef HAVE_UINT128_T
2720#if __has_builtin(__builtin_bswap128)
2721 result.value = __builtin_bswap128(x.value);
2722#else
2723 // Manual byte swap for 128-bit integers
2724 uint64_t low = (uint64_t)x.value;
2725 uint64_t high = (uint64_t)(x.value >> 64);
2726 low = ruby_swap64(low);
2727 high = ruby_swap64(high);
2728 result.value = ((uint128_t)low << 64) | high;
2729#endif
2730#else
2731 // Fallback swap function using two 64-bit integers
2732 // For big-endian data on little-endian host (or vice versa):
2733 // 1. Swap bytes within each 64-bit part
2734 // 2. Swap the order of the parts (since big-endian stores high first, little-endian stores low first)
2735 result.parts.low = ruby_swap64(x.parts.high);
2736 result.parts.high = ruby_swap64(x.parts.low);
2737#endif
2738 return result;
2739}
2740
2741static inline rb_int128_t
2742ruby_swap128_int(rb_int128_t x)
2743{
2744 union uint128_int128_conversion conversion = {
2745 .int128 = x
2746 };
2747 conversion.uint128 = ruby_swap128_uint(conversion.uint128);
2748 return conversion.int128;
2749}
2750
2751#define IO_BUFFER_VALIDATE_TYPE_FOR_WRITING(buffer, base, size, offset, type) \
2752 (io_buffer_get_bytes_for_writing(buffer, &(base), &(size)), \
2753 io_buffer_validate_type(size, offset, sizeof(type)))
2754
2755#define IO_BUFFER_DECLARE_TYPE(name, type, endian, wrap, unwrap, swap) \
2756static ID RB_IO_BUFFER_DATA_TYPE_##name; \
2757\
2758static VALUE \
2759io_buffer_read_##name(const void* base, size_t size, size_t *offset) \
2760{ \
2761 io_buffer_validate_type(size, *offset, sizeof(type)); \
2762 type value; \
2763 memcpy(&value, (char*)base + *offset, sizeof(type)); \
2764 if (endian != RB_IO_BUFFER_HOST_ENDIAN) value = swap(value); \
2765 *offset += sizeof(type); \
2766 return wrap(value); \
2767} \
2768\
2769static void \
2770io_buffer_write_##name(struct rb_io_buffer_view* buffer, size_t *offset, VALUE _value) \
2771{ \
2772 void* base; size_t size; \
2773 IO_BUFFER_VALIDATE_TYPE_FOR_WRITING(buffer, base, size, *offset, type); \
2774 type value = unwrap(_value); \
2775 IO_BUFFER_VALIDATE_TYPE_FOR_WRITING(buffer, base, size, *offset, type); \
2776 if (endian != RB_IO_BUFFER_HOST_ENDIAN) value = swap(value); \
2777 memcpy((char*)base + *offset, &value, sizeof(type)); \
2778 *offset += sizeof(type); \
2779} \
2780\
2781enum { \
2782 RB_IO_BUFFER_DATA_TYPE_##name##_SIZE = sizeof(type) \
2783};
2784
2785IO_BUFFER_DECLARE_TYPE(U8, uint8_t, RB_IO_BUFFER_BIG_ENDIAN, RB_UINT2NUM, RB_NUM2UINT, ruby_swap8)
2786IO_BUFFER_DECLARE_TYPE(S8, int8_t, RB_IO_BUFFER_BIG_ENDIAN, RB_INT2NUM, RB_NUM2INT, ruby_swap8)
2787
2788IO_BUFFER_DECLARE_TYPE(u16, uint16_t, RB_IO_BUFFER_LITTLE_ENDIAN, RB_UINT2NUM, RB_NUM2UINT, ruby_swap16)
2789IO_BUFFER_DECLARE_TYPE(U16, uint16_t, RB_IO_BUFFER_BIG_ENDIAN, RB_UINT2NUM, RB_NUM2UINT, ruby_swap16)
2790IO_BUFFER_DECLARE_TYPE(s16, int16_t, RB_IO_BUFFER_LITTLE_ENDIAN, RB_INT2NUM, RB_NUM2INT, ruby_swap16)
2791IO_BUFFER_DECLARE_TYPE(S16, int16_t, RB_IO_BUFFER_BIG_ENDIAN, RB_INT2NUM, RB_NUM2INT, ruby_swap16)
2792
2793IO_BUFFER_DECLARE_TYPE(u32, uint32_t, RB_IO_BUFFER_LITTLE_ENDIAN, RB_UINT2NUM, RB_NUM2UINT, ruby_swap32)
2794IO_BUFFER_DECLARE_TYPE(U32, uint32_t, RB_IO_BUFFER_BIG_ENDIAN, RB_UINT2NUM, RB_NUM2UINT, ruby_swap32)
2795IO_BUFFER_DECLARE_TYPE(s32, int32_t, RB_IO_BUFFER_LITTLE_ENDIAN, RB_INT2NUM, RB_NUM2INT, ruby_swap32)
2796IO_BUFFER_DECLARE_TYPE(S32, int32_t, RB_IO_BUFFER_BIG_ENDIAN, RB_INT2NUM, RB_NUM2INT, ruby_swap32)
2797
2798IO_BUFFER_DECLARE_TYPE(u64, uint64_t, RB_IO_BUFFER_LITTLE_ENDIAN, RB_ULL2NUM, RB_NUM2ULL, ruby_swap64)
2799IO_BUFFER_DECLARE_TYPE(U64, uint64_t, RB_IO_BUFFER_BIG_ENDIAN, RB_ULL2NUM, RB_NUM2ULL, ruby_swap64)
2800IO_BUFFER_DECLARE_TYPE(s64, int64_t, RB_IO_BUFFER_LITTLE_ENDIAN, RB_LL2NUM, RB_NUM2LL, ruby_swap64)
2801IO_BUFFER_DECLARE_TYPE(S64, int64_t, RB_IO_BUFFER_BIG_ENDIAN, RB_LL2NUM, RB_NUM2LL, ruby_swap64)
2802
2803IO_BUFFER_DECLARE_TYPE(u128, rb_uint128_t, RB_IO_BUFFER_LITTLE_ENDIAN, rb_uint128_to_numeric, rb_numeric_to_uint128, ruby_swap128_uint)
2804IO_BUFFER_DECLARE_TYPE(U128, rb_uint128_t, RB_IO_BUFFER_BIG_ENDIAN, rb_uint128_to_numeric, rb_numeric_to_uint128, ruby_swap128_uint)
2805IO_BUFFER_DECLARE_TYPE(s128, rb_int128_t, RB_IO_BUFFER_LITTLE_ENDIAN, rb_int128_to_numeric, rb_numeric_to_int128, ruby_swap128_int)
2806IO_BUFFER_DECLARE_TYPE(S128, rb_int128_t, RB_IO_BUFFER_BIG_ENDIAN, rb_int128_to_numeric, rb_numeric_to_int128, ruby_swap128_int)
2807
2808IO_BUFFER_DECLARE_TYPE(f32, float, RB_IO_BUFFER_LITTLE_ENDIAN, DBL2NUM, NUM2DBL, ruby_swapf32)
2809IO_BUFFER_DECLARE_TYPE(F32, float, RB_IO_BUFFER_BIG_ENDIAN, DBL2NUM, NUM2DBL, ruby_swapf32)
2810IO_BUFFER_DECLARE_TYPE(f64, double, RB_IO_BUFFER_LITTLE_ENDIAN, DBL2NUM, NUM2DBL, ruby_swapf64)
2811IO_BUFFER_DECLARE_TYPE(F64, double, RB_IO_BUFFER_BIG_ENDIAN, DBL2NUM, NUM2DBL, ruby_swapf64)
2812#undef IO_BUFFER_DECLARE_TYPE
2813
2814static inline size_t
2815io_buffer_buffer_type_size(ID buffer_type)
2816{
2817#define IO_BUFFER_DATA_TYPE_SIZE(name) if (buffer_type == RB_IO_BUFFER_DATA_TYPE_##name) return RB_IO_BUFFER_DATA_TYPE_##name##_SIZE;
2818 IO_BUFFER_DATA_TYPE_SIZE(U8)
2819 IO_BUFFER_DATA_TYPE_SIZE(S8)
2820 IO_BUFFER_DATA_TYPE_SIZE(u16)
2821 IO_BUFFER_DATA_TYPE_SIZE(U16)
2822 IO_BUFFER_DATA_TYPE_SIZE(s16)
2823 IO_BUFFER_DATA_TYPE_SIZE(S16)
2824 IO_BUFFER_DATA_TYPE_SIZE(u32)
2825 IO_BUFFER_DATA_TYPE_SIZE(U32)
2826 IO_BUFFER_DATA_TYPE_SIZE(s32)
2827 IO_BUFFER_DATA_TYPE_SIZE(S32)
2828 IO_BUFFER_DATA_TYPE_SIZE(u64)
2829 IO_BUFFER_DATA_TYPE_SIZE(U64)
2830 IO_BUFFER_DATA_TYPE_SIZE(s64)
2831 IO_BUFFER_DATA_TYPE_SIZE(S64)
2832 IO_BUFFER_DATA_TYPE_SIZE(u128)
2833 IO_BUFFER_DATA_TYPE_SIZE(U128)
2834 IO_BUFFER_DATA_TYPE_SIZE(s128)
2835 IO_BUFFER_DATA_TYPE_SIZE(S128)
2836 IO_BUFFER_DATA_TYPE_SIZE(f32)
2837 IO_BUFFER_DATA_TYPE_SIZE(F32)
2838 IO_BUFFER_DATA_TYPE_SIZE(f64)
2839 IO_BUFFER_DATA_TYPE_SIZE(F64)
2840#undef IO_BUFFER_DATA_TYPE_SIZE
2841
2842 rb_raise(rb_eArgError, "Invalid type name!");
2843}
2844
2845static inline ID
2846io_buffer_type_id(VALUE name)
2847{
2848 Check_Type(name, T_SYMBOL);
2849 if (!STATIC_SYM_P(name)) return 0;
2850 return rb_sym2id(name);
2851}
2852#define TYPE_ID(name) io_buffer_type_id(name)
2853
2854/*
2855 * call-seq:
2856 * size_of(buffer_type) -> byte size
2857 * size_of(array of buffer_type) -> byte size
2858 *
2859 * Returns the size of the given buffer type(s) in bytes.
2860 *
2861 * IO::Buffer.size_of(:u32) # => 4
2862 * IO::Buffer.size_of([:u32, :u32]) # => 8
2863 */
2864static VALUE
2865io_buffer_size_of(VALUE klass, VALUE buffer_type)
2866{
2867 if (RB_TYPE_P(buffer_type, T_ARRAY)) {
2868 size_t total = 0;
2869 for (rb_len_t i = 0; i < RARRAY_LEN(buffer_type); i++) {
2870 total += io_buffer_buffer_type_size(TYPE_ID(RARRAY_AREF(buffer_type, i)));
2871 }
2872 return SIZET2NUM(total);
2873 }
2874 else {
2875 return SIZET2NUM(io_buffer_buffer_type_size(TYPE_ID(buffer_type)));
2876 }
2877}
2878
2879#if USE_ZJIT
2880// ZJIT needs this function to never allocate and never raise, so a range it
2881// cannot serve is reported as NULL.
2882const void *
2883rb_jit_io_buffer_readable_ptr(VALUE self, size_t offset, size_t length)
2884{
2885 void *base;
2886 size_t size;
2887
2888 if (!io_buffer_try_get_bytes(get_io_buffer_view(self), &base, &size)) return NULL;
2889 if (!base) return NULL;
2890 if (size_sum_is_bigger_than(offset, length, size)) return NULL;
2891
2892 return (const char *)base + offset;
2893}
2894#endif
2895
2896static inline VALUE
2897rb_io_buffer_get_value(const void* base, size_t size, ID buffer_type, size_t *offset)
2898{
2899#define IO_BUFFER_GET_VALUE(name) if (buffer_type == RB_IO_BUFFER_DATA_TYPE_##name) return io_buffer_read_##name(base, size, offset);
2900 IO_BUFFER_GET_VALUE(U8)
2901 IO_BUFFER_GET_VALUE(S8)
2902
2903 IO_BUFFER_GET_VALUE(u16)
2904 IO_BUFFER_GET_VALUE(U16)
2905 IO_BUFFER_GET_VALUE(s16)
2906 IO_BUFFER_GET_VALUE(S16)
2907
2908 IO_BUFFER_GET_VALUE(u32)
2909 IO_BUFFER_GET_VALUE(U32)
2910 IO_BUFFER_GET_VALUE(s32)
2911 IO_BUFFER_GET_VALUE(S32)
2912
2913 IO_BUFFER_GET_VALUE(u64)
2914 IO_BUFFER_GET_VALUE(U64)
2915 IO_BUFFER_GET_VALUE(s64)
2916 IO_BUFFER_GET_VALUE(S64)
2917
2918 IO_BUFFER_GET_VALUE(u128)
2919 IO_BUFFER_GET_VALUE(U128)
2920 IO_BUFFER_GET_VALUE(s128)
2921 IO_BUFFER_GET_VALUE(S128)
2922
2923 IO_BUFFER_GET_VALUE(f32)
2924 IO_BUFFER_GET_VALUE(F32)
2925 IO_BUFFER_GET_VALUE(f64)
2926 IO_BUFFER_GET_VALUE(F64)
2927#undef IO_BUFFER_GET_VALUE
2928
2929 rb_raise(rb_eArgError, "Invalid type name!");
2930}
2931
2932/*
2933 * call-seq: get_value(buffer_type, offset) -> numeric
2934 *
2935 * Read from buffer a value of +type+ at +offset+. +buffer_type+ should be one
2936 * of symbols:
2937 *
2938 * * +:U8+: unsigned integer, 1 byte
2939 * * +:S8+: signed integer, 1 byte
2940 * * +:u16+: unsigned integer, 2 bytes, little-endian
2941 * * +:U16+: unsigned integer, 2 bytes, big-endian
2942 * * +:s16+: signed integer, 2 bytes, little-endian
2943 * * +:S16+: signed integer, 2 bytes, big-endian
2944 * * +:u32+: unsigned integer, 4 bytes, little-endian
2945 * * +:U32+: unsigned integer, 4 bytes, big-endian
2946 * * +:s32+: signed integer, 4 bytes, little-endian
2947 * * +:S32+: signed integer, 4 bytes, big-endian
2948 * * +:u64+: unsigned integer, 8 bytes, little-endian
2949 * * +:U64+: unsigned integer, 8 bytes, big-endian
2950 * * +:s64+: signed integer, 8 bytes, little-endian
2951 * * +:S64+: signed integer, 8 bytes, big-endian
2952 * * +:u128+: unsigned integer, 16 bytes, little-endian
2953 * * +:U128+: unsigned integer, 16 bytes, big-endian
2954 * * +:s128+: signed integer, 16 bytes, little-endian
2955 * * +:S128+: signed integer, 16 bytes, big-endian
2956 * * +:f32+: float, 4 bytes, little-endian
2957 * * +:F32+: float, 4 bytes, big-endian
2958 * * +:f64+: double, 8 bytes, little-endian
2959 * * +:F64+: double, 8 bytes, big-endian
2960 *
2961 * A buffer type refers specifically to the type of binary buffer that is stored
2962 * in the buffer. For example, a +:u32+ buffer type is a 32-bit unsigned
2963 * integer in little-endian format.
2964 *
2965 * string = [1.5].pack('f')
2966 * # => "\x00\x00\xC0?"
2967 * IO::Buffer.for(string).get_value(:f32, 0)
2968 * # => 1.5
2969 */
2970static VALUE
2971io_buffer_get_value(VALUE self, VALUE type, VALUE _offset)
2972{
2973 const void *base;
2974 size_t size;
2975 size_t offset = io_buffer_extract_offset(_offset);
2976
2977 rb_io_buffer_get_bytes_for_reading(self, &base, &size);
2978
2979 return rb_io_buffer_get_value(base, size, TYPE_ID(type), &offset);
2980}
2981
2982/*
2983 * call-seq: get_values(buffer_types, offset) -> array
2984 *
2985 * Similar to #get_value, except that it can handle multiple buffer types and
2986 * returns an array of values.
2987 *
2988 * string = [1.5, 2.5].pack('ff')
2989 * IO::Buffer.for(string).get_values([:f32, :f32], 0)
2990 * # => [1.5, 2.5]
2991 */
2992static VALUE
2993io_buffer_get_values(VALUE self, VALUE buffer_types, VALUE _offset)
2994{
2995 size_t offset = io_buffer_extract_offset(_offset);
2996
2997 const void *base;
2998 size_t size;
2999 rb_io_buffer_get_bytes_for_reading(self, &base, &size);
3000
3001 if (!RB_TYPE_P(buffer_types, T_ARRAY)) {
3002 rb_raise(rb_eArgError, "Argument buffer_types should be an array!");
3003 }
3004
3005 VALUE array = rb_ary_new_capa(RARRAY_LEN(buffer_types));
3006
3007 for (rb_len_t i = 0; i < RARRAY_LEN(buffer_types); i++) {
3008 VALUE type = rb_ary_entry(buffer_types, i);
3009 VALUE value = rb_io_buffer_get_value(base, size, TYPE_ID(type), &offset);
3010 rb_ary_push(array, value);
3011 }
3012
3013 return array;
3014}
3015
3016// Extract a count argument, which must be a positive integer.
3017// Count is generally considered relative to the number of things.
3018static inline size_t
3019io_buffer_extract_count(VALUE argument)
3020{
3021 if (rb_int_negative_p(argument)) {
3022 rb_raise(rb_eArgError, "Count can't be negative!");
3023 }
3024
3025 return NUM2SIZET(argument);
3026}
3027
3028static inline void
3029io_buffer_extract_offset_count(ID buffer_type, size_t size, int argc, VALUE *argv, size_t *offset, size_t *count)
3030{
3031 if (argc >= 1) {
3032 *offset = io_buffer_extract_offset(argv[0]);
3033 }
3034 else {
3035 *offset = 0;
3036 }
3037
3038 if (argc >= 2) {
3039 *count = io_buffer_extract_count(argv[1]);
3040 }
3041 else {
3042 if (*offset > size) {
3043 rb_raise(rb_eArgError, "The given offset is bigger than the buffer size!");
3044 }
3045
3046 *count = (size - *offset) / io_buffer_buffer_type_size(buffer_type);
3047 }
3048}
3049
3051 VALUE self;
3052 int argc;
3053 VALUE *argv;
3054};
3055
3056static VALUE
3057io_buffer_each_locked(VALUE _arguments)
3058{
3059 struct io_buffer_each_arguments *arguments = (void *)_arguments;
3060 VALUE self = arguments->self;
3061 int argc = arguments->argc;
3062 VALUE *argv = arguments->argv;
3063
3064 const void *base;
3065 size_t size;
3066
3067 rb_io_buffer_get_bytes_for_reading(self, &base, &size);
3068
3069 ID buffer_type;
3070 if (argc >= 1) {
3071 buffer_type = TYPE_ID(argv[0]);
3072 }
3073 else {
3074 buffer_type = RB_IO_BUFFER_DATA_TYPE_U8;
3075 }
3076
3077 size_t offset, count;
3078 io_buffer_extract_offset_count(buffer_type, size, argc-1, argv+1, &offset, &count);
3079
3080 for (size_t i = 0; i < count; i++) {
3081 size_t current_offset = offset;
3082 VALUE value = rb_io_buffer_get_value(base, size, buffer_type, &offset);
3083 rb_yield_values(2, SIZET2NUM(current_offset), value);
3084 }
3085
3086 return self;
3087}
3088
3089/*
3090 * call-seq:
3091 * each(buffer_type, [offset, [count]]) {|offset, value| ...} -> self
3092 * each(buffer_type, [offset, [count]]) -> enumerator
3093 *
3094 * Iterates over the buffer, yielding each +value+ of +buffer_type+ starting
3095 * from +offset+.
3096 *
3097 * If +count+ is given, only +count+ values will be yielded.
3098 *
3099 * IO::Buffer.for("Hello World").each(:U8, 2, 2) do |offset, value|
3100 * puts "#{offset}: #{value}"
3101 * end
3102 * # 2: 108
3103 * # 3: 108
3104 */
3105static VALUE
3106io_buffer_each(int argc, VALUE *argv, VALUE self)
3107{
3108 RETURN_ENUMERATOR_KW(self, argc, argv, RB_NO_KEYWORDS);
3109
3110 struct io_buffer_each_arguments arguments = {
3111 .self = self,
3112 .argc = argc,
3113 .argv = argv,
3114 };
3115
3116 rb_io_buffer_lock(self);
3117 return rb_ensure(io_buffer_each_locked, (VALUE)&arguments, rb_io_buffer_locked_ensure, self);
3118}
3119
3120/*
3121 * call-seq: values(buffer_type, [offset, [count]]) -> array
3122 *
3123 * Returns an array of values of +buffer_type+ starting from +offset+.
3124 *
3125 * If +count+ is given, only +count+ values will be returned.
3126 *
3127 * IO::Buffer.for("Hello World").values(:U8, 2, 2)
3128 * # => [108, 108]
3129 */
3130static VALUE
3131io_buffer_values(int argc, VALUE *argv, VALUE self)
3132{
3133 const void *base;
3134 size_t size;
3135
3136 rb_io_buffer_get_bytes_for_reading(self, &base, &size);
3137
3138 ID buffer_type;
3139 if (argc >= 1) {
3140 buffer_type = TYPE_ID(argv[0]);
3141 }
3142 else {
3143 buffer_type = RB_IO_BUFFER_DATA_TYPE_U8;
3144 }
3145
3146 size_t offset, count;
3147 io_buffer_extract_offset_count(buffer_type, size, argc-1, argv+1, &offset, &count);
3148
3149 VALUE array = rb_ary_new_capa(count);
3150
3151 for (size_t i = 0; i < count; i++) {
3152 VALUE value = rb_io_buffer_get_value(base, size, buffer_type, &offset);
3153 rb_ary_push(array, value);
3154 }
3155
3156 return array;
3157}
3158
3159static VALUE
3160io_buffer_each_byte_locked(VALUE _arguments)
3161{
3162 struct io_buffer_each_arguments *arguments = (void *)_arguments;
3163 VALUE self = arguments->self;
3164 int argc = arguments->argc;
3165 VALUE *argv = arguments->argv;
3166
3167 const void *base;
3168 size_t size;
3169
3170 rb_io_buffer_get_bytes_for_reading(self, &base, &size);
3171
3172 size_t offset, count;
3173 io_buffer_extract_offset_count(RB_IO_BUFFER_DATA_TYPE_U8, size, argc, argv, &offset, &count);
3174
3175 if (size_sum_is_bigger_than(offset, count, size)) {
3176 rb_raise(rb_eArgError, "Specified offset+count is bigger than the buffer size!");
3177 }
3178
3179 for (size_t i = 0; i < count; i++) {
3180 unsigned char *value = (unsigned char *)base + i + offset;
3181 rb_yield(RB_INT2FIX(*value));
3182 }
3183
3184 return self;
3185}
3186
3187/*
3188 * call-seq:
3189 * each_byte([offset, [count]]) {|byte| ...} -> self
3190 * each_byte([offset, [count]]) -> enumerator
3191 *
3192 * Iterates over the buffer, yielding each byte starting from +offset+.
3193 *
3194 * If +count+ is given, only +count+ bytes will be yielded.
3195 *
3196 * IO::Buffer.for("Hello World").each_byte(2, 2) do |offset, byte|
3197 * puts "#{offset}: #{byte}"
3198 * end
3199 * # 2: 108
3200 * # 3: 108
3201 */
3202static VALUE
3203io_buffer_each_byte(int argc, VALUE *argv, VALUE self)
3204{
3205 RETURN_ENUMERATOR_KW(self, argc, argv, RB_NO_KEYWORDS);
3206
3207 struct io_buffer_each_arguments arguments = {
3208 .self = self,
3209 .argc = argc,
3210 .argv = argv,
3211 };
3212
3213 rb_io_buffer_lock(self);
3214 return rb_ensure(io_buffer_each_byte_locked, (VALUE)&arguments, rb_io_buffer_locked_ensure, self);
3215}
3216
3217static inline void
3218rb_io_buffer_set_value(struct rb_io_buffer_view *buffer, VALUE buffer_type, size_t *offset, VALUE value)
3219{
3220 ID type = TYPE_ID(buffer_type);
3221#define IO_BUFFER_SET_VALUE(name) if (type == RB_IO_BUFFER_DATA_TYPE_##name) {io_buffer_write_##name(buffer, offset, value); return;}
3222 IO_BUFFER_SET_VALUE(U8);
3223 IO_BUFFER_SET_VALUE(S8);
3224
3225 IO_BUFFER_SET_VALUE(u16);
3226 IO_BUFFER_SET_VALUE(U16);
3227 IO_BUFFER_SET_VALUE(s16);
3228 IO_BUFFER_SET_VALUE(S16);
3229
3230 IO_BUFFER_SET_VALUE(u32);
3231 IO_BUFFER_SET_VALUE(U32);
3232 IO_BUFFER_SET_VALUE(s32);
3233 IO_BUFFER_SET_VALUE(S32);
3234
3235 IO_BUFFER_SET_VALUE(u64);
3236 IO_BUFFER_SET_VALUE(U64);
3237 IO_BUFFER_SET_VALUE(s64);
3238 IO_BUFFER_SET_VALUE(S64);
3239
3240 IO_BUFFER_SET_VALUE(u128);
3241 IO_BUFFER_SET_VALUE(U128);
3242 IO_BUFFER_SET_VALUE(s128);
3243 IO_BUFFER_SET_VALUE(S128);
3244
3245 IO_BUFFER_SET_VALUE(f32);
3246 IO_BUFFER_SET_VALUE(F32);
3247 IO_BUFFER_SET_VALUE(f64);
3248 IO_BUFFER_SET_VALUE(F64);
3249#undef IO_BUFFER_SET_VALUE
3250
3251 rb_raise(rb_eArgError, "Invalid type name!");
3252}
3253
3255 struct rb_io_buffer_view *buffer;
3256 size_t offset;
3257 VALUE type, value;
3258};
3259
3260/*
3261 * call-seq: set_value(type, offset, value) -> offset
3262 *
3263 * Write to a buffer a +value+ of +type+ at +offset+. +type+ should be one of
3264 * symbols described in #get_value. Returns the offset just after the written
3265 * value.
3266 *
3267 * buffer = IO::Buffer.new(8)
3268 * # =>
3269 * # #<IO::Buffer 0x0000555f5c9a2d50+8 INTERNAL>
3270 * # 0x00000000 00 00 00 00 00 00 00 00
3271 *
3272 * buffer.set_value(:U8, 1, 111)
3273 * # => 2
3274 *
3275 * buffer
3276 * # =>
3277 * # #<IO::Buffer 0x0000555f5c9a2d50+8 INTERNAL>
3278 * # 0x00000000 00 6f 00 00 00 00 00 00 .o......
3279 *
3280 * Note that if the +type+ is integer and +value+ is Float, the implicit truncation is performed:
3281 *
3282 * buffer = IO::Buffer.new(8)
3283 * buffer.set_value(:U32, 0, 2.5)
3284 *
3285 * buffer
3286 * # =>
3287 * # #<IO::Buffer 0x0000555f5c9a2d50+8 INTERNAL>
3288 * # 0x00000000 00 00 00 02 00 00 00 00
3289 * # ^^ the same as if we'd pass just integer 2
3290 */
3291static VALUE
3292io_buffer_set_value(VALUE self, VALUE type, VALUE _offset, VALUE value)
3293{
3294 struct rb_io_buffer_view *buffer = get_io_buffer_view_for_writing(self);
3295 size_t offset = io_buffer_extract_offset(_offset);
3296 rb_io_buffer_set_value(buffer, type, &offset, value);
3297 return SIZET2NUM(offset);
3298}
3299
3300/*
3301 * call-seq: set_values(buffer_types, offset, values) -> offset
3302 *
3303 * Write +values+ of +buffer_types+ at +offset+ to the buffer. +buffer_types+
3304 * should be an array of symbols as described in #get_value. +values+ should
3305 * be an array of values to write. Returns the offset just after the last
3306 * written value.
3307 *
3308 * buffer = IO::Buffer.new(8)
3309 * buffer.set_values([:U8, :U16], 0, [1, 2])
3310 * # => 3
3311 * buffer
3312 * # =>
3313 * # #<IO::Buffer 0x696f717561746978+8 INTERNAL>
3314 * # 0x00000000 01 00 02 00 00 00 00 00 ........
3315 */
3316static VALUE
3317io_buffer_set_values(VALUE self, VALUE buffer_types, VALUE _offset, VALUE values)
3318{
3319 struct rb_io_buffer_view *buffer = get_io_buffer_view_for_writing(self);
3320
3321 if (!RB_TYPE_P(buffer_types, T_ARRAY)) {
3322 rb_raise(rb_eArgError, "Argument buffer_types should be an array!");
3323 }
3324
3325 size_t offset = io_buffer_extract_offset(_offset);
3326
3327 if (!RB_TYPE_P(values, T_ARRAY)) {
3328 rb_raise(rb_eArgError, "Argument values should be an array!");
3329 }
3330
3331 if (RARRAY_LEN(buffer_types) != RARRAY_LEN(values)) {
3332 rb_raise(rb_eArgError, "Argument buffer_types and values should have the same length!");
3333 }
3334
3335 for (rb_len_t i = 0; i < RARRAY_LEN(buffer_types); i++) {
3336 VALUE type = rb_ary_entry(buffer_types, i);
3337 VALUE value = rb_ary_entry(values, i);
3338 rb_io_buffer_set_value(buffer, type, &offset, value);
3339 }
3340
3341 return SIZET2NUM(offset);
3342}
3343
3344static size_t IO_BUFFER_BLOCKING_SIZE = 1024*1024;
3345
3347 unsigned char * destination;
3348 const unsigned char * source;
3349 size_t length;
3350};
3351
3352static void *
3353io_buffer_memmove_blocking(void *data)
3354{
3355 struct io_buffer_memmove_arguments *arguments = (struct io_buffer_memmove_arguments *)data;
3356
3357 memmove(arguments->destination, arguments->source, arguments->length);
3358
3359 return NULL;
3360}
3361
3362static void
3363io_buffer_memmove_unblock(void *data)
3364{
3365 // No safe way to interrupt.
3366}
3367
3368static void
3369io_buffer_memmove(void *base, size_t size, size_t offset, const void *source_base, size_t source_offset, size_t source_size, size_t length)
3370{
3371 if (size_sum_is_bigger_than(offset, length, size)) {
3372 rb_raise(rb_eArgError, "Specified offset+length is bigger than the buffer size!");
3373 }
3374
3375 if (size_sum_is_bigger_than(source_offset, length, source_size)) {
3376 rb_raise(rb_eArgError, "The computed source range exceeds the size of the source buffer!");
3377 }
3378
3379 if (length == 0) return;
3380
3381 RUBY_ASSERT(base != NULL);
3382 RUBY_ASSERT(source_base != NULL);
3383 struct io_buffer_memmove_arguments arguments = {
3384 .destination = (unsigned char*)base+offset,
3385 .source = (unsigned char*)source_base+source_offset,
3386 .length = length
3387 };
3388
3389 if (arguments.length >= IO_BUFFER_BLOCKING_SIZE) {
3390 rb_nogvl(io_buffer_memmove_blocking, &arguments, io_buffer_memmove_unblock, &arguments, RB_NOGVL_OFFLOAD_SAFE);
3391 } else if (arguments.length != 0) {
3392 memmove(arguments.destination, arguments.source, arguments.length);
3393 }
3394}
3395
3396static void
3397io_buffer_extract_copy_arguments(size_t source_size, int argc, VALUE *argv, size_t *offset, size_t *length, size_t *source_offset)
3398{
3399 // The offset we copy into the buffer:
3400 if (argc >= 1) {
3401 *offset = io_buffer_extract_offset(argv[0]);
3402 }
3403 else {
3404 *offset = 0;
3405 }
3406
3407 // The offset we start from within the string:
3408 if (argc >= 3) {
3409 *source_offset = io_buffer_extract_offset(argv[2]);
3410
3411 if (*source_offset > source_size) {
3412 rb_raise(rb_eArgError, "The given source offset is bigger than the source itself!");
3413 }
3414 }
3415 else {
3416 *source_offset = 0;
3417 }
3418
3419 // The length we are going to copy:
3420 if (argc >= 2 && !RB_NIL_P(argv[1])) {
3421 *length = io_buffer_extract_length(argv[1]);
3422 }
3423 else {
3424 // Default to the source offset -> source size:
3425 *length = source_size - *source_offset;
3426 }
3427}
3428
3429// (offset, length, source_offset) -> length
3430static VALUE
3431io_buffer_copy_from(struct rb_io_buffer_view *buffer, const void *source_base, size_t source_size, int argc, VALUE *argv)
3432{
3433 size_t offset, length, source_offset;
3434 io_buffer_extract_copy_arguments(source_size, argc, argv, &offset, &length, &source_offset);
3435
3436 void *base;
3437 size_t size;
3438 io_buffer_get_bytes_for_writing(buffer, &base, &size);
3439
3440 if (length >= IO_BUFFER_BLOCKING_SIZE) {
3441 io_buffer_lock(buffer);
3442 }
3443
3444 io_buffer_memmove(base, size, offset, source_base, source_offset, source_size, length);
3445
3446 if (length >= IO_BUFFER_BLOCKING_SIZE) {
3447 io_buffer_unlock(buffer);
3448 }
3449
3450 return SIZET2NUM(length);
3451}
3452
3454 VALUE destination;
3455 const void *source_base;
3456 size_t source_size;
3457 int argc;
3458 VALUE *argv;
3459};
3460
3461// This is the innermost callback for IO::Buffer#copy. At this point the source
3462// is locked for reading and the destination is locked for writing, so both
3463// pointers and sizes remain valid while arguments are extracted, ranges are
3464// validated, and memmove potentially releases the GVL.
3465static VALUE
3466io_buffer_copy_to(void *base, size_t size, VALUE _arguments)
3467{
3468 struct io_buffer_copy_arguments *arguments = (void *)_arguments;
3469
3470 size_t offset, length, source_offset;
3471 io_buffer_extract_copy_arguments(arguments->source_size, arguments->argc, arguments->argv, &offset, &length, &source_offset);
3472
3473 io_buffer_memmove(base, size, offset, arguments->source_base, source_offset, arguments->source_size, length);
3474
3475 return SIZET2NUM(length);
3476}
3477
3478// This callback runs while the source is locked for reading. Retain its bytes
3479// in the callback arguments, then enter the destination's writable scope. The
3480// source scope remains active until that nested scope returns.
3481static VALUE
3482io_buffer_copy_from_readable(const void *base, size_t size, VALUE _arguments)
3483{
3484 struct io_buffer_copy_arguments *arguments = (void *)_arguments;
3485
3486 arguments->source_base = base;
3487 arguments->source_size = size;
3488
3489 return rb_io_buffer_locked_for_writing(arguments->destination, io_buffer_copy_to, _arguments);
3490}
3491
3492static VALUE
3493io_buffer_initialize_copy_from(const void *base, size_t size, VALUE self)
3494{
3495 struct rb_io_buffer_storage *buffer = get_io_buffer_storage(self);
3496 if (buffer->lock_count) rb_raise(rb_eIOBufferLockedError, "Cannot initialize locked buffer!");
3497 io_buffer_storage_release(buffer);
3498 io_buffer_storage_initialize(self, buffer, NULL, size, io_flags_for_size(size), Qnil);
3499
3500 struct io_buffer_copy_arguments arguments = {
3501 .destination = self,
3502 .source_base = base,
3503 .source_size = size,
3504 .argc = 0,
3505 .argv = NULL,
3506 };
3507
3508 // The source remains locked by the outer readable scope while the newly
3509 // initialized destination is locked and populated by io_buffer_copy_to.
3510 return rb_io_buffer_locked_for_writing(self, io_buffer_copy_to, (VALUE)&arguments);
3511}
3512
3513/*
3514 * call-seq:
3515 * dup -> io_buffer
3516 * clone -> io_buffer
3517 *
3518 * Make an internal copy of the source buffer. Updates to the copy will not
3519 * affect the source buffer.
3520 *
3521 * source = IO::Buffer.for("Hello World")
3522 * # =>
3523 * # #<IO::Buffer 0x00007fd598466830+11 EXTERNAL READONLY SLICE>
3524 * # 0x00000000 48 65 6c 6c 6f 20 57 6f 72 6c 64 Hello World
3525 * buffer = source.dup
3526 * # =>
3527 * # #<IO::Buffer 0x0000558cbec03320+11 INTERNAL>
3528 * # 0x00000000 48 65 6c 6c 6f 20 57 6f 72 6c 64 Hello World
3529 */
3530static VALUE
3531rb_io_buffer_initialize_copy(VALUE self, VALUE source)
3532{
3533 if (self == source) return self;
3534 rb_check_frozen(self);
3535 return rb_io_buffer_locked_for_reading(source, io_buffer_initialize_copy_from, self);
3536}
3537
3538/*
3539 * call-seq:
3540 * copy(source, [offset, [length, [source_offset]]]) -> size
3541 *
3542 * Efficiently copy from a source IO::Buffer into the buffer, at +offset+
3543 * using +memmove+. For copying String instances, see #set_string.
3544 *
3545 * buffer = IO::Buffer.new(32)
3546 * # =>
3547 * # #<IO::Buffer 0x0000555f5ca22520+32 INTERNAL>
3548 * # 0x00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
3549 * # 0x00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ *
3550 *
3551 * buffer.copy(IO::Buffer.for("test"), 8)
3552 * # => 4 -- size of buffer copied
3553 * buffer
3554 * # =>
3555 * # #<IO::Buffer 0x0000555f5cf8fe40+32 INTERNAL>
3556 * # 0x00000000 00 00 00 00 00 00 00 00 74 65 73 74 00 00 00 00 ........test....
3557 * # 0x00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ *
3558 *
3559 * #copy can be used to put buffer into strings associated with buffer:
3560 *
3561 * string = "data: "
3562 * # => "data: "
3563 * buffer = IO::Buffer.for(string) do |buffer|
3564 * buffer.copy(IO::Buffer.for("test"), 5)
3565 * end
3566 * # => 4
3567 * string
3568 * # => "data:test"
3569 *
3570 * Attempt to copy into a read-only buffer will fail:
3571 *
3572 * File.write('test.txt', 'test')
3573 * buffer = IO::Buffer.map(File.open('test.txt'), nil, 0, IO::Buffer::READONLY)
3574 * buffer.copy(IO::Buffer.for("test"), 8)
3575 * # in `copy': Buffer is not writable! (IO::Buffer::AccessError)
3576 *
3577 * See ::map for details of creation of mutable file mappings, this will
3578 * work:
3579 *
3580 * buffer = IO::Buffer.map(File.open('test.txt', 'r+'))
3581 * buffer.copy(IO::Buffer.for("boom"), 0)
3582 * # => 4
3583 * File.read('test.txt')
3584 * # => "boom"
3585 *
3586 * Attempt to copy the buffer which will need place outside of buffer's
3587 * bounds will fail:
3588 *
3589 * buffer = IO::Buffer.new(2)
3590 * buffer.copy(IO::Buffer.for('test'), 0)
3591 * # in `copy': Specified offset+length is bigger than the buffer size! (ArgumentError)
3592 *
3593 * It is safe to copy between memory regions that overlaps each other.
3594 * In such case, the data is copied as if the data was first copied from the source buffer to
3595 * a temporary buffer, and then copied from the temporary buffer to the destination buffer.
3596 *
3597 * buffer = IO::Buffer.new(10)
3598 * buffer.set_string("0123456789")
3599 * buffer.copy(buffer, 3, 7)
3600 * # => 7
3601 * buffer
3602 * # =>
3603 * # #<IO::Buffer 0x000056494f8ce440+10 INTERNAL>
3604 * # 0x00000000 30 31 32 30 31 32 33 34 35 36 0120123456
3605 */
3606static VALUE
3607io_buffer_copy(int argc, VALUE *argv, VALUE self)
3608{
3609 rb_check_arity(argc, 1, 4);
3610
3611 VALUE source = argv[0];
3612 struct io_buffer_copy_arguments arguments = {
3613 .destination = self,
3614 .argc = argc-1,
3615 .argv = argv+1,
3616 };
3617
3618 // Lock the source first, then io_buffer_copy_from_readable nests the
3619 // destination lock. The scoped helpers use rb_ensure, so the destination
3620 // is unlocked before the source on both normal and exceptional returns.
3621 // If both buffers share an allocation, its reference-counted lock is
3622 // acquired and released twice.
3623 return rb_io_buffer_locked_for_reading(source, io_buffer_copy_from_readable, (VALUE)&arguments);
3624}
3625
3627 size_t offset;
3628 size_t length;
3629 rb_encoding *encoding;
3630};
3631
3632static VALUE
3633io_buffer_get_string_locked(const void *base, size_t size, VALUE _arguments)
3634{
3635 struct io_buffer_get_string_arguments *arguments = (void *)_arguments;
3636 if (size_sum_is_bigger_than(arguments->offset, arguments->length, size)) {
3637 rb_raise(rb_eArgError, "Specified offset+length is bigger than the buffer size!");
3638 }
3639 const char *data = base ? (const char *)base + arguments->offset : NULL;
3640 return rb_enc_str_new(data, arguments->length, arguments->encoding);
3641}
3642
3643/*
3644 * call-seq: get_string([offset, [length, [encoding]]]) -> string
3645 *
3646 * Read a chunk or all of the buffer into a string, in the specified
3647 * +encoding+. If no encoding is provided +Encoding::BINARY+ is used.
3648 *
3649 * buffer = IO::Buffer.for('test')
3650 * buffer.get_string
3651 * # => "test"
3652 * buffer.get_string(2)
3653 * # => "st"
3654 * buffer.get_string(2, 1)
3655 * # => "s"
3656 */
3657static VALUE
3658io_buffer_get_string(int argc, VALUE *argv, VALUE self)
3659{
3660 rb_check_arity(argc, 0, 3);
3661
3662 struct io_buffer_get_string_arguments arguments;
3663 io_buffer_extract_offset_length(self, argc, argv, &arguments.offset, &arguments.length);
3664
3665 // Encoding coercion may invoke Ruby and change the source. Do it before
3666 // locking and resolving the current view; retain no pointer across it.
3667 arguments.encoding = argc >= 3 ? rb_find_encoding(argv[2]) : rb_ascii8bit_encoding();
3668 return rb_io_buffer_locked_for_reading(self, io_buffer_get_string_locked, (VALUE)&arguments);
3669}
3670
3671/*
3672 * call-seq: set_string(string, [offset, [length, [source_offset]]]) -> size
3673 *
3674 * Efficiently copy from a source String into the buffer, at +offset+ using
3675 * +memmove+.
3676 *
3677 * buf = IO::Buffer.new(8)
3678 * # =>
3679 * # #<IO::Buffer 0x0000557412714a20+8 INTERNAL>
3680 * # 0x00000000 00 00 00 00 00 00 00 00 ........
3681 *
3682 * # set buffer starting from offset 1, take 2 bytes starting from string's
3683 * # second
3684 * buf.set_string('test', 1, 2, 1)
3685 * # => 2
3686 * buf
3687 * # =>
3688 * # #<IO::Buffer 0x0000557412714a20+8 INTERNAL>
3689 * # 0x00000000 00 65 73 00 00 00 00 00 .es.....
3690 *
3691 * See also #copy for examples of how buffer writing might be used for changing
3692 * associated strings and files.
3693 */
3694static VALUE
3695io_buffer_set_string(int argc, VALUE *argv, VALUE self)
3696{
3697 rb_check_arity(argc, 1, 4);
3698
3699 struct rb_io_buffer_view *buffer = get_io_buffer_view_for_writing(self);
3700
3701 VALUE string = rb_str_to_str(argv[0]);
3702
3703 const void *source_base = RSTRING_PTR(string);
3704 size_t source_size = RSTRING_LEN(string);
3705
3706 VALUE result = io_buffer_copy_from(buffer, source_base, source_size, argc-1, argv+1);
3707 RB_GC_GUARD(string);
3708 return result;
3709}
3710
3711void
3712rb_io_buffer_clear(VALUE self, uint8_t value, size_t offset, size_t length)
3713{
3714 struct rb_io_buffer_view *buffer = get_io_buffer_view_for_writing(self);
3715
3716 void *base;
3717 size_t size;
3718 io_buffer_get_bytes_for_writing(buffer, &base, &size);
3719
3720 io_buffer_validate_range(buffer, offset, length);
3721
3722 if (length == 0) return;
3723
3724 RUBY_ASSERT(base != NULL);
3725 memset((char*)base + offset, value, length);
3726}
3727
3728/*
3729 * call-seq: clear(value = 0, [offset, [length]]) -> self
3730 *
3731 * Fill buffer with +value+, starting with +offset+ and going for +length+
3732 * bytes.
3733 *
3734 * buffer = IO::Buffer.for('test').dup
3735 * # =>
3736 * # <IO::Buffer 0x00007fca40087c38+4 INTERNAL>
3737 * # 0x00000000 74 65 73 74 test
3738 *
3739 * buffer.clear
3740 * # =>
3741 * # <IO::Buffer 0x00007fca40087c38+4 INTERNAL>
3742 * # 0x00000000 00 00 00 00 ....
3743 *
3744 * buf.clear(1) # fill with 1
3745 * # =>
3746 * # <IO::Buffer 0x00007fca40087c38+4 INTERNAL>
3747 * # 0x00000000 01 01 01 01 ....
3748 *
3749 * buffer.clear(2, 1, 2) # fill with 2, starting from offset 1, for 2 bytes
3750 * # =>
3751 * # <IO::Buffer 0x00007fca40087c38+4 INTERNAL>
3752 * # 0x00000000 01 02 02 01 ....
3753 *
3754 * buffer.clear(2, 1) # fill with 2, starting from offset 1
3755 * # =>
3756 * # <IO::Buffer 0x00007fca40087c38+4 INTERNAL>
3757 * # 0x00000000 01 02 02 02 ....
3758 */
3759static VALUE
3760io_buffer_clear(int argc, VALUE *argv, VALUE self)
3761{
3762 rb_check_arity(argc, 0, 3);
3763
3764 uint8_t value = 0;
3765 if (argc >= 1) {
3766 value = NUM2UINT(argv[0]);
3767 }
3768
3769 size_t offset, length;
3770 io_buffer_extract_offset_length(self, argc-1, argv+1, &offset, &length);
3771
3772 rb_io_buffer_clear(self, value, offset, length);
3773
3774 return self;
3775}
3776
3777static size_t
3778io_buffer_default_size(size_t page_size)
3779{
3780 // Platform agnostic default size, based on empirical performance observation:
3781 const size_t platform_agnostic_default_size = 64*1024;
3782
3783 // Allow user to specify custom default buffer size:
3784 const char *default_size = getenv("RUBY_IO_BUFFER_DEFAULT_SIZE");
3785 if (default_size) {
3786 // For the purpose of setting a default size, 2^31 is an acceptable maximum:
3787 int value = atoi(default_size);
3788
3789 // assuming sizeof(int) <= sizeof(size_t)
3790 if (value > 0) {
3791 return value;
3792 }
3793 }
3794
3795 if (platform_agnostic_default_size < page_size) {
3796 return page_size;
3797 }
3798
3799 return platform_agnostic_default_size;
3800}
3801
3803 struct rb_io *io;
3804 struct rb_io_buffer_view *buffer;
3805 rb_blocking_function_t *function;
3806 void *data;
3807};
3808
3809static VALUE
3810io_buffer_blocking_region_begin(VALUE _argument)
3811{
3812 struct io_buffer_blocking_region_argument *argument = (void*)_argument;
3813
3814 return rb_io_blocking_region(argument->io, argument->function, argument->data);
3815}
3816
3817static VALUE
3818io_buffer_blocking_region_ensure(VALUE _argument)
3819{
3820 struct io_buffer_blocking_region_argument *argument = (void*)_argument;
3821
3822 io_buffer_unlock(argument->buffer);
3823
3824 return Qnil;
3825}
3826
3827static VALUE
3828io_buffer_blocking_region(VALUE io, struct rb_io_buffer_view *buffer, rb_blocking_function_t *function, void *data)
3829{
3830 struct rb_io *ioptr;
3831 RB_IO_POINTER(io, ioptr);
3832
3833 struct io_buffer_blocking_region_argument argument = {
3834 .io = ioptr,
3835 .buffer = buffer,
3836 .function = function,
3837 .data = data,
3838 };
3839
3840 // The buffer should be locked for the duration of the blocking region. We
3841 // always acquire our own reference so another operation cannot release the
3842 // allocation while this operation is still using it:
3843 io_buffer_lock(buffer);
3844
3845 return rb_ensure(io_buffer_blocking_region_begin, (VALUE)&argument, io_buffer_blocking_region_ensure, (VALUE)&argument);
3846}
3847
3849 // The file descriptor to read from:
3850 int descriptor;
3851 // The base pointer to read into:
3852 char *base;
3853 // The maximum number of bytes to read:
3854 size_t length;
3855};
3856
3857static VALUE
3858io_buffer_read_internal(void *_argument)
3859{
3860 struct io_buffer_read_internal_argument *argument = _argument;
3861 ssize_t result = read(argument->descriptor, argument->base, argument->length);
3862
3863 return rb_fiber_scheduler_io_result(result, errno);
3864}
3865
3866VALUE
3867rb_io_buffer_read(VALUE self, VALUE io, size_t offset, size_t length)
3868{
3869 io = rb_io_get_io(io);
3870 struct rb_io_buffer_view *buffer = get_io_buffer_view_for_writing(self);
3871
3872 io_buffer_validate_range(buffer, offset, length);
3873
3874 if (length == 0) return SIZET2NUM(0);
3875
3876 VALUE scheduler = rb_fiber_scheduler_current();
3877 if (scheduler != Qnil) {
3878 VALUE result = rb_fiber_scheduler_io_read(scheduler, io, self, offset, length);
3879
3880 if (!UNDEF_P(result)) {
3881 return result;
3882 }
3883
3884 // The scheduler capability check can invoke Ruby and change the view.
3885 buffer = get_io_buffer_view_for_writing(self);
3886 io_buffer_validate_range(buffer, offset, length);
3887 }
3888
3889 void *base;
3890 size_t size;
3891 io_buffer_get_bytes_for_writing(buffer, &base, &size);
3892
3893 RUBY_ASSERT(base != NULL);
3894
3895 struct io_buffer_read_internal_argument argument = {
3896 .descriptor = rb_io_descriptor(io),
3897 .base = (char*)base + offset,
3898 .length = length,
3899 };
3900
3901 return io_buffer_blocking_region(io, buffer, io_buffer_read_internal, &argument);
3902}
3903
3904/*
3905 * call-seq: read(io, [offset, [length]]) -> read length or -errno
3906 *
3907 * Perform one read operation of at most +length+ bytes from +io+ into the
3908 * buffer starting at +offset+. A short read is a normal result. If an error
3909 * occurs, return <tt>-errno</tt>.
3910 *
3911 * If +offset+ is not given, it defaults to zero, i.e. the beginning of the
3912 * buffer. If +length+ is not given, it defaults to the size of the buffer
3913 * minus the offset. A zero length is a no-op.
3914 *
3915 * IO::Buffer.for('test') do |buffer|
3916 * p buffer
3917 * # =>
3918 * # <IO::Buffer 0x00007fca40087c38+4 SLICE>
3919 * # 0x00000000 74 65 73 74 test
3920 * buffer.read(File.open('/dev/urandom', 'rb'), 0, 2)
3921 * p buffer
3922 * # =>
3923 * # <IO::Buffer 0x00007f3bc65f2a58+4 EXTERNAL SLICE>
3924 * # 0x00000000 05 35 73 74 .5st
3925 * end
3926 */
3927static VALUE
3928io_buffer_read(int argc, VALUE *argv, VALUE self)
3929{
3930 rb_check_arity(argc, 1, 3);
3931
3932 VALUE io = argv[0];
3933
3934 size_t offset, length;
3935 io_buffer_extract_offset_length(self, argc-1, argv+1, &offset, &length);
3936
3937 return rb_io_buffer_read(self, io, offset, length);
3938}
3939
3941 // The file descriptor to read from:
3942 int descriptor;
3943 // The base pointer to read into:
3944 char *base;
3945 // The maximum number of bytes to read:
3946 size_t length;
3947 // The position to read from:
3948 rb_off_t from;
3949};
3950
3951static VALUE
3952io_buffer_pread_internal(void *_argument)
3953{
3954 struct io_buffer_pread_internal_argument *argument = _argument;
3955 ssize_t result = pread(argument->descriptor, argument->base, argument->length, argument->from);
3956
3957 return rb_fiber_scheduler_io_result(result, errno);
3958}
3959
3960VALUE
3961rb_io_buffer_pread(VALUE self, VALUE io, rb_off_t from, size_t offset, size_t length)
3962{
3963 io = rb_io_get_io(io);
3964 struct rb_io_buffer_view *buffer = get_io_buffer_view_for_writing(self);
3965
3966 io_buffer_validate_range(buffer, offset, length);
3967
3968 if (length == 0) return SIZET2NUM(0);
3969
3970 VALUE scheduler = rb_fiber_scheduler_current();
3971 if (scheduler != Qnil) {
3972 VALUE result = rb_fiber_scheduler_io_pread(scheduler, io, from, self, offset, length);
3973
3974 if (!UNDEF_P(result)) {
3975 return result;
3976 }
3977
3978 buffer = get_io_buffer_view_for_writing(self);
3979 io_buffer_validate_range(buffer, offset, length);
3980 }
3981
3982 void *base;
3983 size_t size;
3984 io_buffer_get_bytes_for_writing(buffer, &base, &size);
3985
3986 RUBY_ASSERT(base != NULL);
3987
3988 struct io_buffer_pread_internal_argument argument = {
3989 .descriptor = rb_io_descriptor(io),
3990 .base = (char*)base + offset,
3991 .length = length,
3992 .from = from,
3993 };
3994
3995 return io_buffer_blocking_region(io, buffer, io_buffer_pread_internal, &argument);
3996}
3997
3998/*
3999 * call-seq: pread(io, from, [offset, [length]]) -> read length or -errno
4000 *
4001 * Perform one read operation of at most +length+ bytes from +io+ at +from+
4002 * into the buffer starting at +offset+. A short read is a normal result and
4003 * the IO's current position is not modified. If an error occurs, return
4004 * <tt>-errno</tt>.
4005 *
4006 * If +offset+ is not given, it defaults to zero, i.e. the beginning of the
4007 * buffer. If +length+ is not given, it defaults to the size of the buffer
4008 * minus the offset. A zero length is a no-op.
4009 *
4010 * IO::Buffer.for('test') do |buffer|
4011 * p buffer
4012 * # =>
4013 * # <IO::Buffer 0x00007fca40087c38+4 SLICE>
4014 * # 0x00000000 74 65 73 74 test
4015 *
4016 * # take 2 bytes from the beginning of urandom,
4017 * # put them in buffer starting from position 2
4018 * buffer.pread(File.open('/dev/urandom', 'rb'), 0, 2, 2)
4019 * p buffer
4020 * # =>
4021 * # <IO::Buffer 0x00007f3bc65f2a58+4 EXTERNAL SLICE>
4022 * # 0x00000000 05 35 73 74 te.5
4023 * end
4024 */
4025static VALUE
4026io_buffer_pread(int argc, VALUE *argv, VALUE self)
4027{
4028 rb_check_arity(argc, 2, 4);
4029
4030 VALUE io = argv[0];
4031 rb_off_t from = NUM2OFFT(argv[1]);
4032
4033 size_t offset, length;
4034 io_buffer_extract_offset_length(self, argc-2, argv+2, &offset, &length);
4035
4036 return rb_io_buffer_pread(self, io, from, offset, length);
4037}
4038
4040 // The file descriptor to write to:
4041 int descriptor;
4042 // The base pointer to write from:
4043 const char *base;
4044 // The maximum number of bytes to write:
4045 size_t length;
4046};
4047
4048static VALUE
4049io_buffer_write_internal(void *_argument)
4050{
4051 struct io_buffer_write_internal_argument *argument = _argument;
4052 ssize_t result = write(argument->descriptor, argument->base, argument->length);
4053
4054 return rb_fiber_scheduler_io_result(result, errno);
4055}
4056
4057VALUE
4058rb_io_buffer_write(VALUE self, VALUE io, size_t offset, size_t length)
4059{
4061
4062 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
4063 io_buffer_validate_range(buffer, offset, length);
4064
4065 if (length == 0) return SIZET2NUM(0);
4066
4067 VALUE scheduler = rb_fiber_scheduler_current();
4068 if (scheduler != Qnil) {
4069 VALUE result = rb_fiber_scheduler_io_write(scheduler, io, self, offset, length);
4070
4071 if (!UNDEF_P(result)) {
4072 return result;
4073 }
4074
4075 buffer = get_io_buffer_view(self);
4076 io_buffer_validate_range(buffer, offset, length);
4077 }
4078
4079 const void *base;
4080 size_t size;
4081 io_buffer_get_bytes_for_reading(buffer, &base, &size);
4082
4083 RUBY_ASSERT(base != NULL);
4084
4085 struct io_buffer_write_internal_argument argument = {
4086 .descriptor = rb_io_descriptor(io),
4087 .base = (const char*)base + offset,
4088 .length = length,
4089 };
4090
4091 return io_buffer_blocking_region(io, buffer, io_buffer_write_internal, &argument);
4092}
4093
4094/*
4095 * call-seq: write(io, [offset, [length]]) -> written length or -errno
4096 *
4097 * Perform one write operation of at most +length+ bytes to +io+ from the
4098 * buffer starting at +offset+. A short write is a normal result. If an error
4099 * occurs, return <tt>-errno</tt>.
4100 *
4101 * If +offset+ is not given, it defaults to zero, i.e. the beginning of the
4102 * buffer. If +length+ is not given, it defaults to the size of the buffer
4103 * minus the offset. A zero length is a no-op.
4104 *
4105 * out = File.open('output.txt', 'wb')
4106 * IO::Buffer.for('1234567').write(out, 0, 3)
4107 *
4108 * This leads to +123+ being written into <tt>output.txt</tt>
4109 */
4110static VALUE
4111io_buffer_write(int argc, VALUE *argv, VALUE self)
4112{
4113 rb_check_arity(argc, 1, 3);
4114
4115 VALUE io = argv[0];
4116
4117 size_t offset, length;
4118 io_buffer_extract_offset_length(self, argc-1, argv+1, &offset, &length);
4119
4120 return rb_io_buffer_write(self, io, offset, length);
4121}
4122
4124 // The file descriptor to write to:
4125 int descriptor;
4126 // The base pointer to write from:
4127 const char *base;
4128 // The maximum number of bytes to write:
4129 size_t length;
4130 // The position to write to:
4131 rb_off_t from;
4132};
4133
4134static VALUE
4135io_buffer_pwrite_internal(void *_argument)
4136{
4137 struct io_buffer_pwrite_internal_argument *argument = _argument;
4138 ssize_t result = pwrite(argument->descriptor, argument->base, argument->length, argument->from);
4139
4140 return rb_fiber_scheduler_io_result(result, errno);
4141}
4142
4143VALUE
4144rb_io_buffer_pwrite(VALUE self, VALUE io, rb_off_t from, size_t offset, size_t length)
4145{
4147
4148 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
4149 io_buffer_validate_range(buffer, offset, length);
4150
4151 if (length == 0) return SIZET2NUM(0);
4152
4153 VALUE scheduler = rb_fiber_scheduler_current();
4154 if (scheduler != Qnil) {
4155 VALUE result = rb_fiber_scheduler_io_pwrite(scheduler, io, from, self, offset, length);
4156
4157 if (!UNDEF_P(result)) {
4158 return result;
4159 }
4160
4161 buffer = get_io_buffer_view(self);
4162 io_buffer_validate_range(buffer, offset, length);
4163 }
4164
4165 const void *base;
4166 size_t size;
4167 io_buffer_get_bytes_for_reading(buffer, &base, &size);
4168
4169 RUBY_ASSERT(base != NULL);
4170
4171 struct io_buffer_pwrite_internal_argument argument = {
4172 .descriptor = rb_io_descriptor(io),
4173 .base = (const char*)base + offset,
4174 .length = length,
4175 .from = from,
4176 };
4177
4178 return io_buffer_blocking_region(io, buffer, io_buffer_pwrite_internal, &argument);
4179}
4180
4181/*
4182 * call-seq: pwrite(io, from, [offset, [length]]) -> written length or -errno
4183 *
4184 * Perform one write operation of at most +length+ bytes to +io+ at +from+
4185 * from the buffer starting at +offset+. A short write is a normal result and
4186 * the IO's current position is not modified. If an error occurs, return
4187 * <tt>-errno</tt>.
4188 *
4189 * If +offset+ is not given, it defaults to zero, i.e. the beginning of the
4190 * buffer. If +length+ is not given, it defaults to the size of the buffer
4191 * minus the offset. A zero length is a no-op.
4192 *
4193 * If the +from+ position is beyond the end of the file, the gap will be
4194 * filled with null (0 value) bytes.
4195 *
4196 * out = File.open('output.txt', File::RDWR) # open for read/write, no truncation
4197 * IO::Buffer.for('1234567').pwrite(out, 2, 1, 3)
4198 *
4199 * This leads to +234+ (3 bytes, starting from position 1) being written into
4200 * <tt>output.txt</tt>, starting from file position 2.
4201 */
4202static VALUE
4203io_buffer_pwrite(int argc, VALUE *argv, VALUE self)
4204{
4205 rb_check_arity(argc, 2, 4);
4206
4207 VALUE io = argv[0];
4208 rb_off_t from = NUM2OFFT(argv[1]);
4209
4210 size_t offset, length;
4211 io_buffer_extract_offset_length(self, argc-2, argv+2, &offset, &length);
4212
4213 return rb_io_buffer_pwrite(self, io, from, offset, length);
4214}
4215
4216static inline void
4217io_buffer_check_mask_size(size_t size)
4218{
4219 if (size == 0)
4220 rb_raise(rb_eIOBufferMaskError, "Zero-length mask given!");
4221}
4222
4223static void
4224memory_and(unsigned char * restrict output, const unsigned char * restrict base, size_t size, const unsigned char * restrict mask, size_t mask_size)
4225{
4226 for (size_t offset = 0; offset < size; offset += 1) {
4227 output[offset] = base[offset] & mask[offset % mask_size];
4228 }
4229}
4230
4231/*
4232 * call-seq:
4233 * source & mask -> io_buffer
4234 *
4235 * Generate a new buffer the same size as the source by applying the binary AND
4236 * operation to the source, using the mask, repeating as necessary.
4237 *
4238 * IO::Buffer.for("1234567890") & IO::Buffer.for("\xFF\x00\x00\xFF")
4239 * # =>
4240 * # #<IO::Buffer 0x00005589b2758480+10 INTERNAL>
4241 * # 0x00000000 31 00 00 34 35 00 00 38 39 00 1..45..89.
4242 */
4243static VALUE
4244io_buffer_and(VALUE self, VALUE mask)
4245{
4246 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
4247
4248 struct rb_io_buffer_view *mask_buffer = get_io_buffer_view(mask);
4249
4250 const void *base;
4251 size_t size;
4252 io_buffer_get_bytes_for_reading(buffer, &base, &size);
4253
4254 const void *mask_base;
4255 size_t mask_size;
4256 io_buffer_get_bytes_for_reading(mask_buffer, &mask_base, &mask_size);
4257
4258 io_buffer_check_mask_size(mask_size);
4259
4260 VALUE output = rb_io_buffer_new(NULL, size, io_flags_for_size(size));
4261 struct rb_io_buffer_view *output_buffer = get_io_buffer_view(output);
4262
4263 memory_and(output_buffer->base, base, size, mask_base, mask_size);
4264
4265 return output;
4266}
4267
4268static void
4269memory_or(unsigned char * restrict output, const unsigned char * restrict base, size_t size, const unsigned char * restrict mask, size_t mask_size)
4270{
4271 for (size_t offset = 0; offset < size; offset += 1) {
4272 output[offset] = base[offset] | mask[offset % mask_size];
4273 }
4274}
4275
4276/*
4277 * call-seq:
4278 * source | mask -> io_buffer
4279 *
4280 * Generate a new buffer the same size as the source by applying the binary OR
4281 * operation to the source, using the mask, repeating as necessary.
4282 *
4283 * IO::Buffer.for("1234567890") | IO::Buffer.for("\xFF\x00\x00\xFF")
4284 * # =>
4285 * # #<IO::Buffer 0x0000561785ae3480+10 INTERNAL>
4286 * # 0x00000000 ff 32 33 ff ff 36 37 ff ff 30 .23..67..0
4287 */
4288static VALUE
4289io_buffer_or(VALUE self, VALUE mask)
4290{
4291 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
4292
4293 struct rb_io_buffer_view *mask_buffer = get_io_buffer_view(mask);
4294
4295 const void *base;
4296 size_t size;
4297 io_buffer_get_bytes_for_reading(buffer, &base, &size);
4298
4299 const void *mask_base;
4300 size_t mask_size;
4301 io_buffer_get_bytes_for_reading(mask_buffer, &mask_base, &mask_size);
4302
4303 io_buffer_check_mask_size(mask_size);
4304
4305 VALUE output = rb_io_buffer_new(NULL, size, io_flags_for_size(size));
4306 struct rb_io_buffer_view *output_buffer = get_io_buffer_view(output);
4307
4308 memory_or(output_buffer->base, base, size, mask_base, mask_size);
4309
4310 return output;
4311}
4312
4313static void
4314memory_xor(unsigned char * restrict output, const unsigned char * restrict base, size_t size, const unsigned char * restrict mask, size_t mask_size)
4315{
4316 for (size_t offset = 0; offset < size; offset += 1) {
4317 output[offset] = base[offset] ^ mask[offset % mask_size];
4318 }
4319}
4320
4321/*
4322 * call-seq:
4323 * source ^ mask -> io_buffer
4324 *
4325 * Generate a new buffer the same size as the source by applying the binary XOR
4326 * operation to the source, using the mask, repeating as necessary.
4327 *
4328 * IO::Buffer.for("1234567890") ^ IO::Buffer.for("\xFF\x00\x00\xFF")
4329 * # =>
4330 * # #<IO::Buffer 0x000055a2d5d10480+10 INTERNAL>
4331 * # 0x00000000 ce 32 33 cb ca 36 37 c7 c6 30 .23..67..0
4332 */
4333static VALUE
4334io_buffer_xor(VALUE self, VALUE mask)
4335{
4336 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
4337
4338 struct rb_io_buffer_view *mask_buffer = get_io_buffer_view(mask);
4339
4340 const void *base;
4341 size_t size;
4342 io_buffer_get_bytes_for_reading(buffer, &base, &size);
4343
4344 const void *mask_base;
4345 size_t mask_size;
4346 io_buffer_get_bytes_for_reading(mask_buffer, &mask_base, &mask_size);
4347
4348 io_buffer_check_mask_size(mask_size);
4349
4350 VALUE output = rb_io_buffer_new(NULL, size, io_flags_for_size(size));
4351 struct rb_io_buffer_view *output_buffer = get_io_buffer_view(output);
4352
4353 memory_xor(output_buffer->base, base, size, mask_base, mask_size);
4354
4355 return output;
4356}
4357
4358static void
4359memory_not(unsigned char * restrict output, const unsigned char * restrict base, size_t size)
4360{
4361 for (size_t offset = 0; offset < size; offset += 1) {
4362 output[offset] = ~base[offset];
4363 }
4364}
4365
4366/*
4367 * call-seq:
4368 * ~source -> io_buffer
4369 *
4370 * Generate a new buffer the same size as the source by applying the unary NOT
4371 * operation to the source.
4372 *
4373 * ~IO::Buffer.for("1234567890")
4374 * # =>
4375 * # #<IO::Buffer 0x000055a5ac42f120+10 INTERNAL>
4376 * # 0x00000000 ce cd cc cb ca c9 c8 c7 c6 cf ..........
4377 */
4378static VALUE
4379io_buffer_not(VALUE self)
4380{
4381 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
4382
4383 const void *base;
4384 size_t size;
4385 io_buffer_get_bytes_for_reading(buffer, &base, &size);
4386
4387 VALUE output = rb_io_buffer_new(NULL, size, io_flags_for_size(size));
4388 struct rb_io_buffer_view *output_buffer = get_io_buffer_view(output);
4389
4390 memory_not(output_buffer->base, base, size);
4391
4392 return output;
4393}
4394
4395static inline int
4396io_buffer_overlaps(const struct rb_io_buffer_view *a, const struct rb_io_buffer_view *b)
4397{
4398 // Resolve the current base pointers (following slice indirection):
4399 void *a_base = NULL, *b_base = NULL;
4400 size_t a_size = 0, b_size = 0;
4401 if (!io_buffer_try_get_bytes(a, &a_base, &a_size)) return 0;
4402 if (!io_buffer_try_get_bytes(b, &b_base, &b_size)) return 0;
4403
4404 if (a_size == 0 || b_size == 0 || a_base == NULL || b_base == NULL) return 0;
4405
4406 // Compare integer address differences, without ordering unrelated C
4407 // pointers or constructing end addresses that could overflow.
4408 uintptr_t a_start = (uintptr_t)a_base;
4409 uintptr_t b_start = (uintptr_t)b_base;
4410 if (a_start <= b_start) return b_start - a_start < a_size;
4411 return a_start - b_start < b_size;
4412}
4413
4414static inline void
4415io_buffer_check_overlaps(const struct rb_io_buffer_view *a, const struct rb_io_buffer_view *b)
4416{
4417 if (io_buffer_overlaps(a, b))
4418 rb_raise(rb_eIOBufferMaskError, "Mask overlaps source buffer!");
4419}
4420
4421static void
4422memory_and_inplace(unsigned char * restrict base, size_t size, unsigned char * restrict mask, size_t mask_size)
4423{
4424 for (size_t offset = 0; offset < size; offset += 1) {
4425 base[offset] &= mask[offset % mask_size];
4426 }
4427}
4428
4429/*
4430 * call-seq:
4431 * source.and!(mask) -> io_buffer
4432 *
4433 * Modify the source buffer in place by applying the binary AND
4434 * operation to the source, using the mask, repeating as necessary.
4435 *
4436 * source = IO::Buffer.for("1234567890").dup # Make a read/write copy.
4437 * # =>
4438 * # #<IO::Buffer 0x000056307a0d0c20+10 INTERNAL>
4439 * # 0x00000000 31 32 33 34 35 36 37 38 39 30 1234567890
4440 *
4441 * source.and!(IO::Buffer.for("\xFF\x00\x00\xFF"))
4442 * # =>
4443 * # #<IO::Buffer 0x000056307a0d0c20+10 INTERNAL>
4444 * # 0x00000000 31 00 00 34 35 00 00 38 39 00 1..45..89.
4445 */
4446static VALUE
4447io_buffer_and_inplace(VALUE self, VALUE mask)
4448{
4449 struct rb_io_buffer_view *buffer = get_io_buffer_view_for_writing(self);
4450
4451 struct rb_io_buffer_view *mask_buffer = get_io_buffer_view(mask);
4452
4453 io_buffer_check_mask_size(mask_buffer->size);
4454 io_buffer_check_overlaps(buffer, mask_buffer);
4455
4456 void *base;
4457 size_t size;
4458 io_buffer_get_bytes_for_writing(buffer, &base, &size);
4459
4460 const void *mask_base;
4461 size_t mask_size;
4462 io_buffer_get_bytes_for_reading(mask_buffer, &mask_base, &mask_size);
4463
4464 memory_and_inplace(base, size, (unsigned char *)mask_base, mask_size);
4465
4466 return self;
4467}
4468
4469static void
4470memory_or_inplace(unsigned char * restrict base, size_t size, unsigned char * restrict mask, size_t mask_size)
4471{
4472 for (size_t offset = 0; offset < size; offset += 1) {
4473 base[offset] |= mask[offset % mask_size];
4474 }
4475}
4476
4477/*
4478 * call-seq:
4479 * source.or!(mask) -> io_buffer
4480 *
4481 * Modify the source buffer in place by applying the binary OR
4482 * operation to the source, using the mask, repeating as necessary.
4483 *
4484 * source = IO::Buffer.for("1234567890").dup # Make a read/write copy.
4485 * # =>
4486 * # #<IO::Buffer 0x000056307a272350+10 INTERNAL>
4487 * # 0x00000000 31 32 33 34 35 36 37 38 39 30 1234567890
4488 *
4489 * source.or!(IO::Buffer.for("\xFF\x00\x00\xFF"))
4490 * # =>
4491 * # #<IO::Buffer 0x000056307a272350+10 INTERNAL>
4492 * # 0x00000000 ff 32 33 ff ff 36 37 ff ff 30 .23..67..0
4493 */
4494static VALUE
4495io_buffer_or_inplace(VALUE self, VALUE mask)
4496{
4497 struct rb_io_buffer_view *buffer = get_io_buffer_view_for_writing(self);
4498
4499 struct rb_io_buffer_view *mask_buffer = get_io_buffer_view(mask);
4500
4501 io_buffer_check_mask_size(mask_buffer->size);
4502 io_buffer_check_overlaps(buffer, mask_buffer);
4503
4504 void *base;
4505 size_t size;
4506 io_buffer_get_bytes_for_writing(buffer, &base, &size);
4507
4508 const void *mask_base;
4509 size_t mask_size;
4510 io_buffer_get_bytes_for_reading(mask_buffer, &mask_base, &mask_size);
4511
4512 memory_or_inplace(base, size, (unsigned char *)mask_base, mask_size);
4513
4514 return self;
4515}
4516
4517static void
4518memory_xor_inplace(unsigned char * restrict base, size_t size, unsigned char * restrict mask, size_t mask_size)
4519{
4520 for (size_t offset = 0; offset < size; offset += 1) {
4521 base[offset] ^= mask[offset % mask_size];
4522 }
4523}
4524
4525/*
4526 * call-seq:
4527 * source.xor!(mask) -> io_buffer
4528 *
4529 * Modify the source buffer in place by applying the binary XOR
4530 * operation to the source, using the mask, repeating as necessary.
4531 *
4532 * source = IO::Buffer.for("1234567890").dup # Make a read/write copy.
4533 * # =>
4534 * # #<IO::Buffer 0x000056307a25b3e0+10 INTERNAL>
4535 * # 0x00000000 31 32 33 34 35 36 37 38 39 30 1234567890
4536 *
4537 * source.xor!(IO::Buffer.for("\xFF\x00\x00\xFF"))
4538 * # =>
4539 * # #<IO::Buffer 0x000056307a25b3e0+10 INTERNAL>
4540 * # 0x00000000 ce 32 33 cb ca 36 37 c7 c6 30 .23..67..0
4541 */
4542static VALUE
4543io_buffer_xor_inplace(VALUE self, VALUE mask)
4544{
4545 struct rb_io_buffer_view *buffer = get_io_buffer_view_for_writing(self);
4546
4547 struct rb_io_buffer_view *mask_buffer = get_io_buffer_view(mask);
4548
4549 io_buffer_check_mask_size(mask_buffer->size);
4550 io_buffer_check_overlaps(buffer, mask_buffer);
4551
4552 void *base;
4553 size_t size;
4554 io_buffer_get_bytes_for_writing(buffer, &base, &size);
4555
4556 const void *mask_base;
4557 size_t mask_size;
4558 io_buffer_get_bytes_for_reading(mask_buffer, &mask_base, &mask_size);
4559
4560 memory_xor_inplace(base, size, (unsigned char *)mask_base, mask_size);
4561
4562 return self;
4563}
4564
4565static void
4566memory_not_inplace(unsigned char * restrict base, size_t size)
4567{
4568 for (size_t offset = 0; offset < size; offset += 1) {
4569 base[offset] = ~base[offset];
4570 }
4571}
4572
4573/*
4574 * call-seq:
4575 * source.not! -> io_buffer
4576 *
4577 * Modify the source buffer in place by applying the unary NOT
4578 * operation to the source.
4579 *
4580 * source = IO::Buffer.for("1234567890").dup # Make a read/write copy.
4581 * # =>
4582 * # #<IO::Buffer 0x000056307a33a450+10 INTERNAL>
4583 * # 0x00000000 31 32 33 34 35 36 37 38 39 30 1234567890
4584 *
4585 * source.not!
4586 * # =>
4587 * # #<IO::Buffer 0x000056307a33a450+10 INTERNAL>
4588 * # 0x00000000 ce cd cc cb ca c9 c8 c7 c6 cf ..........
4589 */
4590static VALUE
4591io_buffer_not_inplace(VALUE self)
4592{
4593 struct rb_io_buffer_view *buffer = get_io_buffer_view_for_writing(self);
4594
4595 void *base;
4596 size_t size;
4597 io_buffer_get_bytes_for_writing(buffer, &base, &size);
4598
4599 memory_not_inplace(base, size);
4600
4601 return self;
4602}
4603
4604static size_t
4605memory_bit_count(const unsigned char *base, size_t size)
4606{
4607 size_t count = 0;
4608
4609 // Process 8 bytes at a time for efficiency:
4610 const uint64_t *base64 = (const uint64_t *)base;
4611 size_t count64 = size / 8;
4612 for (size_t i = 0; i < count64; i += 1) {
4613 count += rb_popcount64(base64[i]);
4614 }
4615
4616 // Process any remaining bytes:
4617 size_t remaining = size % 8;
4618 const unsigned char *tail = base + (count64 * 8);
4619 for (size_t i = 0; i < remaining; i += 1) {
4620 count += rb_popcount32(tail[i]);
4621 }
4622
4623 return count;
4624}
4625
4626/*
4627 * call-seq: bit_count([offset, [length]]) -> integer
4628 *
4629 * Returns the number of set bits (1s) in the buffer, also known as the
4630 * Hamming weight or population count. An optional +offset+ and +length+
4631 * can be provided to count bits in a subrange of the buffer.
4632 *
4633 * IO::Buffer.for("\xFF\x00\x0F").bit_count
4634 * # => 12
4635 *
4636 * IO::Buffer.for("\xFF\x00\x0F").bit_count(1, 2)
4637 * # => 4
4638 */
4639static VALUE
4640io_buffer_bit_count(int argc, VALUE *argv, VALUE self)
4641{
4642 rb_check_arity(argc, 0, 2);
4643
4644 size_t offset, length;
4645 struct rb_io_buffer_view *buffer = io_buffer_extract_offset_length(self, argc, argv, &offset, &length);
4646
4647 io_buffer_validate_range(buffer, offset, length);
4648
4649 const void *base;
4650 size_t size;
4651 io_buffer_get_bytes_for_reading(buffer, &base, &size);
4652
4653 if (length == 0) return SIZET2NUM(0);
4654
4655 RUBY_ASSERT(base != NULL);
4656 size_t count = memory_bit_count((const unsigned char *)base + offset, length);
4657
4658 return SIZET2NUM(count);
4659}
4660
4661static bool
4662io_buffer_memory_view_get(VALUE self, rb_memory_view_t *view, int flags)
4663{
4664 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
4665
4666 void *base = NULL;
4667 size_t size = 0;
4668 if (!io_buffer_try_get_bytes(buffer, &base, &size) || base == NULL) {
4669 return false;
4670 }
4671
4672 bool readonly = true;
4673 if (flags & RUBY_MEMORY_VIEW_WRITABLE) {
4674 if (io_buffer_readonly_p(buffer)) {
4675 return false;
4676 } else {
4677 readonly = false;
4678 }
4679 }
4680 rb_memory_view_init_as_byte_array(view, self, base, buffer->size, readonly);
4681 if (flags & RUBY_MEMORY_VIEW_FORMAT) {
4682 view->format = "C";
4683 }
4684 bool request_multi_dimensional = flags & RUBY_MEMORY_VIEW_MULTI_DIMENSIONAL;
4685 bool request_strides =
4686 (flags & RUBY_MEMORY_VIEW_STRIDES) == RUBY_MEMORY_VIEW_STRIDES;
4687 if (request_multi_dimensional || request_strides) {
4688 size_t n_metadata = 0;
4689 if (request_multi_dimensional)
4690 n_metadata++;
4691 if (request_strides)
4692 n_metadata++;
4693 ssize_t *metadata_buffer = ALLOC_N(ssize_t, n_metadata);
4694 size_t i = 0;
4695 if (request_multi_dimensional) {
4696 ssize_t *shape = &metadata_buffer[i];
4697 shape[0] = buffer->size;
4698 view->shape = shape;
4699 i++;
4700 }
4701 if (request_strides) {
4702 ssize_t *strides = &metadata_buffer[i];
4703 strides[0] = 1;
4704 view->strides = strides;
4705 i++;
4706 }
4707 view->private_data = metadata_buffer;
4708 }
4709 io_buffer_lock(buffer);
4710
4711 return true;
4712}
4713
4714static bool
4715io_buffer_memory_view_release(VALUE self, rb_memory_view_t *view)
4716{
4717 rb_io_buffer_unlock(self);
4718 if (view->private_data) {
4719 xfree(view->private_data);
4720 }
4721 return true;
4722}
4723
4724static bool
4725io_buffer_memory_view_available_p(VALUE self)
4726{
4727 struct rb_io_buffer_view *buffer = get_io_buffer_view(self);
4728
4729 void *base = NULL;
4730 size_t size = 0;
4731 return io_buffer_try_get_bytes(buffer, &base, &size) && base != NULL;
4732}
4733
4734static const rb_memory_view_entry_t io_buffer_memory_view_entry = {
4735 .get_func = io_buffer_memory_view_get,
4736 .release_func = io_buffer_memory_view_release,
4737 .available_p_func = io_buffer_memory_view_available_p,
4738};
4739
4740/*
4741 * Document-class: IO::Buffer
4742 *
4743 * IO::Buffer is the common byte-view interface. Its concrete subclasses are
4744 * IO::Buffer::Storage, which manages backing storage, and IO::Buffer::Slice,
4745 * which represents a parent-relative view. Both are IO::Buffer instances.
4746 *
4747 * IO::Buffer.new, IO::Buffer.for, and IO::Buffer.map create Storage objects.
4748 * The abstract base itself cannot be allocated directly. Each factory creates
4749 * one storage-bearing object, with no additional view needed for byte access.
4750 *
4751 * Storage#resize may reallocate; Storage#free and Storage#transfer manage the
4752 * backing storage. Slice#resize and Slice#advance only change a view, and
4753 * Slice never acquires its own storage. Duplicating Storage copies its bytes;
4754 * duplicating a Slice copies its range and source reference without copying
4755 * bytes.
4756 *
4757 * IO::Buffer is an efficient zero-copy buffer for input/output. There are
4758 * typical use cases:
4759 *
4760 * * Create an empty buffer with ::new, fill it with buffer using #copy or
4761 * #set_value, #set_string, get buffer with #get_string or write it directly
4762 * to some file with #write.
4763 * * Create a buffer mapped to some string with ::for, then it could be used
4764 * both for reading with #get_string or #get_value, and writing (writing will
4765 * change the source string, too).
4766 * * Create a buffer mapped to some file with ::map, then it could be used for
4767 * reading and writing the underlying file.
4768 * * Create a string of a fixed size with ::string, then #read into it, or
4769 * modify it using #set_value.
4770 *
4771 * Interaction with string and file memory is performed by efficient low-level
4772 * C mechanisms like `memcpy`.
4773 *
4774 * The class is meant to be an utility for implementing more high-level mechanisms
4775 * like Fiber::Scheduler#io_read and Fiber::Scheduler#io_write and parsing binary
4776 * protocols.
4777 *
4778 * == MemoryView Support
4779 *
4780 * IO::Buffer supports the C-level MemoryView protocol, so C
4781 * extensions can use +rb_memory_view_get()+ to access the buffer's
4782 * memory directly (zero-copy) as a 1-dimensional contiguous array of
4783 * bytes. The memory view is writable if the buffer is not
4784 * #readonly? and +RUBY_MEMORY_VIEW_WRITABLE+ is specified.
4785 *
4786 * While a MemoryView is exported, the buffer is locked.
4787 *
4788 * == Examples of Usage
4789 *
4790 * Empty buffer:
4791 *
4792 * buffer = IO::Buffer.new(8) # create empty 8-byte buffer
4793 * # =>
4794 * # #<IO::Buffer 0x0000555f5d1a5c50+8 INTERNAL>
4795 * # ...
4796 * buffer
4797 * # =>
4798 * # <IO::Buffer 0x0000555f5d156ab0+8 INTERNAL>
4799 * # 0x00000000 00 00 00 00 00 00 00 00
4800 * buffer.set_string('test', 2) # put there bytes of the "test" string, starting from offset 2
4801 * # => 4
4802 * buffer.get_string # get the result
4803 * # => "\x00\x00test\x00\x00"
4804 *
4805 * \Buffer from string:
4806 *
4807 * string = 'data'
4808 * IO::Buffer.for(string) do |buffer|
4809 * buffer
4810 * # =>
4811 * # #<IO::Buffer 0x00007f3f02be9b18+4 SLICE>
4812 * # 0x00000000 64 61 74 61 data
4813 *
4814 * buffer.get_string(2) # read content starting from offset 2
4815 * # => "ta"
4816 * buffer.set_string('---', 1) # write content, starting from offset 1
4817 * # => 3
4818 * buffer
4819 * # =>
4820 * # #<IO::Buffer 0x00007f3f02be9b18+4 SLICE>
4821 * # 0x00000000 64 2d 2d 2d d---
4822 * string # original string changed, too
4823 * # => "d---"
4824 * end
4825 *
4826 * \Buffer from file:
4827 *
4828 * File.write('test.txt', 'test data')
4829 * # => 9
4830 * buffer = IO::Buffer.map(File.open('test.txt'), nil, 0, IO::Buffer::READONLY)
4831 * # =>
4832 * # #<IO::Buffer 0x00007f3f0768c000+9 EXTERNAL MAPPED FILE SHARED READONLY>
4833 * # ...
4834 * buffer.get_string(5, 2) # read 2 bytes, starting from offset 5
4835 * # => "da"
4836 * buffer.set_string('---', 1) # attempt to write
4837 * # in `set_string': Buffer is not writable! (IO::Buffer::AccessError)
4838 *
4839 * # To create writable file-mapped buffer
4840 * # Open file for read-write, pass size, offset, and flags=0
4841 * buffer = IO::Buffer.map(File.open('test.txt', 'r+'), 9, 0, 0)
4842 * buffer.set_string('---', 1)
4843 * # => 3 -- bytes written
4844 * File.read('test.txt')
4845 * # => "t--- data"
4846 *
4847 * <b>The class is experimental and the interface is subject to change, this
4848 * is especially true of file mappings which may be removed entirely in
4849 * the future.</b>
4850 */
4851void
4852Init_IO_Buffer(void)
4853{
4854 rb_cIOBuffer = rb_define_class_under(rb_cIO, "Buffer", rb_cObject);
4855 rb_undef_alloc_func(rb_cIOBuffer);
4856 /*
4857 * Document-class: IO::Buffer::Storage
4858 *
4859 * A buffer that manages backing storage, including internally allocated,
4860 * mapped, String-backed, and borrowed memory. Storage provides Buffer's
4861 * byte-access interface together with allocation resizing, #free, #transfer,
4862 * and storage-specific predicates. It need not own the bytes it references.
4863 *
4864 * IO::Buffer.new, IO::Buffer.for, and IO::Buffer.map create Storage objects.
4865 * The Storage object is directly usable as a buffer; no separate view object
4866 * is needed unless a caller requests a slice. Duplicating Storage copies its
4867 * bytes into independent storage, unlike duplicating an IO::Buffer::Slice.
4868 */
4869 rb_cIOBufferStorage = rb_define_class_under(rb_cIOBuffer, "Storage", rb_cIOBuffer);
4870 /*
4871 * Document-class: IO::Buffer::Slice
4872 *
4873 * A zero-copy, parent-relative view of an IO::Buffer or another Slice.
4874 * Create a view with IO::Buffer#slice or IO::Buffer::Slice.new:
4875 *
4876 * buffer = IO::Buffer.new(6)
4877 * buffer.set_string("abcdef")
4878 * parent = buffer.slice(1, 4)
4879 * child = parent.slice(1, 2)
4880 * child.source.equal?(parent) # => true
4881 * child.get_string # => "cd"
4882 * parent.advance(1)
4883 * child.get_string # => "de"
4884 *
4885 * A slice retains its immediate source and follows that source's current
4886 * view. Its range is valid only while every parent is valid and the range
4887 * fits within its source. Moving the backing allocation does not itself
4888 * invalidate a slice. Shrinking a parent can invalidate descendants;
4889 * growing it again can restore their validity.
4890 *
4891 * Slice inherits Buffer's byte-access interface but does not manage storage.
4892 * Resizing a slice only changes its extent within its parent's bounds, and
4893 * advancing it consumes bytes from the front of its view. Neither operation
4894 * allocates or releases storage. Slice has no +free+ or +transfer+ method,
4895 * nor Storage's predicates such as +mapped?+ or +internal?+.
4896 *
4897 * Writes modify the source's bytes and respect its current permissions.
4898 * Locking a slice protects the backing allocation; +locked?+ reports that
4899 * shared lock state. Locked or read-only views may still be resized or
4900 * advanced, but frozen views cannot change their range. Locking does not
4901 * serialize access to bytes or view metadata.
4902 *
4903 * Duplicating or cloning a Slice copies its view rather than its bytes.
4904 * Both Slice and Storage are subclasses of IO::Buffer.
4905 */
4906 rb_cIOBufferSlice = rb_define_class_under(rb_cIOBuffer, "Slice", rb_cIOBuffer);
4907 rb_define_alloc_func(rb_cIOBufferSlice, io_buffer_slice_allocate);
4908 rb_define_method(rb_cIOBufferSlice, "initialize", io_buffer_slice_initialize, -1);
4909 rb_define_method(rb_cIOBufferSlice, "initialize_copy", io_buffer_slice_initialize_copy, 1);
4910
4911 /* Raised when an operation would resize or re-allocate a locked buffer. */
4912 rb_eIOBufferLockedError = rb_define_class_under(rb_cIOBuffer, "LockedError", rb_eRuntimeError);
4913
4914 /* Raised when the buffer cannot be allocated for some reason, or you try to use a buffer that's not allocated. */
4915 rb_eIOBufferAllocationError = rb_define_class_under(rb_cIOBuffer, "AllocationError", rb_eRuntimeError);
4916
4917 /* Raised when you try to write to a read-only buffer, or resize an external buffer. */
4918 rb_eIOBufferAccessError = rb_define_class_under(rb_cIOBuffer, "AccessError", rb_eRuntimeError);
4919
4920 /* Raised if you try to access a buffer slice which no longer references a valid memory range of the underlying source. */
4921 rb_eIOBufferInvalidatedError = rb_define_class_under(rb_cIOBuffer, "InvalidatedError", rb_eRuntimeError);
4922
4923 /* Raised if the mask given to a binary operation is invalid, e.g. zero length or overlaps the target buffer. */
4924 rb_eIOBufferMaskError = rb_define_class_under(rb_cIOBuffer, "MaskError", rb_eArgError);
4925
4926 rb_define_alloc_func(rb_cIOBufferStorage, rb_io_buffer_type_allocate);
4927 rb_define_singleton_method(rb_cIOBuffer, "new", io_buffer_s_new, -1);
4928 rb_define_singleton_method(rb_cIOBuffer, "for", rb_io_buffer_type_for, 1);
4929 rb_define_singleton_method(rb_cIOBuffer, "string", rb_io_buffer_type_string, 1);
4930
4931#ifdef _WIN32
4932 SYSTEM_INFO info;
4933 GetSystemInfo(&info);
4934 RUBY_IO_BUFFER_PAGE_SIZE = info.dwPageSize;
4935 RUBY_IO_BUFFER_MAP_ALIGNMENT = info.dwAllocationGranularity;
4936#else /* not WIN32 */
4937 RUBY_IO_BUFFER_PAGE_SIZE = sysconf(_SC_PAGESIZE);
4938 RUBY_IO_BUFFER_MAP_ALIGNMENT = RUBY_IO_BUFFER_PAGE_SIZE;
4939#endif
4940
4941 RUBY_IO_BUFFER_DEFAULT_SIZE = io_buffer_default_size(RUBY_IO_BUFFER_PAGE_SIZE);
4942
4943 /* The IO::Buffer interface version. */
4944 rb_define_const(rb_cIOBuffer, "VERSION", INT2NUM(RUBY_IO_BUFFER_VERSION));
4945
4946 /* The operating system page size. Used for efficient page-aligned memory allocations. */
4947 rb_define_const(rb_cIOBuffer, "PAGE_SIZE", SIZET2NUM(RUBY_IO_BUFFER_PAGE_SIZE));
4948
4949 /* The alignment required for file mapping offsets. Mapping sizes do not need to be aligned. */
4950 rb_define_const(rb_cIOBuffer, "MAP_ALIGNMENT", SIZET2NUM(RUBY_IO_BUFFER_MAP_ALIGNMENT));
4951
4952 /* The default buffer size, typically a (small) multiple of the PAGE_SIZE.
4953 Can be explicitly specified by setting the RUBY_IO_BUFFER_DEFAULT_SIZE
4954 environment variable. */
4955 rb_define_const(rb_cIOBuffer, "DEFAULT_SIZE", SIZET2NUM(RUBY_IO_BUFFER_DEFAULT_SIZE));
4956
4957 rb_define_singleton_method(rb_cIOBuffer, "map", io_buffer_map, -1);
4958
4959 // Storage factories belong to Buffer/Storage, not to Slice subclasses.
4960 rb_undef_method(rb_singleton_class(rb_cIOBufferSlice), "for");
4961 rb_undef_method(rb_singleton_class(rb_cIOBufferSlice), "string");
4962 rb_undef_method(rb_singleton_class(rb_cIOBufferSlice), "map");
4963
4964 rb_define_method(rb_cIOBufferStorage, "initialize", rb_io_buffer_initialize, -1);
4965 rb_define_method(rb_cIOBufferStorage, "initialize_copy", rb_io_buffer_initialize_copy, 1);
4966 rb_define_method(rb_cIOBuffer, "inspect", rb_io_buffer_inspect, 0);
4967 rb_define_method(rb_cIOBuffer, "hexdump", rb_io_buffer_hexdump, -1);
4968 rb_define_method(rb_cIOBuffer, "to_s", rb_io_buffer_to_s, 0);
4969 rb_define_method(rb_cIOBuffer, "size", rb_io_buffer_size, 0);
4970 rb_define_method(rb_cIOBuffer, "valid?", rb_io_buffer_valid_p, 0);
4971
4972 rb_define_method(rb_cIOBufferStorage, "transfer", io_buffer_transfer, 0);
4973
4974 /* Indicates that the memory in the buffer is owned by someone else. See #external? for more details. */
4975 rb_define_const(rb_cIOBuffer, "EXTERNAL", RB_INT2NUM(RB_IO_BUFFER_EXTERNAL));
4976
4977 /* Indicates that the memory in the buffer is owned by the buffer. See #internal? for more details. */
4978 rb_define_const(rb_cIOBuffer, "INTERNAL", RB_INT2NUM(RB_IO_BUFFER_INTERNAL));
4979
4980 /* Indicates that the memory in the buffer is mapped by the operating system. See #mapped? for more details. */
4981 rb_define_const(rb_cIOBuffer, "MAPPED", RB_INT2NUM(RB_IO_BUFFER_MAPPED));
4982
4983 /* Indicates that the memory in the buffer is also mapped such that it can be shared with other processes. See #shared? for more details. */
4984 rb_define_const(rb_cIOBuffer, "SHARED", RB_INT2NUM(RB_IO_BUFFER_SHARED));
4985
4986 /* Indicates that the memory in the buffer is mapped privately and changes won't be replicated to the underlying file. See #private? for more details. */
4987 rb_define_const(rb_cIOBuffer, "PRIVATE", RB_INT2NUM(RB_IO_BUFFER_PRIVATE));
4988
4989 /* Indicates that the memory in the buffer is read only, and attempts to modify it will fail. See #readonly? for more details.*/
4990 rb_define_const(rb_cIOBuffer, "READONLY", RB_INT2NUM(RB_IO_BUFFER_READONLY));
4991
4992 /* Refers to little endian byte order, where the least significant byte is stored first. See #get_value for more details. */
4993 rb_define_const(rb_cIOBuffer, "LITTLE_ENDIAN", RB_INT2NUM(RB_IO_BUFFER_LITTLE_ENDIAN));
4994
4995 /* Refers to big endian byte order, where the most significant byte is stored first. See #get_value for more details. */
4996 rb_define_const(rb_cIOBuffer, "BIG_ENDIAN", RB_INT2NUM(RB_IO_BUFFER_BIG_ENDIAN));
4997
4998 /* Refers to the byte order of the host machine. See #get_value for more details. */
4999 rb_define_const(rb_cIOBuffer, "HOST_ENDIAN", RB_INT2NUM(RB_IO_BUFFER_HOST_ENDIAN));
5000
5001 /* Refers to network byte order, which is the same as big endian. See #get_value for more details. */
5002 rb_define_const(rb_cIOBuffer, "NETWORK_ENDIAN", RB_INT2NUM(RB_IO_BUFFER_NETWORK_ENDIAN));
5003
5004 rb_define_method(rb_cIOBuffer, "null?", rb_io_buffer_null_p, 0);
5005 rb_define_method(rb_cIOBuffer, "empty?", rb_io_buffer_empty_p, 0);
5006 rb_define_method(rb_cIOBufferStorage, "external?", rb_io_buffer_external_p, 0);
5007 rb_define_method(rb_cIOBufferStorage, "internal?", rb_io_buffer_internal_p, 0);
5008 rb_define_method(rb_cIOBufferStorage, "mapped?", rb_io_buffer_mapped_p, 0);
5009 rb_define_method(rb_cIOBufferStorage, "shared?", rb_io_buffer_shared_p, 0);
5010 rb_define_method(rb_cIOBuffer, "locked?", rb_io_buffer_locked_p, 0);
5011 rb_define_method(rb_cIOBufferStorage, "private?", rb_io_buffer_private_p, 0);
5012 rb_define_method(rb_cIOBuffer, "readonly?", io_buffer_readonly, 0);
5013
5014 // Locking to prevent changes while using pointer:
5015 // rb_define_method(rb_cIOBuffer, "lock", rb_io_buffer_lock, 0);
5016 // rb_define_method(rb_cIOBuffer, "unlock", rb_io_buffer_unlock, 0);
5017 rb_define_method(rb_cIOBuffer, "locked", rb_io_buffer_locked, 0);
5018
5019 // Manipulation:
5020 rb_define_method(rb_cIOBuffer, "source", io_buffer_source, 0);
5021 rb_define_method(rb_cIOBuffer, "slice", io_buffer_slice, -1);
5022 rb_define_method(rb_cIOBuffer, "<=>", rb_io_buffer_compare, 1);
5023 rb_define_method(rb_cIOBuffer, "==", io_buffer_equal, 1);
5024 rb_define_method(rb_cIOBufferStorage, "resize", io_buffer_resize, 1);
5025 rb_define_method(rb_cIOBufferSlice, "resize", io_buffer_resize, 1);
5026 rb_define_method(rb_cIOBuffer, "advance", io_buffer_advance, 1);
5027 rb_define_method(rb_cIOBuffer, "clear", io_buffer_clear, -1);
5028 rb_define_method(rb_cIOBufferStorage, "free", io_buffer_free, 0);
5029
5030 rb_include_module(rb_cIOBuffer, rb_mComparable);
5031
5032#define IO_BUFFER_DEFINE_DATA_TYPE(name) RB_IO_BUFFER_DATA_TYPE_##name = rb_intern_const(#name)
5033 IO_BUFFER_DEFINE_DATA_TYPE(U8);
5034 IO_BUFFER_DEFINE_DATA_TYPE(S8);
5035
5036 IO_BUFFER_DEFINE_DATA_TYPE(u16);
5037 IO_BUFFER_DEFINE_DATA_TYPE(U16);
5038 IO_BUFFER_DEFINE_DATA_TYPE(s16);
5039 IO_BUFFER_DEFINE_DATA_TYPE(S16);
5040
5041 IO_BUFFER_DEFINE_DATA_TYPE(u32);
5042 IO_BUFFER_DEFINE_DATA_TYPE(U32);
5043 IO_BUFFER_DEFINE_DATA_TYPE(s32);
5044 IO_BUFFER_DEFINE_DATA_TYPE(S32);
5045
5046 IO_BUFFER_DEFINE_DATA_TYPE(u64);
5047 IO_BUFFER_DEFINE_DATA_TYPE(U64);
5048 IO_BUFFER_DEFINE_DATA_TYPE(s64);
5049 IO_BUFFER_DEFINE_DATA_TYPE(S64);
5050
5051 IO_BUFFER_DEFINE_DATA_TYPE(u128);
5052 IO_BUFFER_DEFINE_DATA_TYPE(U128);
5053 IO_BUFFER_DEFINE_DATA_TYPE(s128);
5054 IO_BUFFER_DEFINE_DATA_TYPE(S128);
5055
5056 IO_BUFFER_DEFINE_DATA_TYPE(f32);
5057 IO_BUFFER_DEFINE_DATA_TYPE(F32);
5058 IO_BUFFER_DEFINE_DATA_TYPE(f64);
5059 IO_BUFFER_DEFINE_DATA_TYPE(F64);
5060#undef IO_BUFFER_DEFINE_DATA_TYPE
5061
5062 rb_define_singleton_method(rb_cIOBuffer, "size_of", io_buffer_size_of, 1);
5063
5064 // Data access:
5065 rb_define_method(rb_cIOBuffer, "get_value", io_buffer_get_value, 2);
5066 rb_define_method(rb_cIOBuffer, "get_values", io_buffer_get_values, 2);
5067 rb_define_method(rb_cIOBuffer, "each", io_buffer_each, -1);
5068 rb_define_method(rb_cIOBuffer, "values", io_buffer_values, -1);
5069 rb_define_method(rb_cIOBuffer, "each_byte", io_buffer_each_byte, -1);
5070 rb_define_method(rb_cIOBuffer, "set_value", io_buffer_set_value, 3);
5071 rb_define_method(rb_cIOBuffer, "set_values", io_buffer_set_values, 3);
5072
5073 rb_define_method(rb_cIOBuffer, "copy", io_buffer_copy, -1);
5074
5075 rb_define_method(rb_cIOBuffer, "get_string", io_buffer_get_string, -1);
5076 rb_define_method(rb_cIOBuffer, "set_string", io_buffer_set_string, -1);
5077
5078 // Binary buffer manipulations:
5079 rb_define_method(rb_cIOBuffer, "&", io_buffer_and, 1);
5080 rb_define_method(rb_cIOBuffer, "|", io_buffer_or, 1);
5081 rb_define_method(rb_cIOBuffer, "^", io_buffer_xor, 1);
5082 rb_define_method(rb_cIOBuffer, "~", io_buffer_not, 0);
5083
5084 rb_define_method(rb_cIOBuffer, "and!", io_buffer_and_inplace, 1);
5085 rb_define_method(rb_cIOBuffer, "or!", io_buffer_or_inplace, 1);
5086 rb_define_method(rb_cIOBuffer, "xor!", io_buffer_xor_inplace, 1);
5087 rb_define_method(rb_cIOBuffer, "not!", io_buffer_not_inplace, 0);
5088
5089 rb_define_method(rb_cIOBuffer, "bit_count", io_buffer_bit_count, -1);
5090
5091 // IO operations:
5092 rb_define_method(rb_cIOBuffer, "read", io_buffer_read, -1);
5093 rb_define_method(rb_cIOBuffer, "pread", io_buffer_pread, -1);
5094 rb_define_method(rb_cIOBuffer, "write", io_buffer_write, -1);
5095 rb_define_method(rb_cIOBuffer, "pwrite", io_buffer_pwrite, -1);
5096
5097 // MemoryView:
5098 rb_memory_view_register(rb_cIOBuffer, &io_buffer_memory_view_entry);
5099}
std::string_view view(const pm_buffer_t *buffer PRISM_LIFETIMEBOUND) noexcept
The bytes written to the given buffer so far.
Definition buffer.hpp:49
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
static bool RB_OBJ_FROZEN(VALUE obj)
Checks if an object is frozen.
Definition fl_type.h:714
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1773
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3061
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2907
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1041
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:133
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1708
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define SIZET2NUM
Old name of RB_SIZE2NUM.
Definition size_t.h:62
#define NUM2UINT
Old name of RB_NUM2UINT.
Definition int.h:45
#define STATIC_SYM_P
Old name of RB_STATIC_SYM_P.
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:402
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define NUM2SIZET
Old name of RB_NUM2SIZE.
Definition size_t.h:61
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:474
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
@ RB_WARN_CATEGORY_EXPERIMENTAL
Warning is for experimental features.
Definition error.h:51
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_cIO
IO class.
Definition io.c:178
VALUE rb_class_new_instance_kw(int argc, const VALUE *argv, VALUE klass, int kw_splat)
Identical to rb_class_new_instance(), except you can specify how to handle the last element of the gi...
Definition object.c:2293
static VALUE rb_class_of(VALUE obj)
Object to class mapping function.
Definition globals.h:174
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
VALUE rb_class_inherited_p(VALUE scion, VALUE ascendant)
Determines if the given two modules are relatives.
Definition object.c:1839
VALUE rb_mComparable
Comparable module.
Definition compar.c:19
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
Scheduler APIs.
VALUE rb_fiber_scheduler_current(void)
Identical to rb_fiber_scheduler_get(), except it also returns RUBY_Qnil in case of a blocking fiber.
Definition scheduler.c:581
VALUE rb_fiber_scheduler_io_read(VALUE scheduler, VALUE io, VALUE buffer, size_t offset, size_t length)
Non-blocking read from the passed IO.
Definition scheduler.c:935
VALUE rb_fiber_scheduler_io_pwrite(VALUE scheduler, VALUE io, rb_off_t from, VALUE buffer, size_t offset, size_t length)
Non-blocking write to the passed IO at the specified offset.
Definition scheduler.c:1046
static VALUE rb_fiber_scheduler_io_result(ssize_t result, int error)
Wrap a ssize_t and int errno into a single VALUE.
Definition scheduler.h:52
VALUE rb_fiber_scheduler_io_pread(VALUE scheduler, VALUE io, rb_off_t from, VALUE buffer, size_t offset, size_t length)
Non-blocking read from the passed IO at the specified offset.
Definition scheduler.c:969
VALUE rb_fiber_scheduler_io_write(VALUE scheduler, VALUE io, VALUE buffer, size_t offset, size_t length)
Non-blocking write to the passed IO.
Definition scheduler.c:1012
VALUE rb_ary_entry(VALUE ary, rb_len_t off)
Queries an element of an array.
VALUE rb_ary_new_capa(rb_len_t capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
#define RETURN_ENUMERATOR_KW(obj, argc, argv, kw_splat)
Identical to RETURN_SIZED_ENUMERATOR_KW(), except its size is unknown.
Definition enumerator.h:260
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3949
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1523
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1569
VALUE rb_str_locktmp(VALUE str)
Obtains a "temporary lock" of the string.
VALUE rb_str_buf_new(rb_len_t capa)
Allocates a "string buffer".
Definition string.c:1785
VALUE rb_str_unlocktmp(VALUE str)
Releases a lock formerly obtained by rb_str_locktmp().
Definition string.c:3513
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1539
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:517
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1904
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
ID rb_sym2id(VALUE obj)
Converts an instance of rb_cSymbol into an ID.
Definition symbol.c:1097
VALUE rb_io_get_io(VALUE io)
Identical to rb_io_check_io(), except it raises exceptions on conversion failures.
Definition io.c:821
int rb_io_descriptor(VALUE io)
Returns an integer representing the numeric file descriptor for io.
Definition io.c:3018
#define RB_IO_POINTER(obj, fp)
Queries the underlying IO pointer.
Definition io.h:436
VALUE rb_io_get_write_io(VALUE io)
Queries the tied IO for writing.
Definition io.c:833
void * rb_nogvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2, int flags)
Identical to rb_thread_call_without_gvl(), except it additionally takes "flags" that change the behav...
Definition thread.c:1775
#define RB_NOGVL_OFFLOAD_SAFE
Passing this flag to rb_nogvl() indicates that the passed function is safe to offload to a background...
Definition thread.h:84
#define RB_NUM2INT
Just another name of rb_num2int_inline.
Definition int.h:38
#define RB_UINT2NUM
Just another name of rb_uint2num_inline.
Definition int.h:39
#define RB_INT2NUM
Just another name of rb_int2num_inline.
Definition int.h:37
static unsigned int RB_NUM2UINT(VALUE x)
Converts an instance of rb_cNumeric into C's unsigned int.
Definition int.h:185
#define RB_LL2NUM
Just another name of rb_ll2num_inline.
Definition long_long.h:28
#define RB_ULL2NUM
Just another name of rb_ull2num_inline.
Definition long_long.h:29
#define RB_NUM2ULL
Just another name of rb_num2ull_inline.
Definition long_long.h:33
#define RB_NUM2LL
Just another name of rb_num2ll_inline.
Definition long_long.h:32
VALUE rb_yield_values(int n,...)
Identical to rb_yield(), except it takes variadic number of parameters and pass them to the block.
Definition vm_eval.c:1419
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1396
static VALUE RB_INT2FIX(long i)
Converts a C's long into an instance of rb_cInteger.
Definition len_t.h:99
#define RB_NUM2LEN
Converts an instance of rb_cNumeric into rb_len_t.
Definition len_t.h:50
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
Memory View.
struct rb_memory_view_entry rb_memory_view_entry_t
Operations applied to a specific kind of a memory view.
bool rb_memory_view_register(VALUE klass, const rb_memory_view_entry_t *entry)
Associates the passed class with the passed memory view entry.
bool rb_memory_view_init_as_byte_array(rb_memory_view_t *view, VALUE obj, void *data, const ssize_t len, const bool readonly)
Fill the members of view as an 1-dimensional byte array.
VALUE type(ANYARGS)
ANYARGS-ed function type.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define OFFT2NUM
Converts a C's off_t into an instance of rb_cInteger.
Definition off_t.h:33
#define NUM2OFFT
Converts an instance of rb_cNumeric into C's off_t.
Definition off_t.h:44
std::string_view slice(const pm_parser_t *parser PRISM_LIFETIMEBOUND, pm_location_t location) noexcept
The bytes of source that the given location covers.
Definition parser.hpp:78
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:422
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition rstring.h:450
VALUE rb_str_to_str(VALUE obj)
Identical to rb_check_string_type(), except it raises exceptions in case of conversion failures.
Definition string.c:1846
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:773
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:239
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
Definition scan_args.h:78
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
static bool RB_NIL_P(VALUE obj)
Checks if the given object is nil.
#define RTEST
This is an old name of RB_TEST.
Ruby's IO, metadata and buffers.
Definition io.h:295
A MemoryView structure, rb_memory_view_t, is used for exporting objects' MemoryView.
Definition memory_view.h:77
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:425
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376