Skip to content

StringIO#getc reads one character in C# (and fixes invalid-byte splitting); cached method arity; one-shot Digest hashing - #92

Merged
Largo merged 3 commits into
masterfrom
ccr-4d94625d-0splsp-a6
Nov 4, 2026
Merged

Largo merged 3 commits into
masterfrom
ccr-4d94625d-0splsp-a6

Conversation

@Largo

@Largo Largo commented Nov 4, 2026

Copy link
Copy Markdown
Owner

This PR has three commits that change code unchanged since the 2016 import, and one of them fixes a correctness bug. It touches no file that the open #84 changes.

1. StringIO character and byte readers (Src/Libraries/StringIO/StringIO.cs, Src/StdLib/ironruby/stringio.rb)

Why it was slow:

  • The 2016 C# getc still returned a single byte as an Integer, its Ruby 1.8 meaning.
  • The Ruby wrapper in stringio.rb built each character from that, one byte at a time, calling pack, force_encoding and valid_encoding? per byte.
  • getbyte was read(1).getbyte(0).

Bug fixed: for bytes that don't form a valid character, the wrapper swallowed up to 4 bytes into one "character", then read a fifth byte and dropped it. A UTF-16 lone surrogate was also mis-split.

CRuby before after
StringIO.new("\xFFabcdef"): getc, getc, pos ["\xFF", "a", 2] ["\xFFabc", "e", 6] ("d" lost) ["\xFF", "a", 2]
StringIO.new("\xE3\x81abc").getc "\xE3" "\xE3\x81ab" "\xE3"

Change: the C# getc now returns a real character, measured the way CRuby measures one (rb_enc_mbclen):

  • An ASCII byte in an ASCII-compatible encoding is one character, and so is any byte in BINARY.
  • UTF-8 is checked against Unicode's well-formedness table.
  • Other encodings take the shortest prefix of up to 4 bytes that valid_encoding? accepts; failing that, one code unit.

The old C# byte reader is kept privately as __ir_readbyte__, and getbyte/readbyte are built on it. No new [RubyMethod] was added, so no initializer regeneration was needed.

µs per character/byte before after CRuby 3.3
getc, ASCII 0.55–0.61 0.085–0.090 0.143
getc, UTF-8 multibyte 1.22–1.33 0.094–0.097 0.126
each_char, ASCII 0.55 ~0.095 0.077
each_char, multibyte ~1.3 ~0.105 0.115
getbyte 0.17–0.24 0.07–0.10 0.037
readbyte ~0.25 0.08–0.11 0.055
readchar ~0.62 0.14–0.23 0.087

2. RubyMethodGroupBase.GetArity

Every Method#arity, UnboundMethod#arity or #parameters on a C#-implemented method re-read all overloads' parameters and their attributes by reflection. A method's overloads never change once set, so the arity is now computed once and cached in an int field.

  • method.arity: 1.1–1.44 → 0.053 µs (CRuby 0.062).
  • parameters: 1.3 → 0.2 µs (CRuby 0.19).

3. Digest

Each Digest object created a .NET HashAlgorithm, which opens a native digest context with a finalizable handle and is reset after every hash. That was ~60 % of SHA256.hexdigest.

  • Change: the built-in algorithms now call the static one-shot HashData, and the hex encoding is cheaper. The (HashAlgorithm, int) constructor stays, because the generated AOT subclass uses it.
  • MD5.hexdigest: 3.5 → 1.1–1.7 µs (CRuby 0.64).
  • SHA256.hexdigest: 4.3–4.8 → 1.3–1.6 µs (CRuby 0.87).
  • new << …; hexdigest: 5.3–7.6 → 1.5–2.0 µs (CRuby 1.44).

