From: merch-redmine@... Date: 2018-08-10T03:02:11+00:00 Subject: [ruby-core:88413] [Ruby trunk Feature#14975] String#append without changing receiver's encoding Issue #14975 has been updated by jeremyevans0 (Jeremy Evans). Making `String#<<` not change the encoding of the receiver may cause backward compatibility issues (raising an exception where an exception is not currently raised): ~~~ ruby b = 'a'.force_encoding('BINARY') u = "\u00ff".force_encoding('UTF-8') # This currently results in b having UTF-8 encoding, since b is 7-bit. # With this proposal, b would have BINARY encoding. b << u # This doesn't raise exception now, since b is now has UTF-8 encoding. # With this proposal, an exception would be raised, since the # encodings are not compatible can b is no longer 7-bit. u << b ~~~ I think it may be worth adding support for this feature, but it should probably be a new method (maybe `#bconcat` since `#b` already returns a copy with binary encoding) to not break backwards compatibility. ---------------------------------------- Feature #14975: String#append without changing receiver's encoding https://bugs.ruby-lang.org/issues/14975#change-73465 * Author: ioquatix (Samuel Williams) * Status: Open * Priority: Normal * Assignee: * Target version: ---------------------------------------- I'm not sure where this fits in, but in order to avoid garbage and superfluous function calls, is it possible that `String#<<`, `String#concat` or the (proposed) `String#append` can avoid changing the encoding of the receiver? Right now it's very tricky to do this in a way that doesn't require extra allocations. Here is what I do: ```ruby class Buffer < String BINARY = Encoding::BINARY def initialize super force_encoding(BINARY) end def << string if string.encoding == BINARY super(string) else super(string.b) # Requires extra allocation. end return self end alias concat << end ``` When the receiver is binary, but contains byte sequences, appending UTF_8 can fail: ``` "Foobar".b << "F����bar" => "FoobarF����bar" > "F����bar".b << "F����bar" Encoding::CompatibilityError: incompatible character encodings: ASCII-8BIT and UTF-8 ``` So, it's not possible to append data, generally, and then call `force_encoding(Encoding::BINARY)`. One must ensure the string is binary before appending it. It would be nice if there was a solution which didn't require additional allocations/copies/linear scans for what should basically be a `memcpy`. See also: https://bugs.ruby-lang.org/issues/14033 and https://bugs.ruby-lang.org/issues/13626#note-3 There are two options to fix this: 1/ Don't change receiver encoding in any case. 2/ Apply 1, but only when receiver is using `Encoding::BINARY` -- https://bugs.ruby-lang.org/ Unsubscribe: