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