Shopify2023-10-18Explainer
Code Ranges: A Deeper Look at Ruby Strings
Summary
Ruby's string model supports mutable and immutable operations, per-object or per-file freezing, and more than 100 encodings, while permitting byte sequences invalid for their attached encoding. This flexibility helps legacy and unusual platforms but makes encoding checks, validity scans, and character-boundary handling part of many operations. To reduce repeated O(n) validation scans, Ruby implementations cache each string's state in a four-valued code range: unknown, 7bit, valid, or broken. The post explains how these values map to public methods, how MRI stores them in two header bits, and how JRuby and TruffleRuby represent them differently. It also describes code ranges as inputs to fast and slow paths and as useful but fallible cache information, especially for native extensions and string-heavy metaprogramming.
Context
Ruby strings combine mutability, freezing, many possible encodings, and the ability to hold byte sequences invalid for an attached encoding. Determining validity or character boundaries can require scanning the string, creating runtime overhead in string operations and in Ruby's broader metaprogramming machinery.
Approach / What changed
The post examines code ranges as cached per-string information, covering the four values, their mapping to public Ruby methods, MRI's compact two-bit representation, and differing representations in JRuby and TruffleRuby. It also discusses how code ranges guide optimized and slow paths and how incorrect cache maintenance can affect correctness.
Takeaways
Ruby code ranges have four mutually exclusive values: ENC_CODERANGE_UNKNOWN, ENC_CODERANGE_7BIT, ENC_CODERANGE_VALID, and ENC_CODERANGE_BROKEN.
MRI stores a string's code range in two object-header bits, so the constants must be compared as enum-like values rather than combined or tested directly as bitmasks.
Code ranges can avoid repeated string scans, but native extensions that fail to update them properly can leave cached information wrong and cause correctness or performance issues.
Source and freshness
- Source
- shopify.engineering
- Published
- Added to Yomu
- Last updated
Summaries are generated from the original by a language model. Check the original before relying on it.
Keep reading
Related reading
The Good Stuff
Paid picks we use ourselves. Links carry a referral code — a subscription through one earns us a commission at no extra cost to you.
The best engineering reads, once a week
One useful email. Unsubscribe anytime.