]> git.lizzy.rs Git - rust.git/commit
Rollup merge of #86497 - clarfonthey:nearest_char_boundary, r=scottmcm
authorMatthias Krüger <matthias.krueger@famsik.de>
Tue, 8 Feb 2022 05:47:31 +0000 (06:47 +0100)
committerGitHub <noreply@github.com>
Tue, 8 Feb 2022 05:47:31 +0000 (06:47 +0100)
commit1f841fc5fe4f7c6f6c73de93930c3ee38c5f814b
tree15eea9ca0ac17b89ed6dcc3d6b4c6a467ab5fc57
parente7cc3bddbe0d0e374d05e7003e662bba1742dbae
parentedd318c313763d8c4cf3e8cc339f433832d6454a
Rollup merge of #86497 - clarfonthey:nearest_char_boundary, r=scottmcm

Add {floor,ceil}_char_boundary methods to str

This is technically already used internally by the standard library in the form of `truncate_to_char_boundary`.

Essentially these are two building blocks to allow for approximate string truncation, where you want to cut off the string at "approximately" a given length in bytes but don't know exactly where the character boundaries lie. It's also a good candidate for the standard library as it can easily be done naively, but would be difficult to properly optimise. Although the existing code that's done in error messages is done naively, this code will explicitly only check a window of 4 bytes since we know that a boundary must lie in that range, and because it will make it possible to vectorise.

Although this method doesn't take into account graphemes or other properties, this would still be a required building block for splitting that takes those into account. For example, if you wanted to split at a grapheme boundary, you could take your approximate splitting point and then determine the graphemes immediately following and preceeding the split. If you then notice that these two graphemes could be merged, you can decide to either include the whole grapheme or exclude it depending on whether you decide splitting should shrink or expand the string.

This takes the most conservative approach and just offers the raw indices to the user, and they can decide how to use them. That way, the methods are as useful as possible despite having as few methods as possible.

(Note: I'll add some tests and a tracking issue if it's decided that this is worth including.)