Commit Graph

146 Commits

Author SHA1 Message Date
Yukihiro "Matz" Matsumoto 8956c5abb5 mruby.h: include mruby/presym.h for all source files
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>
2026-03-09 16:50:58 +09:00
Yukihiro "Matz" Matsumoto 2031ae9f90 random.c: fix rand() with float range producing out-of-range values
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>
2026-02-21 07:12:52 +09:00
Yukihiro "Matz" Matsumoto 71cb3c2e3a class.c: allocate ROM table wrappers per mrb_state
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>
2026-02-20 22:24:31 +09:00
Yukihiro "Matz" Matsumoto 483c155a41 class.c: store aspec in ROM method table entries
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>
2026-02-20 11:44:28 +09:00
Yukihiro "Matz" Matsumoto 20b9002214 class.c: merge conditional methods into ROM tables
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>
2026-02-20 11:05:03 +09:00
Yukihiro "Matz" Matsumoto 8adba34bd9 class.c: auto-set MRB_MT_FUNC in MRB_MT_ENTRY macro
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>
2026-02-20 10:37:06 +09:00
Yukihiro "Matz" Matsumoto 0fab703028 class.c: use linear search for method tables; make ROM entries const
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>
2026-02-20 08:26:05 +09:00
Yukihiro "Matz" Matsumoto bde2202100 class.c: refactor ROM method tables to array-of-structs layout
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>
2026-02-19 23:59:30 +09:00
Yukihiro "Matz" Matsumoto 0ed26f8352 class.c: rename mt_/MT_ to mrb_mt_/MRB_MT_ for non-static identifiers
Follow mruby's naming convention: non-static types, macros, and
functions use the mrb_/MRB_ prefix. Renamed:
- union mt_ptr -> union mrb_mt_ptr
- mt_tbl -> mrb_mt_tbl
- MT_KEY(), MT_FUNC, MT_NOARG, MT_PUBLIC, MT_PRIVATE -> MRB_MT_*
- MT_KEY_SHIFT, MT_READONLY_BIT, MT_REMOVED_P -> MRB_MT_*
- mt_init_rom() -> mrb_mt_init_rom()
File-local static functions and macros in class.c are unchanged.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 15:22:55 +09:00
Yukihiro "Matz" Matsumoto 52c71f5b99 mrbgems: remove MRB_NO_PRESYM guards from additional gems
Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 12:17:43 +09:00
Yukihiro "Matz" Matsumoto 4448b5e227 mruby-random: ROM method tables for Random/Kernel/Array (9 methods)
Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 09:39:37 +09:00
Yukihiro "Matz" Matsumoto e19b107642 mruby-random: fix FPE in rand_i() for large ranges
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>
2025-12-29 12:54:32 +09:00
John Bampton 8558ad40ec Adjust broken license links; clean up Markdown 2025-11-29 01:46:54 +10:00
Yukihiro "Matz" Matsumoto 6dd5f05525 mruby-random: split 64-bit state into two 32-bit values on 32-bit platforms
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>
2025-10-16 17:50:03 +09:00
Yukihiro "Matz" Matsumoto 0082dfb7e5 mruby-random: fix unary minus on unsigned type warning
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>
2025-10-16 16:12:11 +09:00
Yukihiro "Matz" Matsumoto 413446657c mruby-random: update readme to reflect pcg algorithm
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>
2025-10-16 14:56:12 +09:00
Yukihiro "Matz" Matsumoto f1bab01b4c mruby-random: replace xoshiro with pcg for better memory efficiency
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>
2025-10-16 14:56:12 +09:00
Yukihiro "Matz" Matsumoto 5f9808587b mruby-random: simplify unsigned arithmetic in rand_i function
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>
2025-08-22 21:28:26 +09:00
Yukihiro "Matz" Matsumoto 64886fd965 mruby-random: use mrb_alloca in mrb_ary_sample to prevent memory leak
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>
2025-08-14 10:53:10 +09:00
Yukihiro "Matz" Matsumoto b9090b089e random.c: unbiased rand(n), faster bytes, cheaper sample/shuffle
- 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>
2025-08-14 10:53:10 +09:00
Yukihiro "Matz" Matsumoto 07b803e28a docs: replace xml-style markup with markdown in comments
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
2025-08-14 10:52:49 +09:00
Yukihiro "Matz" Matsumoto 7b0ee01310 mruby-random: support bigint in rand method
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>
2025-08-14 10:52:46 +09:00
Yukihiro "Matz" Matsumoto 410516fdff mruby-random: add comprehensive call-seq documentation for missing methods
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
2025-07-16 11:58:59 +09:00
Yukihiro "Matz" Matsumoto c4464fa25a array.c: expose mrb_ary_dup() as a new C API 2025-06-29 20:46:51 +09:00
Yukihiro "Matz" Matsumoto 1b189bc1a2 mruby-random: add README.md
The document is written by Google Jules.
2025-06-14 01:02:52 +09:00
Yukihiro "Matz" Matsumoto 3d2f848e64 mruby-random: Random#rand(nil) should raise TypeError 2025-05-08 17:37:05 +09:00
Yukihiro "Matz" Matsumoto 88e86ee62e mruby-random: update error messages to be compatible with CRuby; #6523 2025-05-08 16:42:33 +09:00
leviongit 7be940942c random.c : treat ranges where r.begin > r.end the same way cruby does 2025-05-04 04:10:39 +02:00
leviongit 98906d5ac9 random.c : fix Random#rand not returning value 2025-05-04 03:48:22 +02:00
leviongit 202c213fe1 random.c : add some tests 2025-05-04 02:44:19 +02:00
leviongit 4390aeb78d random.c : add rand(Range) 2025-05-04 02:44:19 +02:00
Yukihiro "Matz" Matsumoto f7142cd327 mruby-random: make Kernel#srand and #rand private 2025-03-07 17:17:43 +09:00
Yukihiro "Matz" Matsumoto 8f184a356b mruby-random: use presym for initialization 2024-06-14 00:15:25 +09:00
Yukihiro "Matz" Matsumoto cf785a6133 mruby-random: move variable declarations to initialization 2024-05-07 17:57:41 +09:00
leviongit ad62d7809e fix: Array#shuffle(!) result distribution 2024-04-04 20:36:44 +02:00
Yukihiro "Matz" Matsumoto 05e9fa34af mruby-random: rename a conflicting local variable 2024-01-08 19:12:55 +09:00
Yukihiro "Matz" Matsumoto 27c2f9ac38 mruby-random (mrb_ary_sample): reduce the scope of loop variables 2024-01-08 07:23:03 +09:00
Yukihiro "Matz" Matsumoto 78bbf75981 mruby-random/random.c: avoid mrb_get_args() 2023-01-26 11:13:48 +09:00
Yukihiro "Matz" Matsumoto c7f1195ccb mruby-random: fix size of kw symbol arrays 2022-11-30 21:50:08 +09:00
Yukihiro "Matz" Matsumoto dfeda0acc8 random.c: remove Random::DEFAULT. 2022-08-28 08:01:59 +09:00
Yukihiro "Matz" Matsumoto 7dec6e776e mruby-random/random.c: pointer to uint32_t cast may fail with clang. 2022-06-17 10:06:07 +09:00
Yukihiro "Matz" Matsumoto f1d669024a mruby-random/random.c: srand to use pointer address as a seed.
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.
2022-06-17 07:14:29 +09:00
Yukihiro "Matz" Matsumoto 267c26d20b mruby-random/random.c: randomize Random::DEFAULT.
Using time(2) and randomized pointer address. May not work well with old
OSes without process randomiser.
2022-06-17 07:12:12 +09:00
Yukihiro "Matz" Matsumoto 0a63cdd594 mruby-random/random.c: use random: keyword argument.
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.
2022-06-16 11:17:22 +09:00
Yukihiro "Matz" Matsumoto 0a52f171aa mruby-random/random.c: factored out Random argument retrieval. 2022-05-16 14:17:20 +09:00
Yukihiro "Matz" Matsumoto 45f61e3879 class.c (mrb_get_args): remove I specifier (istruct); close #5706 2022-05-07 17:35:45 +09:00
Yukihiro "Matz" Matsumoto 50b1ded350 mruby-random/random.c: use rand_i() extensively. 2022-05-04 08:07:02 +09:00
dearblue 9b9424fe32 Strict acquisition of the Random class given by mrb_get_args()
This is to prevent data corruption of the substituted `Random` instance.
If the `Object::Random` constants are redefined to a different `MRB_TT_ISTRUCT` object class, they can pass `mrb_get_args()` validation.