Testing (Linux, net8.0, Release)

  • StringIO differential against CRuby: identical values. It covers getc/each_char/getbyte/readchar/readbyte/ungetc, closed streams, set_encoding and frozen strings.
  • StringIO randomized: getc over 4,800 random byte strings in 16 encodings. 87 still differ from CRuby (about 1,600 differed before). All 87 are Big5/EUC-KR cases where IronRuby's own valid_encoding? disagrees with CRuby's encoding tables.
  • Digest differential: identical to CRuby and to the old build, for all five algorithms. It covers digest, hexdigest, base64, the ! variants, reset, dup, ==, file, lengths, a Ruby subclass and hexencode.
  • No new C# regression test: new tests have to be registered in RubyTests.cs, which is one of perf: JIT/OSR for case/when and Hash/Array access, rule-free first calls, precompiled startup library #84's files.
  • Util/run-tests.sh: PASSED, 0 failure lines.
  • ruby/spec: 369 files, 2,071 examples, 0 failures and 0 errors, both before and after; the error/failure lists are identical.
    • Suites: library/{stringio,digest,zlib,openssl,csv,erb,yaml,securerandom}, core/{method,unboundmethod,proc,struct}, kernel/method, io/getc and io/each_char.
    • The "before" run used the old binary with an unmodified copy of Src/StdLib, so it didn't pick up the new stringio.rb.

Generated by Claude Code

…e character each

StringIO#getc, #each_char, #getbyte, #readchar and #readbyte all went through
stringio.rb, which built a character out of the 2016 C# #getc - still the 1.8 byte
reader - one byte at a time: pack("C*"), force_encoding and valid_encoding? per byte,
looping until the bytes made a valid character. That cost 0.5-0.6 us per ASCII
character and 1.2-1.3 us per multibyte one (CRuby: 0.08-0.14), and #getbyte was
read(1).getbyte(0).

It was also wrong for bytes that are not a character. MRI's strio_getc takes
rb_enc_mbclen: the valid character there, or else one code unit. The loop instead
swallowed up to four bytes into one "character", and after the fourth it read a fifth
byte and dropped it:

  StringIO.new("\xFFabcdef") getc, getc, pos
    CRuby  ["\xFF", "a", 2]
    before ["\xFFabc", "e", 6]      ("d" is lost)
  StringIO.new("\xE3\x81abc").getc   CRuby "\xE3", before "\xE3\x81ab"
  UTF-16LE "a\0" "\0\xD8" "b\0"      CRuby 3 chars, before 2 ("\0\xD8b\0")

The C# #getc now answers the character itself: an ASCII byte (in an ASCII-compatible
encoding) or any byte in BINARY is one character; a UTF-8 sequence is measured with
Unicode's well-formedness table (no overlongs, surrogates or > U+10FFFF, as MRI);
any other encoding takes the shortest prefix of up to four bytes that it calls valid
- what String#valid_encoding? says - and otherwise one code unit (2 bytes in UTF-16,
4 in UTF-32). The result carries the stream's bytes, in the external encoding as
before. stringio.rb keeps the C# #readchar (still a byte reader) as the private
__ir_readbyte__ and builds #getbyte (eof? ? nil : byte) and #readbyte on it.

Before/after, us per character or byte, best of 5, 4 passes over 220 KB
(Base / new / CRuby 3.3):
  getc ASCII             0.55-0.61 / 0.085-0.090 / 0.143
  getc UTF-8 multibyte   1.22-1.33 / 0.094-0.097 / 0.126
  each_char ASCII        0.55      / 0.094-0.097 / 0.077
  each_char multibyte    1.23-1.32 / 0.103-0.109 / 0.115
  getbyte                0.17-0.24 / 0.07-0.10   / 0.037
  readbyte               0.24-0.26 / 0.08-0.11   / 0.055
  readchar               0.61-0.63 / 0.14-0.23   / 0.087

