[llvm] [ADT] Use data() and size() within StringRef (NFC) (PR #113657)

Kazu Hirata via llvm-commits llvm-commits at lists.llvm.org
Fri Oct 25 10:21:14 PDT 2024


kazutakahirata wrote:

> > This makes it easier to replace Data and Length with
> > std::string_view in the future, which in turn allows us to forward
> > most of StringRef functions to the counterparts in std::string_view.
> 
> I don't understand how this will make future replacement with `std::string_view` easier. This PR only modifies the internal usage inside StringRef. Is the intention to use `std::string_view` as a data member inside `StringRef` or inherit from it?

Yes, I'm planning to have `StringRef` privately inherit from `std::string_view` and expose methods that work in the same way in both `StringRef` and `std::string_view` like:

```
class StringRef : private std::string_view {
public:
  using std::string_view::empty;
  using std::string_view::size;
  using std::string_view::data;
  using std::string_view::begin;
  using std::string_view::end;
  using std::string_view::rbegin;
  using std::string_view::rend;
  :
  :
};
```

Once that's done, the implementation of `StringRef` will look like a TODO list.  Anything that is not `using` is an item that we need to do something about.  For example, `StringRef::substr` is more lenient than `std::string_view::substr`, so we need to fix usage and eventually replace the implementation of `substr` with with `using std::string_view::substr;`.  As another example, we might make `StringRef::edit_ditance` a non-member function.  Eventually, `StringRef` will become a collection of `using` declarations.  Once we reach that point, we can do:

```
using StringRef = std::string_view;
```

which is similar to how we removed `llvm::Optional`.

Coming back to this PR, it is the first step in the journey described above.  Specifically, `data()` and `size()` will let us access the private base class `std::string_view` via:

```
  using std::string_view::size;
  using std::string_view::data;
```

By the way, `StringRef::{starts_with,ends_with}` are fairly popular, but `std::string_view::{starts_with,ends_with}` won't be available until we switch to C++20.  That said, we can still prepare `StringRef` for the eventual transition to `std::string_view`.


https://github.com/llvm/llvm-project/pull/113657


More information about the llvm-commits mailing list