The following is an example of how the `Array#shuffle` method rewrites the data of a non `Random` instance.

```c
// code.c

#include <mruby.h>
#include <mruby/class.h>
#include <mruby/compile.h>
#include <mruby/istruct.h>

#define EVAL_LIT(MRB, ...) mrb_load_string((MRB), #__VA_ARGS__)

static mrb_value
fake_initialize(mrb_state *mrb, mrb_value self)
{
  char *p = ISTRUCT_PTR(self);

  for (int i = 0; i < ISTRUCT_DATA_SIZE; i++) {
    p[i] = 'A' + i;
  }

  return self;
}

static mrb_value
fake_to_bytes(mrb_state *mrb, mrb_value self)
{
  const char *p = ISTRUCT_PTR(self);
  return mrb_str_new(mrb, p, ISTRUCT_DATA_SIZE);
}

int
main(int argc, char *argv[])
{
  mrb_state *mrb = mrb_open();

  struct RClass *fake = mrb_define_class(mrb, "Fake", mrb->object_class);
  MRB_SET_INSTANCE_TT(fake, MRB_TT_ISTRUCT);
  mrb_define_method(mrb, fake, "initialize", fake_initialize, MRB_ARGS_NONE());
  mrb_define_method(mrb, fake, "to_bytes", fake_to_bytes, MRB_ARGS_NONE());

  EVAL_LIT(mrb,
    Random = Fake \n
    fake = Fake.new \n
    p [fake, fake.to_bytes] \n
    p a = (1..10).to_a \n
    p a.shuffle(fake) \n
    p [fake, fake.to_bytes]
  );

  mrb_close(mrb);

  return 0;
}
```

```console
% `bin/mruby-config --cc --cflags --ldflags` code.c `bin/mruby-config --libs`
% ./a.out
[#<Fake:0x8007d8f20>, "ABCDEFGHIJKLMNOPQRSTUVWX"]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 7, 8, 10, 2, 6, 9, 3, 4, 5]
[#<Fake:0x8007d8f20>, "\xe81{\v\fM\xb0D<\x99\xb1V+l\x84\x86QRSTUVWX"]
```
2022-05-03 13:35:29 +09:00
dearblue 7bb4a57e56 Added Random.#bytes method
ref: https://docs.ruby-lang.org/ja/3.0.0/method/Random/i/bytes.html
2021-10-31 23:36:10 +09:00
dearblue b774832ee1 Make mrb_static_assert() a variable argument
`mrb_static_assert()` extends the macro function to take one or two arguments.
If the argument is other than that, an error will occur.

References:
- static_assert のメッセージ省略を許可 - cpprefjp C++日本語リファレンス
  https://cpprefjp.github.io/lang/cpp17/extending_static_assert.html
- c - Overloading Macro on Number of Arguments - Stack Overflow
  https://stackoverflow.com/a/11763277
2021-10-24 23:11:52 +09:00