Tested: getc/each_char/getbyte/readchar/readbyte/ungetc/closed-stream/set_encoding
cases against CRuby (identical values); a randomized comparison of getc over 4,800
random byte strings in 16 encodings: 87 differ from CRuby, all Big5/EUC-KR strings
where IronRuby's valid_encoding? itself disagrees with CRuby's tables (before: ~1,600
differed). ruby/spec library/stringio, digest, zlib, openssl, csv, erb, yaml,
securerandom, core/method, unboundmethod, proc, struct, io/getc, io/each_char:
2071 examples, 0 failures, same as Base. IronRuby.Tests: PASSED, 0 FAILED.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KPwZf5xqgL3eZiUCWPfG2b
Method#arity, UnboundMethod#arity and #parameters on a C#-implemented method went
to RubyMethodGroupBase.GetArity (2016), which on every call walked each overload's
parameters - GetHiddenParameterCount, IsParamArray, IsOutParameter, IsMandatory, i.e.
reflection over ParameterInfo and its custom attributes. The overloads of a method
group never change once it has them (MethodBases is set once and copies get their
own instance), so the arity is now computed the first time and kept in an int field
(Int32.MinValue meaning not yet computed; a racing second computation stores the
same value).

us/op, best of 5 (Base / new / CRuby 3.3):
  1.method(:+).arity                   1.10-1.44 / 0.053-0.056 / 0.062
  Integer.instance_method(:+).arity    1.19-1.20 / 0.049       / 0.041
  1.method(:+).parameters              1.26-1.37 / 0.20-0.25   / 0.19

Same answers as before for a set of core methods (differential script); ruby/spec
core/method, unboundmethod, proc: 0 failures, same as Base; IronRuby.Tests: PASSED.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KPwZf5xqgL3eZiUCWPfG2b
…object

Every Digest::MD5/SHA1/SHA256/SHA384/SHA512 object created a .NET HashAlgorithm in
its constructor (2016 code). On Linux that opens an OpenSSL EVP context behind a
finalizable SafeHandle, and ComputeHash reinitializes it afterwards; together they
were about 60% of Digest::SHA256.hexdigest(str). Since #update already keeps the
whole input and #finish hashes it in one go, the built-in digests now call the
static one-shot HashData (MD5.HashData etc.) and hold no algorithm object. The
(HashAlgorithm, blockLength) constructor stays for subclasses that bring their own
(the AOT subclass of Digest::Base uses it). Bytes2Hex builds the lowercase hex
directly instead of BitConverter.ToString + Replace("-") + ToLowerInvariant.

us/op, best of 5 (Base / new / CRuby 3.3):
  Digest::MD5.hexdigest("hello world")      3.52-3.62 / 1.08-1.66 / 0.64
  Digest::SHA256.hexdigest("hello world")   4.33-4.76 / 1.34-1.62 / 0.87
  Digest::SHA1.digest("hello world")        2.93-3.37 / 1.16-1.18 / 0.76
  SHA256.new << "abc"; hexdigest            5.27-7.60 / 1.50-1.99 / 1.44

Tested: digest/hexdigest/base64digest/digest!/hexdigest!/reset/dup/==/file/
digest_length/block_length/Ruby subclass/Digest.hexencode for all five algorithms
over several inputs - identical to CRuby and to Base. ruby/spec library/digest,
openssl: 0 failures, same as Base; IronRuby.Tests: PASSED.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KPwZf5xqgL3eZiUCWPfG2b
@coderabbitai

coderabbitai Bot commented Nov 4, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 59 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e2d08a65-32be-4128-8771-06c1697992e7
Commits

Reviewing files that changed from the base of the PR and between aaaaedb and c9260ec.

Files selected for processing: 4
  • Src/Libraries/Digest/Digest.cs
  • Src/Libraries/StringIO/StringIO.cs
  • Src/Ruby/Runtime/Calls/RubyMethodGroupBase.cs
  • Src/StdLib/ironruby/stringio.rb
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@Largo
Largo merged commit b28e706 into master Nov 4, 2026
8 checks passed
Largo added a commit that referenced this pull request Nov 10, 2026
Issue #89 leftovers: EUC-KR table gaps, #92 regression tests, cheaper Thread.new location
Largo added a commit that referenced this pull request Nov 10, 2026
Multibyte encodings: split, validate and scrub as MRI's enc tables do; #92 regression tests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants