This repository was archived by the owner on Nov 9, 2025. It is now read-only.
feat: add from_utf8_lossy #104
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This function attempts to directly convert the byte slice into a
SmolStr,leveraging its inline storage for small results to avoid heap allocations.
For larger inputs or when the converted string (with replacements) exceeds
the inline capacity, it falls back to a heap-allocated
SmolStr.Performance
This native implementation of
from_utf8_lossyaims to optimize forSmolStr'sunique characteristics, particularly its inline storage. The performance relative
to
String::from_utf8_lossyvaries significantly based on input size and validity.Key Trade-off:
SmolStrcannot achieve zero-copy for small, valid borrowedbyte slices like
Stringcan (viaCow::Borrowed).SmolStrmust copy the bytesinto its internal inline buffer for transient inputs, which introduces overhead.
Benchmarks (for
INLINE_CAP=23):Summary:
SmolStris significantly faster for small, invalid UTF-8 strings because it avoidsString's heap allocation forCow::Ownedresults.SmolStris significantly faster for large, valid UTF-8 strings due to the efficiencyof converting a
&strdirectly into anArc<str>for heap storage.SmolStris slower for small, valid UTF-8 strings because it must copy the bytesinto its inline buffer, whereas
Stringcan return a zero-copyCow::Borrowed.SmolStris generally slower for medium to large, invalid UTF-8 strings, asString::from_utf8_lossyhas a highly optimized heap-based replacement logic that outperforms
SmolStr's current approachfor these scenarios.