From: "Eregon (Benoit Daloze) via ruby-core" <ruby-core@...>
Date: 2023-01-06T12:33:16+00:00
Subject: [ruby-core:111679] [Ruby master Feature#19315] Lazy substrings in CRuby

Issue #19315 has been updated by Eregon (Benoit Daloze).


The documentation of RSTRING_PTR() doesn't specify it returns a \0-terminated `char*`, but it seems assumed in various places and it would likely be a security issue if that's not always \0-terminated.
So RSTRING_PTR() needs to realloc and \0-terminate if RSTRING_END(str) is not already \0 (can be multiple zeros for minwidth > 1 encodings, one way to deal with that is always terminate with 4 \0).

----------------------------------------
Feature #19315: Lazy substrings in CRuby
https://bugs.ruby-lang.org/issues/19315#change-101074

* Author: Eregon (Benoit Daloze)
* Status: Open
* Priority: Normal
----------------------------------------
CRuby should implement lazy substrings, i.e., "abcdef"[1..3] must not copy bytes.

Currently CRuby only reuse the char* if the substring is until the end of the buffer.
But it should also work wherever the substring starts and ends.
Yes, it means RSTRING_PTR() might need to allocate to \0-terminate, so be it, it's worth it.

There is already code for this (`SHARABLE_MIDDLE_SUBSTRING`), but it's disabled by default and `RSTRING_PTR()` needs to be changed to deal with this.
It seems a good idea to introduce a variant of `RSTRING_PTR` which doesn't guarantee \0-termination, so such callers can then use the existing bytes always without copy.

There are countless workarounds for this missing optimization, all not worth and all less readable:
* https://bugs.ruby-lang.org/issues/19314
* https://github.com/ruby/net-protocol/pull/14
* Manual lazy substrings which track string + index + length
* More but I don't remember all now, feel free to comment or link more urls/tickets.



-- 
https://bugs.ruby-lang.org/
 ______________________________________________
 ruby-core mailing list -- ruby-core@ml.ruby-lang.org
 To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org
 ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/