A non-owning string class (similar to the forthcoming std::string_view) Note that, because a StringRef may be a substring of another string, it may not be null terminated.
| 602 | /// Note that, because a StringRef may be a substring of another string, |
| 603 | /// it may not be null terminated. |
| 604 | class StringRef { |
| 605 | public: |
| 606 | using size_type = std::size_t; |
| 607 | using const_iterator = const char*; |
| 608 | |
| 609 | private: |
| 610 | static constexpr char const* const s_empty = ""; |
| 611 | |
| 612 | char const* m_start = s_empty; |
| 613 | size_type m_size = 0; |
| 614 | |
| 615 | public: // construction |
| 616 | constexpr StringRef() noexcept = default; |
| 617 | |
| 618 | StringRef( char const* rawChars ) noexcept; |
| 619 | |
| 620 | constexpr StringRef( char const* rawChars, size_type size ) noexcept |
| 621 | : m_start( rawChars ), |
| 622 | m_size( size ) |
| 623 | {} |
| 624 | |
| 625 | StringRef( std::string const& stdString ) noexcept |
| 626 | : m_start( stdString.c_str() ), |
| 627 | m_size( stdString.size() ) |
| 628 | {} |
| 629 | |
| 630 | explicit operator std::string() const { |
| 631 | return std::string(m_start, m_size); |
| 632 | } |
| 633 | |
| 634 | public: // operators |
| 635 | auto operator == ( StringRef const& other ) const noexcept -> bool; |
| 636 | auto operator != (StringRef const& other) const noexcept -> bool { |
| 637 | return !(*this == other); |
| 638 | } |
| 639 | |
| 640 | auto operator[] ( size_type index ) const noexcept -> char { |
| 641 | assert(index < m_size); |
| 642 | return m_start[index]; |
| 643 | } |
| 644 | |
| 645 | public: // named queries |
| 646 | constexpr auto empty() const noexcept -> bool { |
| 647 | return m_size == 0; |
| 648 | } |
| 649 | constexpr auto size() const noexcept -> size_type { |
| 650 | return m_size; |
| 651 | } |
| 652 | |
| 653 | // Returns the current start pointer. If the StringRef is not |
| 654 | // null-terminated, throws std::domain_exception |
| 655 | auto c_str() const -> char const*; |
| 656 | |
| 657 | public: // substrings and searches |
| 658 | // Returns a substring of [start, start + length). |
| 659 | // If start + length > size(), then the substring is [start, size()). |
| 660 | // If start > size(), then the substring is empty. |
| 661 | auto substr( size_type start, size_type length ) const noexcept -> StringRef; |
no test coverage detected