rand_range_int() computed `end - begin + 1` in mrb_int before checking
for a reversed or empty range. For extreme bounds the subtraction itself
overflowed mrb_int (UndefinedBehaviorSanitizer signed-integer-overflow),
and the wraparound could turn a reversed range into a positive span,
defeating the guard.
Reject reversed or empty ranges before subtracting, and compute the
candidate count in unsigned arithmetic, so no signed overflow is
possible. A new unsigned uniform sampler draws from the full mrb_int
domain, so valid ranges whose width exceeds MRB_INT_MAX now return a
uniform in-range value instead of nil, matching CRuby.
Co-authored-by: Claude <noreply@anthropic.com>
Since presym is now mandatory, mruby.h includes presym.h so that
MRB_SYM() macros are available everywhere without explicit include.
Remove redundant #include <mruby/presym.h> from all source files.
Co-authored-by: Claude <noreply@anthropic.com>
rand_range_float() incorrectly added +1.0 to span for inclusive
ranges, logic copied from integer range handling. For float ranges,
the span should simply be end-begin without adjustment.
Fixes#6720.
Co-authored-by: Claude <noreply@anthropic.com>
ROM method tables used static mrb_mt_tbl variables shared
across the process. The next pointer in each wrapper was
mutated by mrb_mt_init_rom(), causing cross-state
contamination when multiple mrb_state instances existed.
Allocate mrb_mt_tbl wrappers per-state via mrb_malloc().
The const mrb_mt_entry[] arrays remain static and shared.
Wrappers are tracked in mrb->rom_mt and freed at mrb_close().
Remove MRB_MT_ROM_TAB macro; add MRB_MT_INIT_ROM macro that
auto-computes size and calls the new mrb_mt_init_rom().
Co-authored-by: Claude <noreply@anthropic.com>
Restore MRB_ARGS_* argument specs and ISO section comments to all
709 ROM method table entries. The aspec is encoded in bits 4-27 of
the flags field; MRB_MT_NOARG is now auto-derived from aspec==0.
Add MRB_MT_ENTRY_PRIVATE() macro for private methods (53 entries)
and MRB_MT_ASPEC() accessor for extracting aspec from flags.
Co-authored-by: Claude <noreply@anthropic.com>
Move conditional mrb_define_method_id() calls into ROM entry
arrays using #ifdef guards. With linear search, sizeof in
MRB_MT_ROM_TAB() adjusts automatically after preprocessing.
Cross-class ROM tables (methods a gem defines on a class it does
not own) are reverted to mrb_define_method_id(). Multiple gems
should not add ROM table layers to the same class; each layer
costs a 16-byte mrb_mt_tbl struct in RAM and deepens the lookup
chain. Use mrb_define_method_id() for cross-class methods.
Co-authored-by: Claude <noreply@anthropic.com>
Since ROM table entries are always C functions, have the
MRB_MT_ENTRY() macro set MRB_MT_FUNC automatically. This
simplifies entry definitions across all 32 source files.
Co-authored-by: Claude <noreply@anthropic.com>
Replace binary search with linear scan in mt_get(), mt_put(),
mt_del(), mt_chain_has(), and mrb_mt_foreach(). The method cache
makes repeated lookups O(1), so linear scan on cache misses is
acceptable.
This removes the sorting requirement, allowing ROM entry arrays
to be declared const. On embedded systems, const static data
resides in flash/ROM instead of RAM, saving ~8.4KB for ~700
method entries on 32-bit MCUs.
Co-authored-by: Claude <noreply@anthropic.com>
Replace the parallel-arrays (struct-of-arrays) ROM method table
layout with an array-of-structs layout where each mrb_mt_entry
bundles its function pointer and symbol key together.
New MRB_MT_ENTRY() and MRB_MT_ROM_TAB() macros simplify ROM table
definitions from a 3-part pattern (SIZE define + anonymous struct +
mrb_mt_tbl) to a 2-part pattern (entries array + mrb_mt_tbl).
Internal mt_* functions in class.c are simplified: single memmove/
memcpy operations replace paired key+value operations.
Co-authored-by: Claude <noreply@anthropic.com>
When rand is called with a range exceeding UINT32_MAX (e.g.,
rand(2..4294967297)), the span value could overflow when cast
to uint32_t, causing division by zero in the modulo operation.
Add 64-bit path for MRB_INT64 builds that combines two 32-bit
randoms when the range exceeds 32 bits.
Found by ClusterFuzz (oss-fuzz/mruby_fuzzer).
Co-authored-by: Claude <noreply@anthropic.com>
on 32-bit systems, the rand_state struct with uint64_t state (8 bytes,
8-byte aligned) followed by uint32_t seed_value (4 bytes) resulted in
16 bytes due to padding, exceeding the 12-byte ISTRUCT_DATA_SIZE limit.
this caused the static_assert at line 540 to fail.
split the state field into state_lo and state_hi on MRB_32BIT platforms
to achieve perfect 12-byte alignment (4+4+4) without padding. add
GET_STATE/SET_STATE macros to provide uniform access across platforms.
Co-authored-by: Claude <noreply@anthropic.com>
replace (-rot) with (32 - rot) to avoid msvc warning c4146. both
expressions are equivalent when masked with & 31, but the latter
is clearer and doesn't trigger warnings about negating unsigned values.
Co-authored-by: Claude <noreply@anthropic.com>
updates algorithm section to document the change from xoshiro128++
to PCG-XSH-RR. highlights key benefits including 50% memory reduction,
platform-adaptive optimization, and excellent statistical quality.
Co-authored-by: Claude <noreply@anthropic.com>
replaces xoshiro128++/xorshift96 with PCG-XSH-RR algorithm. PCG uses
64-bit state compared to xoshiro's 128-bit state, reducing memory
footprint by 50% while maintaining excellent statistical quality.
on 32-bit platforms, uses optimized 32-bit multiplier (0xf13283ad)
requiring only 2 multiplies instead of 3. on 64-bit platforms, uses
standard 64-bit multiplier for maximum quality.
all existing tests pass. api compatibility maintained.
Co-authored-by: Claude <noreply@anthropic.com>
Remove intermediate bound variable and cast max directly to uint32_t
where needed for unsigned operations. This eliminates C4146 warning
about unary minus on unsigned type while maintaining the same
mathematical behavior.
Co-authored-by: Claude <noreply@anthropic.com>
Refactor mrb_ary_sample to use mrb_alloca for the 'idx' array. This
ensures that the memory is automatically freed when the C function
returns, preventing a memory leak if an exception is raised during
array manipulation.
Co-authored-by: Gemini <gemini@google.com>
- Replace modulo with rejection sampling in rand_i() to remove modulo bias.
This yields uniform integers in [0, max) and ensures Fisher–Yates
shuffles are truly uniform.
- Speed up Random#bytes by writing 4 bytes per PRNG call (pack a uint32_t)
and add a negative-size check (raise ArgumentError).
- Minor shuffle! tweak: hoist RARRAY_PTR/length out of the loop to avoid
repeated lookups.
- Lower GC pressure in Array#sample(n): collect unique indices in a small
C buffer, then push array elements directly, avoiding temporary Ruby
integers.
Behavioral notes:
- rand(n) and methods depending on it now have unbiased distributions.
- Random#bytes(size) now explicitly rejects negative sizes.
- Other semantics remain unchanged.
Co-authored-by: OpenAI Coding Assistant <noreply@openai.com>
Replace XML-style markup tags in comments with markdown equivalents:
- <code>...</code> to `...` (inline code)
- <tt>...</tt> to `...` (teletype/monospace)
- <i>...</i> to *...* (italics/emphasis)
- +...+ to `...` (parameter/variable references)
Updated 80+ files across core source, headers, mrbgems, and libraries
to use consistent markdown formatting in documentation comments.
Handled edge cases including special characters like <=> operators.
Co-authored-by: Atlassian Rovo Dev
To achieve this, the following changes were made:
- Exported `mrb_bint_size`, `mrb_bint_from_bytes`, and `mrb_bint_sign`
functions from `mruby-bigint` to be used in other mrbgems.
- Modified `mruby-random` to use these new functions to handle Bigint
arguments in the `rand` method.
Co-authored-by: Gemini <gemini@google.com>
Added complete call-seq documentation for 7 missing public methods in the
random gem, improving documentation coverage from 25% to 100%.
Documentation added:
- Random.new: Create new random number generator with optional seed
- Random#rand: Generate random numbers (float, integer, or range)
- Random#srand: Seed the random number generator
- Random#bytes: Generate random byte strings
- Random.rand/rand: Class method and Kernel method for default generator
- Random.srand/srand: Class method and Kernel method for seeding
- Random.bytes: Class method for random bytes using default generator
Each method now includes:
- Clear method signatures with parameter and return types
- Detailed descriptions of random number generation behavior
- Practical examples showing different usage patterns
- Notes about default vs instance generators
- Cross-references between class methods and Kernel methods
- Range and numeric type handling explanations
The existing Array methods (shuffle, shuffle!, sample) were already
well-documented and remain unchanged. This completes the documentation
for all random number generation functionality in mruby, covering both
the Random class API and the traditional Kernel methods.
This significantly improves usability for developers working with
random number generation, cryptographic applications, and statistical
sampling in embedded Ruby environments.
Co-authored-by: Atlassian Rovo Dev
Utilize process randomiser which may not be provided by non Linux OSes.
With those OSes, rand() would return same values if the processes are
invoked within a second.
For Array#sample and Array#shuffle. They used to take optional ordinal
argument for Random object but CRuby uses `random:` keyword argument.
Now mruby is compatible with CRuby here.